From 959332840ce5f3aae7e1472236b8e34f43f337bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:27:12 -0800 Subject: [PATCH 01/42] Live Corners: hovering a corner widget highlights the corner it controls While the pointer is within 5 px of a Live Corners widget (the distance within which a press picks the widget), the canvas draws the cut of the corner that widget controls in a 2 px line of the layer color, under the widgets. It works with every tool that shows the widgets: Selection, Direct Selection and the shape tools. Round, inverted round and chamfer corners are highlighted; a square corner has no cut, so nothing is drawn. No line is drawn while a mouse button is down (a press on the widget or a pan), or where a widget is hidden. CornerWidgets::hovered_cut finds the widget under the pointer and takes its corner's segment from the path as drawn, through the corner sources LiveCorners keeps, so a live rectangle, a live polygon and a plain path with Live Corners all highlight the segment they draw. Docs: docs/mcp.md (Live Corners) and the docs/target-app-parity.md evidence list. Part of #1232, reported by XTRECY-BD. --- crates/tools/src/corners.rs | 29 +++++++++++ crates/tools/src/corners/tests.rs | 74 +++++++++++++++++++++++++++ crates/ui-egui/src/canvas/overlays.rs | 11 ++++ crates/ui-egui/src/canvas/tests.rs | 62 ++++++++++++++++++++++ docs/mcp.md | 4 ++ docs/target-app-parity.md | 1 + 6 files changed, 181 insertions(+) diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index ab234cf507..e741af77f7 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -197,6 +197,35 @@ impl CornerWidgets { out.insert(key.into(), value); Value::Object(out) } + + /// The cut corner whose widget is within `tol` (document units) of `p`, as the path draws it in + /// the document, with the object it belongs to: what the canvas highlights while the pointer + /// is over that widget. `None` away from the widgets and for a corner with no cut. + pub fn hovered_cut(&self, doc: &Document, p: Point, tol: f64) -> Option<(NodeId, BezPath)> { + let (i, k) = self.hit(p, tol)?; + let (id, w) = (self.paths.get(i)?.id, self.widget(i, k)?); + let node = doc.node(id)?; + let NodeKind::Path { path, .. } = &node.kind else { return None }; + let lc = LiveCorners::of(node)?; + let mut out = BezPath::new(); + for (sp, from) in path.subpaths.iter().zip(lc.sources()) { + // A subpath whose anchors do not match its sources gives no cut rather than a wrong one. + if from.len() != sp.anchors.len() { + continue; + } + // A corner's cut is the segment between its two anchors (the last one, for a closed + // subpath's first corner); a square corner is one anchor and has none. + for s in 0..sp.segment_count() { + let (a, b) = (from.get(s), from.get(s + 1).or(from.first())); + if a == Some(&w.corner.index) && b == a { + let c = sp.segment(s); + out.move_to(c.p0); + out.curve_to(c.p1, c.p2, c.p3); + } + } + } + (!out.elements().is_empty()).then_some((id, out)) + } } /// The angle between corner `c`'s sides once `xf` maps them into the document, in degrees. diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index 21b240b453..77c2aff468 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -527,3 +527,77 @@ fn a_pen_path_shows_widgets_on_its_corners_only() { assert_eq!(w.corners(), [1, 2]); assert_eq!(pts(&w)[0], Point::new(290.0, 110.0)); } + +/// The bounds of the cut `w` gives for the pointer at `at`, rounded to 1e-6. +fn hovered_bounds(w: &CornerWidgets, d: &Document, at: Point) -> Option<(NodeId, [f64; 4])> { + let (id, cut) = w.hovered_cut(d, at, 5.0)?; + let b = vectorcraft_geom::Shape::bounding_box(&cut); + Some((id, [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 1e6).round() / 1e6))) +} + +/// #1232: the pointer within a press's reach of a widget gives the cut of the corner that widget +/// controls, for each corner of a rounded rectangle, the first one included; nothing away from +/// the widgets. +#[test] +fn a_widget_under_the_pointer_gives_its_corners_cut() { + let (d, id) = live_rect(20.0, Affine::translate((100.0, 100.0))); + let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap(); + assert_eq!(pts(&w), [Point::new(120.0, 120.0), Point::new(180.0, 120.0), Point::new(180.0, 180.0), Point::new(120.0, 180.0)]); + let cuts = [[100.0, 100.0, 120.0, 120.0], [180.0, 100.0, 200.0, 120.0], [180.0, 180.0, 200.0, 200.0], [100.0, 180.0, 120.0, 200.0]]; + for (at, cut) in pts(&w).into_iter().zip(cuts) { + assert_eq!(hovered_bounds(&w, &d, at + Vec2::new(3.0, -3.0)), Some((id, cut)), "{at:?}"); + } + assert_eq!(hovered_bounds(&w, &d, Point::new(127.0, 120.0)), None, "past a press's reach"); + assert_eq!(hovered_bounds(&w, &d, Point::new(150.0, 150.0)), None); +} + +/// #1232: a square corner has no cut to give, and a plain path cut in one corner gives that +/// corner's cut from its own widget, with the corners Direct Selection shows, for each corner +/// kind. +#[test] +fn a_square_corner_gives_no_cut_and_a_plain_paths_corner_gives_its_own() { + let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0))); + let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap(); + assert_eq!(hovered_bounds(&w, &d, Point::new(110.0, 110.0)), None); + for kind in [CornerKind::Round, CornerKind::InvertedRound, CornerKind::Chamfer] { + let (mut d, id) = doc_with_rect(); + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + vectorcraft_doc::corners::set_corners(path, live, &[2].into(), Some(30.0), Some(kind)); + } + let w = CornerWidgets::of(&d, &selected(id), 1.0, true).unwrap(); + assert_eq!(w.corners(), [0, 1, 2, 3], "{kind:?}"); + assert_eq!(hovered_bounds(&w, &d, Point::new(110.0, 110.0)), None, "{kind:?}: the square top-left corner"); + let at = pts(&w)[2]; + assert_eq!(hovered_bounds(&w, &d, at), Some((id, [170.0, 170.0, 200.0, 200.0])), "{kind:?}"); + } +} + +/// #1232: a live polygon's widget gives its corner's cut, and a widget hidden by Hide Corner +/// Widget for angles greater than gives none at its place. +#[test] +fn a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none() { + let live = + LiveShape::Polygon { radius: 80.0, sides: 6, xf: Affine::translate((200.0, 200.0)), radii: vec![], kinds: vec![], radii_relative: false }; + let (mut d, id) = doc_with(live.to_path(), Some(live)); + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + vectorcraft_doc::corners::set_corners(path, live, &[0].into(), Some(10.0), None); + } + let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap(); + let at = pts(&w)[0]; + let (got, b) = hovered_bounds(&w, &d, at).unwrap(); + assert_eq!(got, id); + // The arc of a 10 pt radius at a 120° corner spans 10 pt between its ends. + let (wide, high) = (b[2] - b[0], b[3] - b[1]); + assert!(wide.max(high) <= 10.5 && wide.max(high) > 5.0, "{b:?}"); + let centre = Point::new((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0); + assert!(centre.distance(at) < 15.0, "{b:?} {at:?}"); + // Sheared by 30°: the rectangle's 120° corners (1 and 3) hide above 100°. + let shear = Affine::translate((100.0, 100.0)) * Affine::new([1.0, 0.0, 30f64.to_radians().tan(), 1.0, 0.0, 0.0]); + let (d, id) = live_rect(10.0, shear); + let all = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap(); + let shown = all.clone().within_angle(100.0).unwrap(); + assert_eq!(shown.corners(), [0, 2]); + assert!(hovered_bounds(&shown, &d, pts(&all)[0]).is_some()); + assert!(hovered_bounds(&all, &d, pts(&all)[1]).is_some(), "shown, the 120° corner has a cut"); + assert_eq!(hovered_bounds(&shown, &d, pts(&all)[1]), None, "hidden, it gives none"); +} diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b4d2d44aac..cdbe089f61 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -10,6 +10,9 @@ use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_pa use super::selection_marks::{MarkOptions, SelectionMarks}; use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; +/// The width (screen px) of the cut corner drawn while the pointer is over its Live Corners widget. +const CORNER_HOVER_WIDTH: f32 = 2.0; + pub(super) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { let Some(h) = app.hover_doc else { return }; // Smart Guides › Object Highlighting: a Smart Guides display option, so it needs them on and Snap to Grid and Pixel Preview off. @@ -229,6 +232,14 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: app.session.prefs.hide_corner_widget_above, ) { + // The pointer within 5 px of a widget, the distance at which a press picks it: the cut + // corner it controls drawn thicker, under the widgets. Not while the tool is busy (from + // the press to the release) or a mouse button is down (a pan drag leaves the tool idle). + let reach = 5.0 / xf.zoom.max(1e-9); + let idle = !app.session.tool_busy() && !p.ctx().input(|i| i.pointer.any_down()); + if let Some((id, cut)) = app.hover_doc.filter(|_| idle).and_then(|h| w.hovered_cut(&st.doc, h, reach)) { + stroke_path(p, &cut, xf, Stroke::new(CORNER_HOVER_WIDTH, c32(st.doc.layer_color(id)))); + } for (id, q) in w.visible_on() { let (sp, color) = (xf.to_screen(q), c32(st.doc.layer_color(id))); p.circle_filled(sp, 3.0, Color32::WHITE); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..c903791964 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6112,6 +6112,68 @@ fn corner_widgets_hide_above_the_preference_angle() { assert_eq!(widgets(&mut app), 0); } +/// #1232: with the pointer over a corner widget, the canvas draws the rounded corner it controls +/// thicker in the layer color, with Direct Selection, the Selection tool and the Rectangle tool. +/// It stops while a mouse button is down (a press on the widget or a pan), when the pointer moves +/// away, and where the widget is hidden by Hide Corner Widget for angles greater than. +#[test] +fn hovering_a_corner_widget_highlights_its_corner() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("object.setLiveShape", &json!({"id": id, "radius": 20})).unwrap(); + let id = vectorcraft_doc::NodeId(id); + let color = c32(app.session.active().unwrap().doc.layer_color(id)); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + for tool in ["directSelection", "selection", "rectangle"] { + app.select_tool(tool); + let st = app.session.active().unwrap(); + let w = vectorcraft_tools::corners::CornerWidgets::of(&st.doc, &st.selection, app.view_info().zoom, tool == "directSelection").unwrap(); + let top_left = w.visible().next().unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(top_left))]); + let drawn = drawn_in(&mut app, &ctx, color, 2.0); + // The top-left arc, from (100, 120) to (120, 100) in the document. + let (from, to) = (xf.to_screen(Point::new(100.0, 120.0)), xf.to_screen(Point::new(120.0, 100.0))); + let inside = egui::Rect::from_two_pos(from, to).expand(0.5); + assert!(drawn.len() > 2 && drawn.iter().all(|q| inside.contains(*q)), "{tool}: {drawn:?}"); + assert!(drawn.iter().any(|q| q.distance(from) < 0.5) && drawn.iter().any(|q| q.distance(to) < 0.5), "{tool}: {drawn:?}"); + // While the button is down on the widget and while it is dragged, the corner is not + // highlighted. + let view = app.view_info(); + let inward = top_left + vectorcraft_geom::Vec2::new(8.0, 8.0); + app.session.pointer(&PointerEvent::new(PointerKind::Down, top_left.x, top_left.y), view).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(top_left))]); + assert!(drawn_in(&mut app, &ctx, color, 2.0).is_empty(), "{tool}: after the press"); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, inward.x, inward.y), view).unwrap(); + assert!(app.session.tool_busy(), "{tool}"); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(inward))]); + assert!(drawn_in(&mut app, &ctx, color, 2.0).is_empty(), "{tool}: during the drag"); + app.session.pointer(&PointerEvent::new(PointerKind::Up, inward.x, inward.y), view).unwrap(); + app.session.execute("edit.undo", &json!({})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(Point::new(150.0, 150.0)))]); + assert!(drawn_in(&mut app, &ctx, color, 2.0).is_empty(), "{tool}: away from the widgets"); + } + // A widget hidden by the angle preference gives no highlight at its place. + app.select_tool("directSelection"); + let st = app.session.active().unwrap(); + let top_left = + vectorcraft_tools::corners::CornerWidgets::of(&st.doc, &st.selection, app.view_info().zoom, true).unwrap().visible().next().unwrap(); + // The middle button down over the widget (a pan, which leaves the tool idle) draws none. + let over = xf.to_screen(top_left); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]); + assert!(!drawn_in(&mut app, &ctx, color, 2.0).is_empty(), "over the widget"); + let middle = |pressed| egui::Event::PointerButton { pos: over, button: egui::PointerButton::Middle, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![middle(true)]); + assert!(!app.session.tool_busy()); + assert!(drawn_in(&mut app, &ctx, color, 2.0).is_empty(), "the middle button down"); + frame(&mut app, &ctx, vec![middle(false)]); + app.session.execute("prefs.set", &json!({"key": "hideCornerWidgetAbove", "value": 80})).unwrap(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(xf.to_screen(top_left))]); + assert!(drawn_in(&mut app, &ctx, color, 2.0).is_empty(), "hidden above the angle"); +} + /// View › Hide Edges hides a live rectangle's corner widgets, and the Selection tool then /// neither shows the corner cursor over one's place nor rounds the corners from it. With /// edges shown, a drag from the same widget rounds them. diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..b3b7b1f168 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7702,6 +7702,10 @@ and those shape tools: hidden widgets are not drawn, and those tools do not answ on them. `on`, when given and not `null`, must be `true` or `false` and sets the state; without it, or with `null`, the command toggles. The reply is the new state (`true` when shown, the default). The bounding box, the center point and Direct Selection's corner widgets, which follow `view.cornerWidget` alone, stay as they are, and no undo step is added. +While the pointer is within 5 px of a corner widget that shows, with any tool that shows it, the desktop app draws the +cut of that widget's corner (round, inverted round or chamfer) in a 2 px line of the layer color. A square corner has +no cut and gets no line, and no line is drawn while a mouse button is down. The 5 px reach, the 2 px width and the +color are VectorCraft's own values. No command runs and no undo step is added. ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"id":12,"corners":[1],"radius":16}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..9734a310bb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1481,6 +1481,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. + With the pointer on a Direct Selection corner widget or close to it, the canvas marks the cut of that widget's corner with a thicker line (#1232). The help page describes this marking of a widget's corner while the pointer is on the widget or close to it ([Live Corners help page, archived](https://web.archive.org/web/2016id_/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, the mark also shows with the Selection tool and the shape tools on the widgets they show, it is a 2 px line of the layer color within 5 px of the widget, a square corner gets none, and none is drawn while a mouse button is down. Tests: `corners::tests::a_widget_under_the_pointer_gives_its_corners_cut`, `corners::tests::a_square_corner_gives_no_cut_and_a_plain_paths_corner_gives_its_own`, `corners::tests::a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none`, `canvas::tests::hovering_a_corner_widget_highlights_its_corner`. - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). From b57d3393eb6f3dc14cfbde0260816440fca08ee0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:09:31 -0800 Subject: [PATCH 02/42] Smooth: a drag's segment search stays within its piece limit however many curved segments are in reach A Smooth drag gave each curved segment in reach at least one measured piece of its share of MAX_REACH_PIECES, measured the whole of every curved segment it passed, counted or not, and charged a segment's own share one piece per call while each halving measured two, so the total grew past the limit when more curved segments than the limit were in reach, and a long curve measured a few pieces more than its share. path.smoothRegion now keeps one count of the pieces the whole drag may measure past the first measurement of each curved segment. A piece is halved only when two pieces are left both in the segment's share and in the drag's count, and both halves are taken from each before either is measured. A drag measures at most 131,072 pieces plus one for each curved segment it searches, the segments in reach still share the search equally whatever order they come in, and a segment searched after the count runs out is still found in reach at its middle or its point nearest the drag. Docs: docs/mcp.md (path.smoothRegion), docs/target-app-parity.md. --- crates/engine/src/cmd/draw2/smooth.rs | 161 ++++++++++++++++++++++---- docs/mcp.md | 5 + docs/target-app-parity.md | 1 + 3 files changed, 142 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..e0a539d2a6 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -402,11 +402,18 @@ fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath { } /// Pieces of curve that one Smooth drag measures against the drag while it searches the segments -/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach, -/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach -/// of the drag. +/// under it ([`reach_samples`]), besides the whole of each curved segment, which is measured once +/// however many there are: a drag measures no more than this many pieces plus one for each curved +/// segment of the paths it searches. Shared equally by the curved segments that come within its +/// reach, it is enough to search 300,000 pt of curve within the default reach of the drag. const MAX_REACH_PIECES: usize = 1 << 17; +#[cfg(test)] +thread_local! { + /// Tests: how many pieces of curve [`reach_samples`] measured against a drag on this thread. + static PIECES_MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The box around the control points of `s`, which holds all of `s`. fn control_box(s: CubicBez) -> Rect { Rect::from_points(s.p0, s.p1).union_pt(s.p2).union_pt(s.p3) @@ -486,13 +493,24 @@ fn segments_in_reach(pd: &PathData, pts: &[Point], radius: f64) -> usize { /// Samples along the part of `c` from `t0` to `t1`, in order: (t, whether the point there is within /// `radius` of the stretches `of` of the drag `pts`). A piece no stretch comes near gives one sample /// out of reach; the others are halved until their control polygon is no longer than half the -/// reach, or until `budget` pieces have been measured, and then give one sample: in reach at the -/// piece's middle or at its place nearest the drag when either is in reach, otherwise out of reach -/// at its middle. Each piece measures only the stretches near +/// reach, or until fewer than the two halves are left in this segment's `budget` or in `shared`, +/// the pieces the whole drag may still measure past the first piece of each segment, and then give +/// one sample: in reach at the piece's middle or at its place nearest the drag when either is in +/// reach, otherwise out of reach at its middle. Both halves of a piece are taken from `budget` and +/// from `shared` before either is measured, so a search measures no more than one piece besides +/// what it takes from them. Each piece measures only the stretches near /// the piece it was cut from, so a long drag along a long curve costs about one pass over the drag /// per halving, plus the stretches near each piece. -fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usize]), radius: f64, budget: &mut usize, out: &mut Vec<(f64, bool)>) { - *budget = budget.saturating_sub(1); +fn reach_samples( + c: CubicBez, + (t0, t1): (f64, f64), + (pts, of): (&[Point], &[usize]), + radius: f64, + (budget, shared): (&mut usize, &mut usize), + out: &mut Vec<(f64, bool)>, +) { + #[cfg(test)] + PIECES_MEASURED.set(PIECES_MEASURED.get() + 1); let s = c.subsegment(t0..t1); let mid = 0.5 * (t0 + t1); let near = stretches_near(pts, of, control_box(s), radius); @@ -501,7 +519,7 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz return; } let len = s.p0.distance(s.p1) + s.p1.distance(s.p2) + s.p2.distance(s.p3); - if len <= (radius / 2.0).max(1e-3) || *budget == 0 || mid <= t0 || mid >= t1 { + if len <= (radius / 2.0).max(1e-3) || *budget < 2 || *shared < 2 || mid <= t0 || mid >= t1 { // The piece's middle, or the place on it nearest the drag when the middle is out of reach. let sample = if dist_to_stretches(pts, &near, c.eval(mid)) <= radius { (mid, true) @@ -512,8 +530,10 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz out.push(sample); return; } - reach_samples(c, (t0, mid), (pts, &near), radius, budget, out); - reach_samples(c, (mid, t1), (pts, &near), radius, budget, out); + *budget -= 2; + *shared -= 2; + reach_samples(c, (t0, mid), (pts, &near), radius, (&mut *budget, &mut *shared), out); + reach_samples(c, (mid, t1), (pts, &near), radius, (budget, shared), out); } /// `sp` cut where the reach `radius` of the drag `pts` crosses its curved segments, and whether each @@ -522,8 +542,11 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz /// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a /// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between /// stay as they are. A segment is searched no more than half the reach apart where it comes within -/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment. -fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubPath, Vec) { +/// the reach of the drag ([`reach_samples`]): each curved segment is measured whole, and then up +/// to `share` more pieces of it are measured while the drag's `shared` pieces last, so the segments +/// in reach share the search equally whatever order they come in, and a segment searched after +/// the pieces run out is still found where its middle or its place nearest the drag is in reach. +fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, (share, shared): (usize, &mut usize)) -> (SubPath, Vec) { let near = |q: Point| dist_to_polyline(pts, q) <= radius; let n = sp.anchors.len(); let marked: Vec = sp.anchors.iter().map(|a| near(a.p)).collect(); @@ -535,7 +558,7 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP } let c = sp.segment(i); let (mut samples, mut budget) = (vec![], share); - reach_samples(c, (0.0, 1.0), (pts, &all), radius, &mut budget, &mut samples); + reach_samples(c, (0.0, 1.0), (pts, &all), radius, (&mut budget, &mut *shared), &mut samples); // Stretches of samples alike, in order: (in reach, first, last). let mut runs: Vec<(bool, usize, usize)> = vec![]; for (k, s) in samples.iter().enumerate() { @@ -580,14 +603,15 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP /// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach. /// A closed path whose first anchor is in reach starts at the point of the refitted path nearest -/// that anchor's place (VectorCraft's own rule). -fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option { +/// that anchor's place (VectorCraft's own rule). `search` is each curved segment's share of the +/// drag's search and the pieces the drag has left ([`mark_reached`]). +fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, search: (usize, &mut usize), tol: f64, sigma: f64) -> Option { if sp.anchors.len() < 2 { return None; } let near = &|q: Point| dist_to_polyline(pts, q) <= radius; // A drag along a segment smooths it even when its anchors are out of reach. - let (sp, marked) = mark_reached(sp, pts, radius, share); + let (sp, marked) = mark_reached(sp, pts, radius, search); let sp = &sp; if !marked.iter().any(|m| *m) { return None; @@ -743,15 +767,17 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) { paths.push((id, path_of(&st.doc, id)?.0)); } - // Each curved segment in reach gets the same share of the search, whatever order they come in. + // Each curved segment in reach gets the same share of the search, whatever order they come in, + // and all of them together measure no more than `MAX_REACH_PIECES` pieces past their first. let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &pts, radius)).sum(); let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1); + let mut shared = MAX_REACH_PIECES; for (id, pd) in paths { let mut changed = false; let subs: Vec = pd .subpaths .iter() - .map(|sp| match smooth_subpath(sp, &pts, radius, share, tol, sigma) { + .map(|sp| match smooth_subpath(sp, &pts, radius, (share, &mut shared), tol, sigma) { Some(n) if n != *sp && n.anchors.len() >= 2 => { changed = true; n @@ -1094,19 +1120,104 @@ mod tests { assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring()); } + /// How many pieces `f` makes [`reach_samples`] measure on this thread. + fn pieces_measured(f: impl FnOnce()) -> usize { + let before = PIECES_MEASURED.get(); + f(); + PIECES_MEASURED.get() - before + } + /// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more - /// pieces than the budget it is given, and a search with none left gives one sample. + /// than one piece besides the drag's `MAX_REACH_PIECES`, counting the pieces it halves as well + /// as those it samples, and a search with none of the drag's pieces left measures the curve + /// once and gives one sample, whatever share of its own it has. #[test] fn searching_a_segment_under_a_drag_stays_within_its_budget() { let c = CubicBez::new(Point::new(0.0, 0.0), Point::new(300000.0, 0.0), Point::new(700000.0, 0.0), Point::new(1000000.0, 0.0)); let pts: Vec = (0..1000).map(|i| Point::new(f64::from(i) * 1000.0, 0.0)).collect(); let all = drag_stretches(&pts); - let mut budget = MAX_REACH_PIECES; + let (mut budget, mut shared) = (MAX_REACH_PIECES, MAX_REACH_PIECES); let (mut first, mut second) = (vec![], vec![]); - reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut first); - reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut second); - assert!(first.len() <= MAX_REACH_PIECES, "{} samples", first.len()); - assert_eq!((budget, second.len()), (0, 1), "the budget is spent, so the next search gives one sample"); + let measured = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut budget, &mut shared), &mut first)); + assert!(measured <= MAX_REACH_PIECES + 1, "{measured} pieces measured"); + assert!(first.len() <= measured && first.len() > 1, "{} samples", first.len()); + assert!(shared < 2, "{shared} pieces left"); + let mut fresh = MAX_REACH_PIECES; + let again = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut fresh, &mut shared), &mut second)); + assert_eq!((again, second.len()), (1, 1), "the drag's pieces are spent, so the next search gives one sample"); + } + + /// One curved segment `w` pt wide from `(x, y)`, bowed `h` pt up. + fn bow((x, y): (f64, f64), w: f64, h: f64) -> CubicBez { + CubicBez::new(Point::new(x, y), Point::new(x + w / 3.0, y + h), Point::new(x + 2.0 * w / 3.0, y + h), Point::new(x + w, y)) + } + + /// An open subpath of the curved segments `segs`, each starting where the one before ends. + fn chain(segs: &[CubicBez]) -> SubPath { + let mut anchors: Vec = vec![]; + for s in segs { + match anchors.last_mut() { + Some(last) => *last = Anchor::with_handles(s.p0, last.h_in, s.p1), + None => anchors.push(Anchor::with_handles(s.p0, s.p0, s.p1)), + } + anchors.push(Anchor::with_handles(s.p3, s.p2, s.p3)); + } + SubPath::new(anchors, false) + } + + /// A drag along two subpaths of 21,845 curved segments 100 pt long each, which share the search + /// three pieces to a segment, and past a third of 1,000 curved segments far from the drag: every + /// segment is measured whole and the whole drag measures no more than `MAX_REACH_PIECES` pieces + /// past those, though each segment in reach would halve its pieces while its share lasts. Each + /// segment in reach, the last one included, is halved once with its share of three, so the + /// segments searched first leave the later ones their share. + #[test] + fn a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each() { + let row = |(x, y): (f64, f64), n: u32| chain(&(0..n).map(|i| bow((x + f64::from(i) * 100.0, y), 100.0, 8.0)).collect::>()); + let subs = [row((0.0, 0.0), 21_845), row((3_000_000.0, 0.0), 21_845), row((0.0, 1e6), 1000)]; + let pts = [Point::new(-10.0, 0.0), Point::new(6_000_000.0, 0.0)]; + let segments: usize = subs.iter().map(SubPath::segment_count).sum(); + assert_eq!(segments, 2 * 21_845 + 1000); + let in_reach = segments_in_reach(&PathData::new(subs.to_vec()), &pts, 12.0); + assert_eq!(in_reach, 2 * 21_845, "the far segments are not counted"); + let share = (MAX_REACH_PIECES / in_reach).max(1); + assert_eq!(share, 3); + let mut shared = MAX_REACH_PIECES; + let mut marks = vec![]; + let measured = pieces_measured(|| { + for sp in &subs { + marks.push(mark_reached(sp, &pts, 12.0, (share, &mut shared)).1); + } + }); + assert!(measured >= segments && measured <= segments + MAX_REACH_PIECES, "{measured} pieces measured for {segments} segments"); + assert_eq!((measured, shared), (segments + 2 * in_reach, MAX_REACH_PIECES - 2 * in_reach), "every segment in reach is halved once"); + assert!(marks[0].iter().all(|m| *m), "the first path's anchors are all on the drag"); + } + + /// More than `MAX_REACH_PIECES` short curved segments in reach are each measured once, and a + /// segment searched after the drag's pieces are spent is still found in reach where only a + /// narrow stretch of it, away from its middle, comes near the drag. + #[test] + fn every_curved_segment_is_searched_after_the_drags_pieces_run_out() { + let n = 140_000; + let tiny = chain(&(0..n).map(|i| bow((f64::from(i) * 4.0, 0.0), 4.0, 1.0)).collect::>()); + let pts = [Point::new(0.0, 0.0), Point::new(f64::from(n) * 4.0, 0.0)]; + let share = (MAX_REACH_PIECES / segments_in_reach(&PathData::single(tiny.clone()), &pts, 12.0).max(1)).max(1); + let mut shared = MAX_REACH_PIECES; + let measured = pieces_measured(|| { + mark_reached(&tiny, &pts, 12.0, (share, &mut shared)); + }); + assert_eq!(measured, 140_000, "each segment is measured whole once"); + // An arch 1,000 pt wide and 300 pt high, with the drag on it a quarter of the way along. + let arch = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 400.0), Point::new(1000.0, 400.0), Point::new(1000.0, 0.0)); + let sp = chain(&[arch]); + let hit = [arch.eval(0.25)]; + assert!(dist_to_polyline(&hit, arch.eval(0.5)) > 12.0, "the arch's middle is out of reach"); + let mut spent = 0; + let (out, marked) = mark_reached(&sp, &hit, 12.0, (MAX_REACH_PIECES, &mut spent)); + assert_eq!(out.anchors.len(), 3, "{out:?}"); + assert_eq!(marked, vec![false, true, false]); + assert!(out.anchors[1].p.distance(hit[0]) <= 12.0, "{out:?}"); } /// A small piece of curve is measured only against the few stretches of a drag of 100,000 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..b80eab886b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7171,6 +7171,11 @@ own, and the corner keeps its place and the directions the path arrives and leav `fidelity`. A call that changes no anchor returns `{ids: [], before: 0, after: 0}` and adds no undo step. The 57.5° threshold is VectorCraft's own value. +`path.smoothRegion` measures each curved segment of the paths it searches once whole against `points`, and cuts all of +them together into no more than 131,072 further pieces while it finds where `radius` reaches them, shared equally by +the segments in reach. A segment searched after those pieces run out is still smoothed where its middle, or its point +nearest `points`, is within `radius`. The limit is VectorCraft's own value. + In the desktop app, Object › Path › Smooth, the canvas context menu's Smooth… (listed while the selection holds a path) and the Contextual Task Bar's Smooth (with a path selected whole with the Direct Selection tool) open the slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` with field `level`) at the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..311bfabf6b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1552,6 +1552,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. + A Smooth drag measures each curved segment of the paths it searches once whole, and cuts all of them together into no more than 131,072 further pieces, shared equally by the segments in its reach, however many curved segments it passes over (`path.smoothRegion`). A segment searched after those pieces run out is still smoothed where its middle, or its point nearest the drag, is in reach. The limit is VectorCraft's own (engine tests `a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each` and `every_curved_segment_is_searched_after_the_drags_pieces_run_out`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). From 16bd590f4105de53fae26635c516a231bd526a1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:10:37 -0800 Subject: [PATCH 03/42] Tangent Circle Tool: Ask For Circle Radius asks for the radius after a click Two new tool options, both off by default. With Ask For Circle Radius (`askRadius`) on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag, which sets the radius itself, still draws at once. Each radius typed previews the circle of that radius nearest the click. A radius with no circle there shows the tool's note and leaves OK off; a radius outside 0.01 to 1000000 pt, other than the one the dialog opened with, is an error. OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default (`autoUpdateDefault`) on, OK also makes the radius given the tool's Shift radius. Both options persist with the tool's radius, show in the tool's options dialog and reject values that are not true or false. Part of #7178. --- crates/tools/src/addons/tangent_circle.rs | 204 +++++++++++++- crates/tools/src/settings.rs | 2 +- crates/ui-egui/src/addons/pathtools.rs | 14 +- .../addons/pathtools/tangent_circle_radius.rs | 259 ++++++++++++++++++ crates/ui-egui/src/addons/pathtools/tests.rs | 14 +- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/dialogs/form.rs | 8 + crates/ui-egui/src/dialogs/tools.rs | 5 + crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + docs/mcp.md | 15 +- docs/target-app-parity.md | 2 + 38 files changed, 560 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index b40cffd8e7..5ccc3815de 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -15,7 +15,10 @@ //! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another //! document, or a change to the first segment that leaves no undo step (a live preview, or one that //! was canceled) forgets the first segment. The circles are looked for again whenever either -//! segment's shape differs from the one they were found on. +//! segment's shape differs from the one they were found on. With the `askRadius` option on, a click +//! on the second segment (not a drag, which sets the radius itself) opens the [`RADIUS_DIALOG`] +//! instead of drawing: it starts at the radius of the circle found and draws the circle of the radius +//! typed ([`radius_circle`]); the first segment stays picked until it does. use kurbo::{CubicBez, Shape}; use serde_json::{Value, json}; @@ -39,6 +42,9 @@ const STEP_PX: f64 = 4.0; const SLOW: f64 = 0.1; /// The note shown over a second segment that gives no circle. pub const NO_CIRCLE: &str = "No tangent circle here"; +/// The dialog a click on the second segment opens with `askRadius` on: its parameters hold the two +/// segments, the click and the circle found ([`radius_circle`]). +pub const RADIUS_DIALOG: &str = "tangentCircleRadius"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; @@ -72,6 +78,10 @@ struct Press { pub struct TangentCircleTool { radius: f64, + /// Whether a click on the second segment asks for the radius (`askRadius`), and whether the + /// radius given there becomes `radius` (`autoUpdateDefault`, which the dialog reads). + ask_radius: bool, + auto_update: bool, first: Option, hover: Option, press: Option, @@ -91,7 +101,19 @@ type CacheKey = (NodeId, usize, usize, Option, CubicBez, Vec); impl Default for TangentCircleTool { fn default() -> Self { - Self { radius: RADIUS, first: None, hover: None, press: None, picking: false, found: None, looked: false, pointer: Point::ZERO, cache: None } + Self { + radius: RADIUS, + ask_radius: false, + auto_update: false, + first: None, + hover: None, + press: None, + picking: false, + found: None, + looked: false, + pointer: Point::ZERO, + cache: None, + } } } @@ -196,6 +218,67 @@ fn segment_path(c: &CubicBez) -> BezPath { bp } +fn point_json(p: Point) -> Value { + json!([p.x, p.y]) +} + +fn curve_json(c: &CubicBez) -> Value { + json!([point_json(c.p0), point_json(c.p1), point_json(c.p2), point_json(c.p3)]) +} + +/// A finite point written by [`point_json`]. +fn point_of(v: &Value) -> Option { + let [x, y] = v.as_array()?.as_slice() else { return None }; + let p = Point::new(x.as_f64()?, y.as_f64()?); + (p.x.is_finite() && p.y.is_finite()).then_some(p) +} + +/// A segment written by [`curve_json`]. +fn curve_of(v: &Value) -> Option { + let [a, b, c, d] = v.as_array()?.as_slice() else { return None }; + Some(CubicBez::new(point_of(a)?, point_of(b)?, point_of(c)?, point_of(d)?)) +} + +/// The [`RADIUS_DIALOG`]'s parameters for circle `c`, found by a click at `at` on `first` and the +/// segments `second`, which `points` (from [`draw`]) draws: the segments, the click, the circle's +/// radius and points, and the tolerance [`draw`] checked them with. +fn dialog_params(first: &CubicBez, second: &[CubicBez], at: Point, c: &SegmentCircle, points: &Value, tol: f64) -> Value { + json!({ + "first": curve_json(first), + "second": second.iter().map(curve_json).collect::>(), + "at": point_json(at), + "radius": c.circle.radius, + "points": points, + "tol": tol, + }) +} + +/// The `shape.circleThroughPoints` parameters that draw the circle of `radius` the [`RADIUS_DIALOG`] +/// opened with parameters `p` gives: at the radius the click found, the circle found; at any other, +/// the circle of `radius` touching the second segments nearest the click, anywhere along the first +/// segment (as with Shift). None for a radius that is not a finite number above 0, when no circle of +/// that radius can be drawn there, or for parameters the tool did not write. +pub fn radius_circle(p: &Value, radius: f64) -> Option { + if !(radius.is_finite() && radius > 0.0) { + return None; + } + if p.get("radius").and_then(Value::as_f64) == Some(radius) { + let points = p.get("points")?; + let [a, b, c] = points.as_array()?.as_slice() else { return None }; + return [a, b, c].into_iter().all(|q| point_of(q).is_some()).then(|| json!({ "points": points })); + } + let first = curve_of(p.get("first")?)?; + // The second segment and at most one on either side of it. + let second: Vec = p.get("second")?.as_array().filter(|s| (1..=3).contains(&s.len()))?.iter().map(curve_of).collect::>()?; + let at = point_of(p.get("at")?)?; + let tol = p.get("tol").and_then(Value::as_f64).filter(|t| t.is_finite() && *t > 0.0)?; + let c = nearest_to(circles_of_radius(first, &second, radius), at, tol)?; + match draw(&c, tol)? { + Action::Exec(_, params) => Some(params), + _ => None, + } +} + impl TangentCircleTool { /// The radius a drag gives, with Shift in round steps. fn shown_radius(cx: &ToolContext, r: f64, shift: bool) -> f64 { @@ -335,14 +418,23 @@ impl Tool for TangentCircleTool { // The release's own position and keys set the radius of a drag. self.drag_to(cx, ev); self.picking = false; - if self.press.take().is_none() { - return vec![]; - } + let Some(press) = self.press.take() else { return vec![] }; // No circle, or one the three points cannot draw: the first segment stays picked, // for another try. It also stays when the command fails: only a drawn circle tells // the tool (`notify`) to forget it. - let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] }; + let tol = cx.tol(DRAW_PX); + let Some((c, action)) = self.found.take().and_then(|c| draw(&c, tol).map(|a| (c, a))) else { return vec![] }; self.looked = false; + // Asked for: a click, not a drag (which set the radius), opens the radius dialog, + // which draws the circle. Until then the first segment stays picked, so Cancel + // leaves it for another try. + if self.ask_radius + && press.radius.is_none() + && let (Some(first), Action::Exec(_, drawn)) = (&self.first, &action) + { + let params = dialog_params(&first.curve, &press.second, press.at, &c, &drawn["points"], tol); + return vec![Action::Dialog(RADIUS_DIALOG.into(), params)]; + } vec![action, Action::Notify(DRAWN.into())] } // The canvas sends a double-click after the second click's `Up`, which drew the circle. @@ -439,14 +531,19 @@ impl Tool for TangentCircleTool { } fn options(&self) -> Value { - json!({ "radius": self.radius }) + json!({ "radius": self.radius, "askRadius": self.ask_radius, "autoUpdateDefault": self.auto_update }) } fn set_option(&mut self, key: &str, v: &Value) { - if key == "radius" - && let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) - { - self.radius = r; + match (key, v) { + ("radius", _) => { + if let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) { + self.radius = r; + } + } + ("askRadius", Value::Bool(b)) => self.ask_radius = *b, + ("autoUpdateDefault", Value::Bool(b)) => self.auto_update = *b, + _ => {} } } @@ -454,6 +551,7 @@ impl Tool for TangentCircleTool { use crate::option_check as c; match key { "radius" => c::number(key, v, RADIUS_RANGE.0, RADIUS_RANGE.1), + "askRadius" | "autoUpdateDefault" => c::boolean(key, v), _ => Err(c::unknown(key)), } } @@ -520,6 +618,90 @@ mod tests { [(a.0, b.0), (a.1, b.1), (a.2, b.2), (a.3, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-4) } + /// The circle `shape.circleThroughPoints` parameters `p` draw, as [`drawn`] gives it. + fn boxed(p: &Value) -> (f64, f64, f64, f64) { + drawn(&[Action::Exec("shape.circleThroughPoints".into(), p.clone()), Action::Notify(DRAWN.into())]) + } + + /// The radius dialog's parameters in `actions`, which hold nothing else. + fn asked(actions: &[Action]) -> Value { + let [Action::Dialog(kind, p)] = actions else { panic!("{actions:?}") }; + assert_eq!(kind, RADIUS_DIALOG); + p.clone() + } + + #[test] + fn ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!((t.options()["askRadius"].clone(), t.options()["autoUpdateDefault"].clone()), (json!(false), json!(false))); + for key in ["askRadius", "autoUpdateDefault"] { + assert_eq!(t.check_option(key, &json!(true)), Ok(())); + for bad in [json!(1), json!("true"), Value::Null] { + assert_eq!(t.check_option(key, &bad), Err(format!("`{key}` must be true or false")), "{bad}"); + t.set_option(key, &bad); + assert_eq!(t.options()[key], json!(false), "{bad}"); + } + t.set_option(key, &json!(true)); + assert_eq!(t.options()[key], json!(true)); + } + // A click on the second line: the dialog, at the click's circle (radius 20), and nothing + // drawn yet; the first segment stays picked. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let p = asked(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert!((p["radius"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{p}"); + assert!(t.first.is_some() && !t.busy()); + let r = p["radius"].as_f64().unwrap(); + assert!(close(boxed(&radius_circle(&p, r).unwrap()), (130.0, 100.0, 40.0, 40.0)), "{p}"); + // Lines 40 pt apart take no other radius; nor is there a circle without a radius above 0. + for no in [25.0, 0.0, -20.0, f64::NAN, f64::INFINITY] { + assert_eq!(radius_circle(&p, no), None, "{no}"); + } + // Shift on the L's corner: the dialog at the tool's radius, and another radius gives that + // radius's fillet. + t.key(&cx, ToolKey::Escape, Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let p = asked(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0))); + assert_eq!(p["radius"], json!(RADIUS)); + assert!(close(boxed(&radius_circle(&p, RADIUS).unwrap()), (300.0 - 72.0, 300.0, 72.0, 72.0)), "{p}"); + assert!(close(boxed(&radius_circle(&p, 10.0).unwrap()), (280.0, 300.0, 20.0, 20.0)), "{p}"); + // Parameters the tool did not write give no circle. + assert_eq!(radius_circle(&json!({}), 10.0), None); + let second = p["second"].as_array().unwrap()[0].clone(); + for (key, bad) in [ + ("second", json!([])), + ("second", json!([second, second, second, second])), + ("at", json!([1.0])), + ("tol", json!(0)), + ("first", json!("x")), + ("points", json!([[0, 0]])), + ] { + let mut q = p.clone(); + q[key] = bad; + let r = if key == "points" { RADIUS } else { 10.0 }; + assert_eq!(radius_circle(&q, r), None, "{key}"); + } + // A drag sets the radius itself: drawn at once, with no dialog. + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 365.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 300.0, 365.0)); + assert!(close(drawn(&released), (300.0 - 30.0, 300.0, 30.0, 30.0)), "{released:?}"); + assert!(t.first.is_none()); + // A click that finds no circle opens no dialog. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0)); + assert!(t.pointer(&cx, &shifted(PointerKind::Up, 200.0, 139.0)).is_empty()); + assert!(t.first.is_some()); + } + #[test] fn two_clicks_draw_the_circle_tangent_at_the_first_click() { let d = doc(); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 1d9d8c4a54..3576d03379 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -108,7 +108,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius"]), + (&[crate::addons::tangent_circle::ID], None, &["radius", "askRadius", "autoUpdateDefault"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 3e7b864c05..f1933770bb 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -3,8 +3,9 @@ //! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle… and Add Bounding Circle…; the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel -//! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and -//! `tool.setOption`. +//! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog +//! ([`tangent_circle_radius`]). Everything acts through `addon.pathtools.*` and `tool.setOption`, except that the radius +//! dialog draws its circle with `shape.circleThroughPoints`. pub mod bridge; pub mod corner; @@ -13,6 +14,7 @@ pub mod set_corners; pub mod shape; pub mod shared_edge; pub mod tangent_circle; +pub mod tangent_circle_radius; use egui::Ui; use serde_json::{Map, Value, json}; @@ -245,6 +247,14 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { d.fields.insert("radius".into(), json!(x)); } }); + if widgets::check(ui, tl!("Ask For Circle Radius"), d.bool("askRadius"), true) { + let on = !d.bool("askRadius"); + d.fields.insert("askRadius".into(), json!(on)); + } + if widgets::check(ui, tl!("Auto-Update Default"), d.bool("autoUpdateDefault"), true) { + let on = !d.bool("autoUpdateDefault"); + d.fields.insert("autoUpdateDefault".into(), json!(on)); + } return false; } let rows = [ diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs new file mode 100644 index 0000000000..bc1b6d5992 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -0,0 +1,259 @@ +//! The Tangent Circle Tool's radius dialog, which a click on the second segment opens when the +//! tool's Ask For Circle Radius option is on. It starts at the radius of the circle the click found, +//! and each radius previews on the canvas the circle of that radius touching the two segments +//! nearest the click ([`tangent_circle::radius_circle`]). A radius that gives no circle there shows +//! the tool's note and leaves OK off. OK draws the circle with `shape.circleThroughPoints` in one +//! undo step, and with Auto-Update Default on also sets the tool's `radius` to the one given; Cancel +//! draws nothing. + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_tools::addons::tangent_circle; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::widgets; + +/// The dialog's kind. +pub const KIND: &str = tangent_circle::RADIUS_DIALOG; +/// The command that draws the circle. +const DRAW: &str = "shape.circleThroughPoints"; +const LABEL_W: f32 = 60.0; +const FIELD_W: f32 = 90.0; +/// What the tool found (a private field): the segments, the click and its circle. +const CLICK: &str = "__click"; +/// The radius the circle was last looked for at, and the circle's parameters for [`DRAW`] (null: +/// none) (private fields). +const TRIED: &str = "__tried"; +const CIRCLE: &str = "__circle"; +/// The error for a radius outside the tool's range. +const RADIUS_RANGE: &str = "`radius` must be from 0.01 to 1000000 pt"; + +/// Open the dialog on what the tool found (its [`tangent_circle::RADIUS_DIALOG`] parameters). +pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { + let radius = p.get("radius").cloned().unwrap_or(json!(tangent_circle::RADIUS)); + app.ui.dialog = Some(Dialog::new(KIND, json!({ "radius": radius, "preview": true, CLICK: p }))); +} + +pub(crate) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Tangent Circle").to_string(), + body, + confirm, + preview: true, + ok_enabled: Some(|_, d| circle_of(d).is_some_and(|c| c.is_ok_and(|c| c.is_some()))), + min_width: 280.0, + ..DialogSpec::FORM +}; + +/// Whether `r` is in the tool's radius range. +fn in_range(r: f64) -> bool { + let (lo, hi) = tangent_circle::RADIUS_RANGE; + (lo..=hi).contains(&r) +} + +/// The radius typed, when it is in the tool's range or is the radius of the circle the click found +/// (which a click without Shift may find outside that range). +fn radius(d: &Dialog) -> Result { + let found = d.fields.get(CLICK).and_then(|p| p.get("radius")).and_then(Value::as_f64); + d.fields.get("radius").and_then(Value::as_f64).filter(|r| in_range(*r) || Some(*r) == found).ok_or_else(|| RADIUS_RANGE.to_string()) +} + +/// The circle last looked for, when it was looked for at the radius the dialog holds: its [`DRAW`] +/// parameters, or none. +fn circle_of(d: &Dialog) -> Option, String>> { + let r = match radius(d) { + Ok(r) => r, + Err(e) => return Some(Err(e)), + }; + (d.fields.get(TRIED).and_then(Value::as_f64) == Some(r)).then(|| Ok(d.fields.get(CIRCLE).filter(|c| !c.is_null()).cloned())) +} + +/// The circle at the radius the dialog holds, looked for again only when the radius changed. +fn circle(d: &mut Dialog) -> Result, String> { + if let Some(found) = circle_of(d) { + return found; + } + let r = radius(d)?; + let found = d.fields.get(CLICK).and_then(|p| tangent_circle::radius_circle(p, r)); + d.fields.insert(TRIED.into(), json!(r)); + d.fields.insert(CIRCLE.into(), found.clone().unwrap_or(Value::Null)); + Ok(found) +} + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + let (lo, hi) = tangent_circle::RADIUS_RANGE; + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + form::length_within(ui, d, "radius", unit, FIELD_W, Some(lo..=hi)); + }); + let note = match circle(d) { + Ok(Some(points)) => { + form::preview_without_check(app, d, "Tangent Circle", DRAW, points); + return false; + } + Ok(None) => tl!(tangent_circle::NO_CIRCLE).to_string(), + Err(e) => crate::i18n::msg(&e), + }; + form::rollback_preview(app, d); + ui.add_space(6.0); + ui.label(egui::RichText::new(note).color(Tokens::get(ui.ctx()).error)); + false +} + +/// OK: draw the circle (keeping its preview) and close; with Auto-Update Default on, the radius +/// becomes the tool's when it is in the tool's range. Without a circle the dialog stays open. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut d = d.clone(); + let r = radius(&d)?; + let points = circle(&mut d)?.ok_or_else(|| tangent_circle::NO_CIRCLE.to_string())?; + let auto = app.session.tool_options_of(tangent_circle::ID).get("autoUpdateDefault").and_then(Value::as_bool) == Some(true); + form::commit_preview(app, DRAW, points)?; + if auto && in_range(r) { + app.run("tool.setOption", json!({ "tool": tangent_circle::ID, "key": "radius", "value": r }))?; + } + Ok(Value::Null) +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + use vectorcraft_engine::{Session, ViewInfo}; + use vectorcraft_tools::addons::tangent_circle as tool; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + use crate::VectorcraftApp; + use crate::tests_labels::painted_text; + + fn count(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers[0].children().unwrap().len() + } + + fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// A click with the active tool at (`x`, `y`), Shift held when `shift`, with what it asks the + /// interface for done. + fn click(app: &mut VectorcraftApp, x: f64, y: f64, shift: bool) { + for kind in [PointerKind::Down, PointerKind::Up] { + let mut ev = PointerEvent::new(kind, x, y); + ev.mods.shift = shift; + let r = app.session.pointer(&ev, ViewInfo::default()); + crate::canvas::apply_requests(app, r); + } + } + + /// A frame of the open dialog: the text it shows. + fn frame(app: &mut VectorcraftApp) -> String { + painted_text(app, |app, ui| crate::dialogs::show(app, ui.ctx())) + } + + fn set_radius(app: &mut VectorcraftApp, r: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), r); + } + + fn ok_enabled(app: &VectorcraftApp) -> bool { + super::SPEC.ok_enabled.is_some_and(|f| f(app, app.ui.dialog.as_ref().unwrap())) + } + + #[test] + fn the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 500, "height": 500})).unwrap(); + for (a, b) in [((100, 100), (300, 100)), ((100, 140), (300, 140))] { + app.run("path.create", json!({"anchors": [{"x": a.0, "y": a.1}, {"x": b.0, "y": b.1}]})).unwrap(); + } + app.run("path.create", json!({"anchors": [{"x": 100, "y": 300}, {"x": 300, "y": 300}, {"x": 300, "y": 400}]})).unwrap(); + app.session.select_tool(tool::ID, ViewInfo::default()).unwrap(); + app.run("tool.setOption", json!({"tool": tool::ID, "key": "askRadius", "value": true})).unwrap(); + let (paths, steps) = (count(&app), undo_steps(&app)); + // A click on each line: the dialog at the click's circle (radius 20), previewed. + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + assert!((app.ui.dialog.as_ref().unwrap().f64("radius", 0.0) - 20.0).abs() < 1e-6); + let shown = frame(&mut app); + for s in ["Tangent Circle", "Radius:"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + assert_eq!(count(&app), paths + 1, "previewed: {}", app.ui.status); + assert!(ok_enabled(&app)); + // Lines 40 pt apart take no other radius: the note, nothing previewed, and OK off. + set_radius(&mut app, json!(25)); + assert!(frame(&mut app).contains(tool::NO_CIRCLE)); + assert_eq!(count(&app), paths); + assert!(!ok_enabled(&app)); + assert_eq!(crate::dialogs::confirm(&mut app), Err(tool::NO_CIRCLE.to_string())); + assert!(app.ui.dialog.is_some() && count(&app) == paths); + // A radius that is not a number in the tool's range (as a control request can set it) is an + // error. + for bad in [json!(0), json!(-20), json!(2e6), json!("x"), Value::Null] { + set_radius(&mut app, bad.clone()); + assert!(frame(&mut app).contains(super::RADIUS_RANGE), "{bad}"); + assert!(!ok_enabled(&app), "{bad}"); + assert_eq!(crate::dialogs::confirm(&mut app), Err(super::RADIUS_RANGE.to_string()), "{bad}"); + assert_eq!(count(&app), paths, "{bad}"); + } + // Back at 20, previewed again; Cancel draws nothing and leaves no undo step. + set_radius(&mut app, json!(20)); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + crate::dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); + // The first line stays picked: a click on the second asks again, and OK draws the circle in + // one undo step; the tool's radius stays. + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1)); + let b = app.session.doc().unwrap().doc.bounds_of(&[app.session.doc().unwrap().doc.layers[0].children().unwrap()[paths].id], false).unwrap(); + assert!((b.x0 - 130.0).abs() < 1e-3 && (b.y0 - 100.0).abs() < 1e-3 && (b.width() - 40.0).abs() < 1e-3, "{b:?}"); + assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); + // Auto-Update Default: Shift in the L's corner asks at the tool's radius; Cancel keeps the + // tool's radius, and OK with another radius draws that fillet and makes it the tool's. + app.run("tool.setOption", json!({"tool": tool::ID, "key": "autoUpdateDefault", "value": true})).unwrap(); + click(&mut app, 150.0, 300.0, false); + click(&mut app, 300.0, 350.0, true); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), tool::RADIUS); + set_radius(&mut app, json!(12)); + frame(&mut app); + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); + click(&mut app, 300.0, 350.0, true); + set_radius(&mut app, json!(10)); + frame(&mut app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((count(&app), undo_steps(&app)), (paths + 2, steps + 2)); + assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(10.0)); + } + + #[test] + fn a_click_found_radius_outside_the_tool_range_can_be_drawn() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 500, "height": 500})).unwrap(); + // Lines 2,400,000 pt apart: a click on each finds the circle of radius 1,200,000, past the + // largest radius the tool takes. + for y in [100, 2_400_100] { + app.run("path.create", json!({"anchors": [{"x": 100, "y": y}, {"x": 300, "y": y}]})).unwrap(); + } + app.session.select_tool(tool::ID, ViewInfo::default()).unwrap(); + for key in ["askRadius", "autoUpdateDefault"] { + app.run("tool.setOption", json!({"tool": tool::ID, "key": key, "value": true})).unwrap(); + } + let (paths, steps) = (count(&app), undo_steps(&app)); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 2_400_100.0, false); + assert!((app.ui.dialog.as_ref().unwrap().f64("radius", 0.0) - 1_200_000.0).abs() < 1e-3, "{}", app.ui.status); + frame(&mut app); + assert!(ok_enabled(&app)); + // OK draws it; the tool's radius stays, since the tool does not take that radius. + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1)); + assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); + } +} diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 2c49c661fe..2d83329e24 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -99,14 +99,20 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("arc")); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); - // The Tangent Circle tool's radius for Shift. + // The Tangent Circle tool's radius for Shift, Ask For Circle Radius and Auto-Update Default. app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), 36.0); let text = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); - assert!(text.contains("Tangent Circle Tool Options") && text.contains("Radius:"), "{text}"); - app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(12.5)); + for s in ["Tangent Circle Tool Options", "Radius:", "Ask For Circle Radius", "Auto-Update Default"] { + assert!(text.contains(s), "{s} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert!(!d.bool("askRadius") && !d.bool("autoUpdateDefault")); + d.fields.insert("radius".into(), json!(12.5)); + d.fields.insert("askRadius".into(), json!(true)); crate::dialogs::confirm(&mut app).unwrap(); - assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); + let o = app.session.tool_options_of("tangentCircle"); + assert_eq!((o["radius"].clone(), o["askRadius"].clone(), o["autoUpdateDefault"].clone()), (json!(12.5), json!(true), json!(false))); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..afd89e6cb9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -509,6 +509,7 @@ registry! { DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, SmoothBridge: [crate::addons::pathtools::bridge::KIND] => crate::addons::pathtools::bridge::SPEC, TangentCircle: [crate::addons::pathtools::tangent_circle::KIND] => crate::addons::pathtools::tangent_circle::SPEC, + TangentCircleRadius: [crate::addons::pathtools::tangent_circle_radius::KIND] => crate::addons::pathtools::tangent_circle_radius::SPEC, SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, SwatchLegend: [crate::addons::color::legend::KIND] => crate::addons::color::legend::SPEC, diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index f19cd18cda..be6e1f390c 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -1049,6 +1049,14 @@ pub(crate) fn preview_without_check(app: &mut crate::VectorcraftApp, d: &mut Dia let _ = preview_or_rollback(app, d, label, cmd, params); } +/// Roll back the preview [`preview_without_check`] runs, for values that give nothing to preview: +/// the next preview starts again from the document as it was. +pub(crate) fn rollback_preview(app: &mut crate::VectorcraftApp, d: &mut Dialog) { + if d.fields.remove(PREVIEWED).is_some() { + let _ = app.session.cancel_interaction(); + } +} + /// [`preview_now`] while Preview is on; off, it rolls the preview back. fn preview_or_rollback(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) -> Option { if !d.bool("preview") { diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 0ad9ed936c..e6addca10c 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -171,6 +171,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { } return; } + // A Tangent Circle Tool click with Ask For Circle Radius on: the circle's radius. + crate::addons::pathtools::tangent_circle_radius::KIND => { + crate::addons::pathtools::tangent_circle_radius::open(app, &p); + return; + } // A click or double-click that would edit type set in fonts that aren't available. vectorcraft_tools::text::MISSING_FONT_EDIT => { super::confirm::ask_missing_font_edit(app, &p); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..797a2b2017 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7587,6 +7587,8 @@ breakText Glyphs Глифи Tangent Circle Допирателна окръжност Tangent Circle Tool Инструмент „Допирателна окръжност“ No tangent circle here Тук няма допирателна окръжност + Ask For Circle Radius Питане за радиуса на окръжността + Auto-Update Default Автоматично обновяване на стойността по подразбиране Circle: Окръжност: @msg `ids` names an object twice `ids` посочва обект два пъти @msg select two or three paths or compound paths изберете два или три пътя или съставни пътя diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..db61b3aed3 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7636,6 +7636,8 @@ shape Open Otvoren Tangent Circle Tangentna kružnica Tangent Circle Tool Alat tangentna kružnica No tangent circle here Ovdje nema tangentne kružnice + Ask For Circle Radius Pitaj za poluprečnik kružnice + Auto-Update Default Automatski ažuriraj zadanu vrijednost Circle: Kružnica: @msg `ids` names an object twice `ids` navodi objekat dvaput @msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..eff5103a3b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8468,6 +8468,8 @@ breakText Glyphs Glifs Tangent Circle Cercle tangent Tangent Circle Tool Eina de cercle tangent No tangent circle here Aquí no hi ha cap cercle tangent + Ask For Circle Radius Demana el radi del cercle + Auto-Update Default Actualitza automàticament el valor predeterminat Circle: Cercle: @msg `ids` names an object twice `ids` indica un objecte dues vegades @msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..105be5cac2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8449,6 +8449,8 @@ breakText Glyphs Glyfy Tangent Circle Tečná kružnice Tangent Circle Tool Nástroj Tečná kružnice No tangent circle here Zde není žádná tečná kružnice + Ask For Circle Radius Ptát se na poloměr kružnice + Auto-Update Default Automaticky aktualizovat výchozí hodnotu Circle: Kružnice: @msg `ids` names an object twice `ids` uvádí některý objekt dvakrát @msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..6396024ada 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10505,6 +10505,8 @@ breakText Glyphs Glyffer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkel-værktøj No tangent circle here Ingen tangentcirkel her + Ask For Circle Radius Spørg om cirklens radius + Auto-Update Default Opdater standard automatisk Circle: Cirkel: @msg `ids` names an object twice `ids` nævner et objekt to gange @msg select two or three paths or compound paths vælg to eller tre stier eller sammensatte stier diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..61d3b10d1d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8074,6 +8074,8 @@ breakText Glyphs Glyphen Tangent Circle Tangentialkreis Tangent Circle Tool Tangentialkreis-Werkzeug No tangent circle here Hier kein Tangentialkreis + Ask For Circle Radius Nach Kreisradius fragen + Auto-Update Default Standardwert automatisch aktualisieren Circle: Kreis: @msg `ids` names an object twice `ids` nennt ein Objekt zweimal @msg select two or three paths or compound paths wählen Sie zwei oder drei Pfade oder zusammengesetzte Pfade aus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..c008194ebd 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8440,6 +8440,8 @@ breakText Glyphs Γλύφοι Tangent Circle Εφαπτόμενος κύκλος Tangent Circle Tool Εφαπτόμενος κύκλος (Tangent Circle Tool) No tangent circle here Δεν υπάρχει εφαπτόμενος κύκλος εδώ + Ask For Circle Radius Ερώτηση για την ακτίνα του κύκλου + Auto-Update Default Αυτόματη ενημέρωση προεπιλογής Circle: Κύκλος: @msg `ids` names an object twice το `ids` αναφέρει ένα αντικείμενο δύο φορές @msg select two or three paths or compound paths επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..6e59438927 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8426,6 +8426,8 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Herramienta Círculo tangente No tangent circle here No hay círculo tangente aquí + Ask For Circle Radius Preguntar el radio del círculo + Auto-Update Default Actualizar automáticamente el valor predeterminado Circle: Círculo: @msg `ids` names an object twice `ids` indica un objeto dos veces @msg select two or three paths or compound paths seleccione dos o tres trazados o trazados compuestos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..9cb0a278dc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8516,6 +8516,8 @@ breakText Glyphs Merkit Tangent Circle Sivuava ympyrä Tangent Circle Tool Sivuava ympyrä -työkalu No tangent circle here Tässä ei ole sivuavaa ympyrää + Ask For Circle Radius Kysy ympyrän säde + Auto-Update Default Päivitä oletus automaattisesti Circle: Ympyrä: @msg `ids` names an object twice `ids` mainitsee saman objektin kahdesti @msg select two or three paths or compound paths valitse kaksi tai kolme polkua tai yhdistelmäpolkua diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..5c13273bde 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8445,6 +8445,8 @@ breakText Glyphs Glyphes Tangent Circle Cercle tangent Tangent Circle Tool Outil Cercle tangent No tangent circle here Aucun cercle tangent ici + Ask For Circle Radius Demander le rayon du cercle + Auto-Update Default Mettre à jour automatiquement la valeur par défaut Circle: Cercle : @msg `ids` names an object twice `ids` désigne deux fois le même objet @msg select two or three paths or compound paths sélectionnez deux ou trois tracés ou tracés transparents diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..5cc465adf3 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4336,6 +4336,8 @@ arrowhead Feather પીંછું Tangent Circle સ્પર્શક વર્તુળ Tangent Circle Tool સ્પર્શક વર્તુળ ટૂલ No tangent circle here અહીં કોઈ સ્પર્શક વર્તુળ નથી + Ask For Circle Radius વર્તુળની ત્રિજ્યા પૂછો + Auto-Update Default ડિફૉલ્ટ આપમેળે અપડેટ કરો Tangent Circle… સ્પર્શક વર્તુળ… Taper ટેપર Target લક્ષ્ય diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..404c9c0fae 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5889,6 +5889,8 @@ arrowhead Feather पंख Tangent Circle स्पर्शी वृत्त Tangent Circle Tool स्पर्शी वृत्त टूल No tangent circle here यहाँ कोई स्पर्शी वृत्त नहीं है + Ask For Circle Radius वृत्त की त्रिज्या पूछें + Auto-Update Default डिफ़ॉल्ट स्वचालित रूप से अपडेट करें Tangent Circle… स्पर्शी वृत्त… Taper टेपर Target लक्ष्य diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..f5b9232d45 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8435,6 +8435,8 @@ breakText Glyphs Glifák Tangent Circle Érintőkör Tangent Circle Tool Érintőkör eszköz No tangent circle here Itt nincs érintőkör + Ask For Circle Radius Kérdés a kör sugaráról + Auto-Update Default Alapértelmezett érték automatikus frissítése Circle: Kör: @msg `ids` names an object twice `ids`: egy objektumot kétszer nevez meg @msg select two or three paths or compound paths jelölj ki két vagy három útvonalat vagy összetett útvonalat diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..364bc3bae8 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8290,6 +8290,8 @@ breakText Glyphs Glif Tangent Circle Lingkaran singgung Tangent Circle Tool Alat lingkaran singgung No tangent circle here Tidak ada lingkaran singgung di sini + Ask For Circle Radius Tanyakan Radius Lingkaran + Auto-Update Default Perbarui Default Otomatis Circle: Lingkaran: @msg `ids` names an object twice `ids` menyebut satu objek dua kali @msg select two or three paths or compound paths pilih dua atau tiga jalur atau jalur gabungan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..81823d1b5f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8112,6 +8112,8 @@ breakText Glyphs Glifi Tangent Circle Cerchio tangente Tangent Circle Tool Strumento Cerchio tangente No tangent circle here Nessun cerchio tangente qui + Ask For Circle Radius Chiedi il raggio del cerchio + Auto-Update Default Aggiorna automaticamente il valore predefinito Circle: Cerchio: @msg `ids` names an object twice `ids` indica due volte lo stesso oggetto @msg select two or three paths or compound paths seleziona due o tre tracciati o tracciati composti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..6c4dc97248 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10001,6 +10001,8 @@ breakText Glyphs 字形 Tangent Circle 接円 Tangent Circle Tool 接円ツール No tangent circle here ここに接円はありません + Ask For Circle Radius 円の半径を確認 + Auto-Update Default デフォルトを自動更新 Circle: 円: @msg `ids` names an object twice `ids` に同じオブジェクトが 2 回指定されています @msg select two or three paths or compound paths パスまたは複合パスを 2 つか 3 つ選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..5a7507f429 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10623,6 +10623,8 @@ breakText Glyphs გლიფები Tangent Circle მხები წრე Tangent Circle Tool მხები წრის ხელსაწყო No tangent circle here აქ მხები წრე არ არის + Ask For Circle Radius წრის რადიუსის კითხვა + Auto-Update Default ნაგულისხმევის ავტომატური განახლება Circle: წრე: @msg `ids` names an object twice `ids` ერთსა და იმავე ობიექტს ორჯერ მიუთითებს @msg select two or three paths or compound paths მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..483cb08228 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8084,6 +8084,8 @@ breakText Glyphs 글리프 Tangent Circle 접원 Tangent Circle Tool 접원 도구 No tangent circle here 여기에는 접원이 없음 + Ask For Circle Radius 원 반지름 묻기 + Auto-Update Default 기본값 자동 업데이트 Circle: 원: @msg `ids` names an object twice `ids`에 같은 오브젝트가 두 번 있습니다 @msg select two or three paths or compound paths 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..b9147289a4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10343,6 +10343,8 @@ breakText Glyphs Glyphs Tangent Circle Raakcirkel Tangent Circle Tool Raakcirkel-gereedschap No tangent circle here Hier geen raakcirkel + Ask For Circle Radius Vragen naar cirkelradius + Auto-Update Default Standaard automatisch bijwerken Circle: Cirkel: @msg `ids` names an object twice `ids` noemt een object twee keer @msg select two or three paths or compound paths selecteer twee of drie paden of samengestelde paden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..8a59fca111 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8308,6 +8308,8 @@ breakText Glyphs Glify Tangent Circle Okrąg styczny Tangent Circle Tool Narzędzie Okrąg styczny No tangent circle here Brak okręgu stycznego w tym miejscu + Ask For Circle Radius Pytaj o promień okręgu + Auto-Update Default Automatycznie aktualizuj wartość domyślną Circle: Okrąg: @msg `ids` names an object twice `ids` wskazuje ten sam obiekt dwa razy @msg select two or three paths or compound paths zaznacz dwie lub trzy ścieżki lub ścieżki złożone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..447da1dfff 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8468,6 +8468,8 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Ferramenta Círculo tangente No tangent circle here Nenhum círculo tangente aqui + Ask For Circle Radius Perguntar o Raio do Círculo + Auto-Update Default Atualizar o Padrão Automaticamente Circle: Círculo: @msg `ids` names an object twice `ids` indica um objeto duas vezes @msg select two or three paths or compound paths selecione dois ou três caminhos ou caminhos compostos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..b657fcc52f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8440,6 +8440,8 @@ breakText Glyphs Глифы Tangent Circle Касательная окружность Tangent Circle Tool Инструмент «Касательная окружность» No tangent circle here Здесь нет касательной окружности + Ask For Circle Radius Запрашивать радиус окружности + Auto-Update Default Автоматически обновлять значение по умолчанию Circle: Окружность: @msg `ids` names an object twice `ids` указывает объект дважды @msg select two or three paths or compound paths выделите два или три контура или составных контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..2a152f819e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8484,6 +8484,8 @@ breakText Glyphs Glyfer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkelverktyget No tangent circle here Ingen tangentcirkel här + Ask For Circle Radius Fråga efter cirkelradie + Auto-Update Default Uppdatera standard automatiskt Circle: Cirkel: @msg `ids` names an object twice `ids` anger ett objekt två gånger @msg select two or three paths or compound paths markera två eller tre banor eller sammansatta banor diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..b431a70dc1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10339,6 +10339,8 @@ breakText Glyphs Glifler Tangent Circle Teğet Daire Tangent Circle Tool Teğet Daire Aracı No tangent circle here Burada teğet daire yok + Ask For Circle Radius Daire Yarıçapını Sor + Auto-Update Default Varsayılanı Otomatik Güncelle Circle: Daire: @msg `ids` names an object twice `ids` bir nesneyi iki kez belirtiyor @msg select two or three paths or compound paths iki veya üç yol ya da bileşik yol seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..03c5daa27e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8094,6 +8094,8 @@ breakText Glyphs Гліфи Tangent Circle Дотичне коло Tangent Circle Tool Інструмент «Дотичне коло» No tangent circle here Тут немає дотичного кола + Ask For Circle Radius Запитувати радіус кола + Auto-Update Default Автоматично оновлювати значення за замовчуванням Circle: Коло: @msg `ids` names an object twice `ids` указує об’єкт двічі @msg select two or three paths or compound paths виділіть два або три контури чи складені контури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..f7556a0633 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8140,6 +8140,8 @@ breakText Glyphs Glyph Tangent Circle Đường tròn tiếp xúc Tangent Circle Tool Công cụ Đường tròn tiếp xúc No tangent circle here Không có đường tròn tiếp xúc ở đây + Ask For Circle Radius Hỏi bán kính đường tròn + Auto-Update Default Tự động cập nhật mặc định Circle: Đường tròn: @msg `ids` names an object twice `ids` nêu một đối tượng hai lần @msg select two or three paths or compound paths chọn hai hoặc ba đường dẫn hoặc đường dẫn phức hợp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..43e0258fad 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8318,6 +8318,8 @@ breakText Glyphs 字形 Tangent Circle 相切圆 Tangent Circle Tool 相切圆工具 No tangent circle here 此处没有相切圆 + Ask For Circle Radius 询问圆半径 + Auto-Update Default 自动更新默认值 Circle: 圆: @msg `ids` names an object twice `ids` 重复指定了同一个对象 @msg select two or three paths or compound paths 请选择两个或三个路径或复合路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..b69db647b4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8142,6 +8142,8 @@ breakText Glyphs 字符 Tangent Circle 相切圓 Tangent Circle Tool 相切圓工具 No tangent circle here 此處沒有相切圓 + Ask For Circle Radius 詢問圓半徑 + Auto-Update Default 自動更新預設值 Circle: 圓: @msg `ids` names an object twice `ids` 將同一個物件指定了兩次 @msg select two or three paths or compound paths 請選取兩個或三個路徑或複合路徑 diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..7823ccaa24 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14566,8 +14566,19 @@ Tools: change to the first segment that makes no undo step (a live preview, or one that was canceled) forgets the first segment. The circle is looked for again whenever either segment no longer has the shape it was found on, so a canceled preview does not leave a circle worked out on the previewed paths. - Option (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36). `tool.setOption` - gives an error for a value outside that range or one that is not a number, and for any other option. + Options (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36), `askRadius` (Ask For + Circle Radius, true or false, false) and `autoUpdateDefault` (Auto-Update Default, true or false, false). + `tool.setOption` gives an error for a radius outside that range or one that is not a number, for a value of the other + two that is not true or false, and for any other option. With `askRadius` on, a click on the second segment that finds + a circle (with or without Shift) opens the Tangent Circle dialog (`tangentCircleRadius`) instead of drawing; a drag, + which sets the radius, draws at once. The dialog's Radius starts at the radius of the circle found, and each radius + previews the circle of that radius touching the second segments nearest the click, anywhere along the first segment + (at the radius it opened with, the circle found). A radius that gives no circle there shows the note and leaves OK + off, and one outside 0.01 to 1000000 pt (or not a number, as `ui.dialog.set` can give) shows the radius error, except + the radius the dialog opened with; OK then gives that error and the dialog stays open. OK draws the circle in one undo + step, with `shape.circleThroughPoints`, and with `autoUpdateDefault` on also sets `radius` to the radius given when + it is in that range. Cancel draws nothing, leaves no undo step and + keeps the first segment picked. - **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed, on any path that can be edited, selected or not. A click runs `addon.pathtools.trim` with `at`, for the path within 4 screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..05e32366ce 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2997,6 +2997,8 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. +Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there shows the note and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` in `vectorcraft-tools` and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok` in `vectorcraft-ui-egui`. + ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, since 2026-11-16; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. The tool shows the Knife's cursor, now drawn as a knife with the blade's point on the hotspot (2026-11-16; tests `trim_at_crossings_is_in_the_scissors_flyout` and `a_saved_toolbar_without_trim_at_crossings_keeps_its_layout` in `edit_toolbar::tests`, `trim_at_crossings_is_in_the_scissors_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`, `the_knife_shows_a_knife_with_its_point_on_the_hotspot` in `cursors::tests` and `drawing_tools_show_their_own_cursor` in `vectorcraft-tools`). From 8bea29062f3a22261cffcc51e02c2b9c2fb869c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:30:20 -0800 Subject: [PATCH 04/42] Tangent Circle Tool: a radius typed outside the tool's range shows the error The dialog's Radius field kept a typed radius inside 0.01 to 1000000 pt, so typing 0 drew a 0.01 pt circle and the radius error never showed. The field now keeps the radius as typed: one outside the range shows the error and leaves OK off. --- .../addons/pathtools/tangent_circle_radius.rs | 67 ++++++++++++++++++- docs/target-app-parity.md | 2 +- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index bc1b6d5992..7c953fbed2 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -84,9 +84,9 @@ fn circle(d: &mut Dialog) -> Result, String> { fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { let unit = app.session.general_unit(); - let (lo, hi) = tangent_circle::RADIUS_RANGE; + // The field keeps a radius as typed, so one outside the tool's range shows [`RADIUS_RANGE`]. widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { - form::length_within(ui, d, "radius", unit, FIELD_W, Some(lo..=hi)); + form::length_within(ui, d, "radius", unit, FIELD_W, None); }); let note = match circle(d) { Ok(Some(points)) => { @@ -158,6 +158,69 @@ mod tests { super::SPEC.ok_enabled.is_some_and(|f| f(app, app.ui.dialog.as_ref().unwrap())) } + /// Click the dialog's Radius field, select its text, type `text` over it and press Tab. + fn type_radius(app: &mut VectorcraftApp, text: &str) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut time = 0.0; + let mut run = |app: &mut VectorcraftApp, events: Vec| { + time += 0.1; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + run(app, vec![]); + let out = run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + // The Radius field is the dialog's only text field. + let fields: Vec<_> = nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput).filter_map(|(_, n)| n.bounds()).collect(); + let [b] = fields[..] else { panic!("one text field, not {fields:?}") }; + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + run(app, vec![egui::Event::PointerMoved(at), button]); + } + let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() }; + let select_all = egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: all }; + run(app, vec![select_all, egui::Event::Text(text.into())]); + for pressed in [true, false] { + run(app, vec![egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed, repeat: false, modifiers: Default::default() }]); + } + run(app, vec![]); + } + + #[test] + fn a_radius_typed_outside_the_tool_range_shows_the_error_and_leaves_ok_off() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 500, "height": 500})).unwrap(); + for y in [100, 140] { + app.run("path.create", json!({"anchors": [{"x": 100, "y": y}, {"x": 300, "y": y}]})).unwrap(); + } + app.session.select_tool(tool::ID, ViewInfo::default()).unwrap(); + app.run("tool.setOption", json!({"tool": tool::ID, "key": "askRadius", "value": true})).unwrap(); + let paths = count(&app); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert!(ok_enabled(&app)); + // A radius typed in the field is kept as typed, not moved into the tool's range. + for (typed, kept) in [("0", 0.0), ("-20", -20.0), ("2000000", 2e6)] { + type_radius(&mut app, typed); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", f64::NAN), kept, "{typed}"); + assert!(frame(&mut app).contains(super::RADIUS_RANGE), "{typed}"); + assert!(!ok_enabled(&app), "{typed}"); + assert_eq!(count(&app), paths, "{typed}"); + } + // Typing the click's radius again previews its circle and turns OK on. + type_radius(&mut app, "20"); + frame(&mut app); + assert!(ok_enabled(&app)); + assert_eq!(count(&app), paths + 1); + } + #[test] fn the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 05e32366ce..007d573a48 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2997,7 +2997,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. -Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there shows the note and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` in `vectorcraft-tools` and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok` in `vectorcraft-ui-egui`. +Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there shows the note and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` in `vectorcraft-tools` and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok` and `a_radius_typed_outside_the_tool_range_shows_the_error_and_leaves_ok_off` in `vectorcraft-ui-egui`. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) From 9bb2e0dbfe8b90171ae2c27af6167014fe8e9f0a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:13:54 -0800 Subject: [PATCH 05/42] Tangent Circle Tool: the radius dialog draws nothing after its segments change The dialog kept the segments it was opened on, so a control request that edited either path, or a switch to another document with the same paths, left it previewing and drawing a circle that no longer touched them. It now records the segments' places and the document, and shows the note with OK off when either segment differs or another document is active. --- crates/tools/src/addons/tangent_circle.rs | 100 +++++++++++++++--- .../addons/pathtools/tangent_circle_radius.rs | 76 +++++++++++-- docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 4 files changed, 155 insertions(+), 28 deletions(-) diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index 5ccc3815de..e57740e5a7 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -18,11 +18,12 @@ //! segment's shape differs from the one they were found on. With the `askRadius` option on, a click //! on the second segment (not a drag, which sets the radius itself) opens the [`RADIUS_DIALOG`] //! instead of drawing: it starts at the radius of the circle found and draws the circle of the radius -//! typed ([`radius_circle`]); the first segment stays picked until it does. +//! typed ([`radius_circle`]); the first segment stays picked until it does. While the dialog is open, +//! an edit to either segment leaves it without a circle ([`segments_unchanged`]). use kurbo::{CubicBez, Shape}; use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{Document, NodeId}; use vectorcraft_geom::{BezPath, ParamCurve, Point}; use vectorcraft_pathops::addons::pathtools::{SegmentCircle, circles_of_radius, circles_through}; @@ -128,10 +129,24 @@ fn pick_at(cx: &ToolContext, p: Point) -> Option { Some(Pick { id, subpath, segment, t, p: curve.eval(t), curve }) } +/// A segment's place in the document: its path, subpath and index. +type Place = (NodeId, usize, usize); + +impl Pick { + fn place(&self) -> Place { + (self.id, self.subpath, self.segment) + } +} + /// The document's segment at `pick` as it is now: none when its path, subpath or segment is gone. fn segment_now(cx: &ToolContext, pick: &Pick) -> Option { - let sp = cx.doc.node(pick.id)?.path_data()?.subpaths.get(pick.subpath)?; - (pick.segment < sp.segment_count()).then(|| sp.segment(pick.segment)) + segment_at(cx.doc, pick.place()) +} + +/// The segment of `doc` at `place`: none when its path, subpath or segment is gone. +fn segment_at(doc: &Document, (id, subpath, segment): Place) -> Option { + let sp = doc.node(id)?.path_data()?.subpaths.get(subpath)?; + (segment < sp.segment_count()).then(|| sp.segment(segment)) } /// Whether the document's segment at `pick` still has the shape it had when it was picked. @@ -142,12 +157,17 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool { /// The segments a circle may touch when `second` is picked: it and the segments on either side of /// it, without `first`. None when `second` is the first segment again. fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { - if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { + second_set_at(cx.doc, first.place(), second.place()) +} + +/// [`second_set`] for the segments of `doc` at `first` and `second`. +fn second_set_at(doc: &Document, first: Place, second: Place) -> Vec { + if first == second { return vec![]; } - let Some(sp) = cx.doc.node(second.id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(second.subpath)) else { return vec![] }; + let (id, subpath, i) = second; + let Some(sp) = doc.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(subpath)) else { return vec![] }; let n = sp.segment_count(); - let i = second.segment; let mut indices = vec![i]; if i > 0 || sp.closed { indices.push((i + n - 1) % n); @@ -157,7 +177,7 @@ fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { } indices.sort_unstable(); indices.dedup(); - let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; + let is_first = |k: usize| first == (id, subpath, k); indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect() } @@ -239,13 +259,26 @@ fn curve_of(v: &Value) -> Option { Some(CubicBez::new(point_of(a)?, point_of(b)?, point_of(c)?, point_of(d)?)) } -/// The [`RADIUS_DIALOG`]'s parameters for circle `c`, found by a click at `at` on `first` and the -/// segments `second`, which `points` (from [`draw`]) draws: the segments, the click, the circle's -/// radius and points, and the tolerance [`draw`] checked them with. -fn dialog_params(first: &CubicBez, second: &[CubicBez], at: Point, c: &SegmentCircle, points: &Value, tol: f64) -> Value { +fn place_json((id, subpath, segment): Place) -> Value { + json!([id.0, subpath, segment]) +} + +/// A place written by [`place_json`]. +fn place_of(v: &Value) -> Option { + let [id, subpath, segment] = v.as_array()?.as_slice() else { return None }; + let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()); + Some((NodeId(id.as_u64()?), index(subpath)?, index(segment)?)) +} + +/// The [`RADIUS_DIALOG`]'s parameters for circle `c`, found by a click at `at` on `first` and on +/// `picked`, whose segments a circle may touch are `second`, which `points` (from [`draw`]) draws: +/// the segments and their places, the click, the circle's radius and points, and the tolerance +/// [`draw`] checked them with. +fn dialog_params(first: &Pick, picked: &Pick, second: &[CubicBez], at: Point, c: &SegmentCircle, points: &Value, tol: f64) -> Value { json!({ - "first": curve_json(first), + "first": curve_json(&first.curve), "second": second.iter().map(curve_json).collect::>(), + "places": [place_json(first.place()), place_json(picked.place())], "at": point_json(at), "radius": c.circle.radius, "points": points, @@ -253,6 +286,19 @@ fn dialog_params(first: &CubicBez, second: &[CubicBez], at: Point, c: &SegmentCi }) } +/// Whether the segments the [`RADIUS_DIALOG`] opened with parameters `p` holds are still those of +/// `doc`: false when a path was edited or removed since the click, in another document, or for +/// parameters the tool did not write. +pub fn segments_unchanged(doc: &Document, p: &Value) -> bool { + let check = || -> Option { + let [first, second] = p.get("places")?.as_array()?.as_slice() else { return None }; + let (first, second) = (place_of(first)?, place_of(second)?); + let second_then: Vec = p.get("second")?.as_array()?.iter().map(curve_of).collect::>()?; + Some(segment_at(doc, first)? == curve_of(p.get("first")?)? && second_then == second_set_at(doc, first, second)) + }; + check() == Some(true) +} + /// The `shape.circleThroughPoints` parameters that draw the circle of `radius` the [`RADIUS_DIALOG`] /// opened with parameters `p` gives: at the radius the click found, the circle found; at any other, /// the circle of `radius` touching the second segments nearest the click, anywhere along the first @@ -432,7 +478,7 @@ impl Tool for TangentCircleTool { && press.radius.is_none() && let (Some(first), Action::Exec(_, drawn)) = (&self.first, &action) { - let params = dialog_params(&first.curve, &press.second, press.at, &c, &drawn["points"], tol); + let params = dialog_params(first, &press.pick, &press.second, press.at, &c, &drawn["points"], tol); return vec![Action::Dialog(RADIUS_DIALOG.into(), params)]; } vec![action, Action::Notify(DRAWN.into())] @@ -702,6 +748,32 @@ mod tests { assert!(t.first.is_some()); } + #[test] + fn the_radius_dialog_knows_when_its_segments_changed() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("askRadius", &json!(true)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let p = asked(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert!(segments_unchanged(&d, &p)); + assert!(segments_unchanged(&doc_at(100.0, 140.0), &p), "the same paths"); + // Either line moved, or another document: changed. + for (a, b) in [(100.0, 150.0), (110.0, 140.0)] { + assert!(!segments_unchanged(&doc_at(a, b), &p), "{a} {b}"); + } + assert!(!segments_unchanged(&Document::new(500.0, 500.0), &p)); + // Parameters the tool did not write. + for key in ["places", "first", "second"] { + let mut q = p.clone(); + q[key] = json!("x"); + assert!(!segments_unchanged(&d, &q), "{key}"); + } + } + #[test] fn two_clicks_draw_the_circle_tangent_at_the_first_click() { let d = doc(); diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index 7c953fbed2..f64042bc3c 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -2,12 +2,13 @@ //! tool's Ask For Circle Radius option is on. It starts at the radius of the circle the click found, //! and each radius previews on the canvas the circle of that radius touching the two segments //! nearest the click ([`tangent_circle::radius_circle`]). A radius that gives no circle there shows -//! the tool's note and leaves OK off. OK draws the circle with `shape.circleThroughPoints` in one -//! undo step, and with Auto-Update Default on also sets the tool's `radius` to the one given; Cancel -//! draws nothing. +//! the tool's note and leaves OK off, as does an edit to either segment after the click. OK draws +//! the circle with `shape.circleThroughPoints` in one undo step, and with Auto-Update Default on +//! also sets the tool's `radius` to the one given; Cancel draws nothing. use egui::Ui; use serde_json::{Value, json}; +use vectorcraft_doc::Document; use vectorcraft_tools::addons::tangent_circle; use crate::VectorcraftApp; @@ -28,13 +29,16 @@ const CLICK: &str = "__click"; /// none) (private fields). const TRIED: &str = "__tried"; const CIRCLE: &str = "__circle"; +/// The id of the document the click was in (`DocState::uid`; a private field). +const DOC: &str = "__doc"; /// The error for a radius outside the tool's range. const RADIUS_RANGE: &str = "`radius` must be from 0.01 to 1000000 pt"; /// Open the dialog on what the tool found (its [`tangent_circle::RADIUS_DIALOG`] parameters). pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { let radius = p.get("radius").cloned().unwrap_or(json!(tangent_circle::RADIUS)); - app.ui.dialog = Some(Dialog::new(KIND, json!({ "radius": radius, "preview": true, CLICK: p }))); + let doc = app.session.doc().ok().map(|s| s.uid); + app.ui.dialog = Some(Dialog::new(KIND, json!({ "radius": radius, "preview": true, CLICK: p, DOC: doc }))); } pub(crate) const SPEC: DialogSpec = DialogSpec { @@ -42,11 +46,18 @@ pub(crate) const SPEC: DialogSpec = DialogSpec { body, confirm, preview: true, - ok_enabled: Some(|_, d| circle_of(d).is_some_and(|c| c.is_ok_and(|c| c.is_some()))), + ok_enabled: Some(|app, d| circle_of(doc(app, d), d).is_some_and(|c| c.is_ok_and(|c| c.is_some()))), min_width: 280.0, ..DialogSpec::FORM }; +/// The document the click was in, while it is the active one. A preview adds the circle to it and +/// leaves the two segments as they are. +fn doc<'a>(app: &'a VectorcraftApp, d: &Dialog) -> Option<&'a Document> { + let clicked = d.fields.get(DOC).and_then(Value::as_u64)?; + app.session.doc().ok().filter(|s| s.uid == clicked).map(|s| &*s.doc) +} + /// Whether `r` is in the tool's radius range. fn in_range(r: f64) -> bool { let (lo, hi) = tangent_circle::RADIUS_RANGE; @@ -61,18 +72,23 @@ fn radius(d: &Dialog) -> Result { } /// The circle last looked for, when it was looked for at the radius the dialog holds: its [`DRAW`] -/// parameters, or none. -fn circle_of(d: &Dialog) -> Option, String>> { +/// parameters, or none. None too without the document clicked in (`doc`), or when either segment in +/// it is no longer the one clicked (a control request edited or removed its path). +fn circle_of(doc: Option<&Document>, d: &Dialog) -> Option, String>> { let r = match radius(d) { Ok(r) => r, Err(e) => return Some(Err(e)), }; + let click = d.fields.get(CLICK).unwrap_or(&Value::Null); + if !doc.is_some_and(|doc| tangent_circle::segments_unchanged(doc, click)) { + return Some(Ok(None)); + } (d.fields.get(TRIED).and_then(Value::as_f64) == Some(r)).then(|| Ok(d.fields.get(CIRCLE).filter(|c| !c.is_null()).cloned())) } /// The circle at the radius the dialog holds, looked for again only when the radius changed. -fn circle(d: &mut Dialog) -> Result, String> { - if let Some(found) = circle_of(d) { +fn circle(doc: Option<&Document>, d: &mut Dialog) -> Result, String> { + if let Some(found) = circle_of(doc, d) { return found; } let r = radius(d)?; @@ -88,7 +104,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { form::length_within(ui, d, "radius", unit, FIELD_W, None); }); - let note = match circle(d) { + let note = match circle(doc(app, d), d) { Ok(Some(points)) => { form::preview_without_check(app, d, "Tangent Circle", DRAW, points); return false; @@ -107,7 +123,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut d = d.clone(); let r = radius(&d)?; - let points = circle(&mut d)?.ok_or_else(|| tangent_circle::NO_CIRCLE.to_string())?; + let points = circle(doc(app, &d), &mut d)?.ok_or_else(|| tangent_circle::NO_CIRCLE.to_string())?; let auto = app.session.tool_options_of(tangent_circle::ID).get("autoUpdateDefault").and_then(Value::as_bool) == Some(true); form::commit_preview(app, DRAW, points)?; if auto && in_range(r) { @@ -221,6 +237,44 @@ mod tests { assert_eq!(count(&app), paths + 1); } + #[test] + fn another_document_or_a_segment_changed_after_the_click_gives_no_circle() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 500, "height": 500})).unwrap(); + for y in [100, 140] { + app.run("path.create", json!({"anchors": [{"x": 100, "y": y}, {"x": 300, "y": y}]})).unwrap(); + } + app.session.select_tool(tool::ID, ViewInfo::default()).unwrap(); + app.run("tool.setOption", json!({"tool": tool::ID, "key": "askRadius", "value": true})).unwrap(); + let paths = count(&app); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert!(ok_enabled(&app)); + assert_eq!(count(&app), paths + 1); + // Clicked in another document than the active one: no circle and OK off, until that one is + // active again. + let clicked = app.ui.dialog.as_ref().unwrap().fields[super::DOC].clone(); + assert_eq!(clicked, json!(app.session.doc().unwrap().uid)); + app.ui.dialog.as_mut().unwrap().fields.insert(super::DOC.into(), json!(clicked.as_u64().unwrap() + 1)); + assert!(frame(&mut app).contains(tool::NO_CIRCLE)); + assert_eq!(count(&app), paths); + assert!(!ok_enabled(&app)); + app.ui.dialog.as_mut().unwrap().fields.insert(super::DOC.into(), clicked); + frame(&mut app); + assert!(ok_enabled(&app)); + assert_eq!(count(&app), paths + 1); + // The dialog holds a first segment the document no longer has (as when a control request + // moves that line): no circle, nothing previewed, OK off and refused. + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.get_mut(super::CLICK).unwrap()["first"] = json!([[100.0, 110.0], [100.0, 110.0], [300.0, 110.0], [300.0, 110.0]]); + assert!(frame(&mut app).contains(tool::NO_CIRCLE)); + assert_eq!(count(&app), paths); + assert!(!ok_enabled(&app)); + assert_eq!(crate::dialogs::confirm(&mut app), Err(tool::NO_CIRCLE.to_string())); + assert_eq!(count(&app), paths); + } + #[test] fn the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index 7823ccaa24..2dd4e1087c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14574,8 +14574,9 @@ Tools: which sets the radius, draws at once. The dialog's Radius starts at the radius of the circle found, and each radius previews the circle of that radius touching the second segments nearest the click, anywhere along the first segment (at the radius it opened with, the circle found). A radius that gives no circle there shows the note and leaves OK - off, and one outside 0.01 to 1000000 pt (or not a number, as `ui.dialog.set` can give) shows the radius error, except - the radius the dialog opened with; OK then gives that error and the dialog stays open. OK draws the circle in one undo + off, as do an edit to either segment's path after the click and another active document; one outside 0.01 to + 1000000 pt, typed or set (or not a number, as `ui.dialog.set` can give), shows the radius error, except the radius the + dialog opened with; OK then gives that error and the dialog stays open. OK draws the circle in one undo step, with `shape.circleThroughPoints`, and with `autoUpdateDefault` on also sets `radius` to the radius given when it is in that range. Cancel draws nothing, leaves no undo step and keeps the first segment picked. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 007d573a48..e1469ce595 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2997,7 +2997,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. -Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there shows the note and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` in `vectorcraft-tools` and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok` and `a_radius_typed_outside_the_tool_range_shows_the_error_and_leaves_ok_off` in `vectorcraft-ui-egui`. +Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `a_radius_typed_outside_the_tool_range_shows_the_error_and_leaves_ok_off` and `another_document_or_a_segment_changed_after_the_click_gives_no_circle` in `vectorcraft-ui-egui`. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) From 7b580467d721cafa943777ed6cebb9c47c35a0cc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:17:27 -0800 Subject: [PATCH 06/42] Tangent Circle Tool: the radius dialog keeps OK off on a locked or hidden layer A target layer locked or hidden while the radius dialog is open now shows why in the dialog and leaves OK off, instead of offering a draw that fails. A second segment's subpath edited down to no segments gives no circle instead of panicking. --- crates/tools/src/addons/tangent_circle.rs | 9 +++++ .../addons/pathtools/tangent_circle_radius.rs | 35 ++++++++++++++++++- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index e57740e5a7..c4771344ae 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -167,7 +167,11 @@ fn second_set_at(doc: &Document, first: Place, second: Place) -> Vec { } let (id, subpath, i) = second; let Some(sp) = doc.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(subpath)) else { return vec![] }; + // A subpath edited down to no segments (while the radius dialog is open) has nothing to touch. let n = sp.segment_count(); + if n == 0 { + return vec![]; + } let mut indices = vec![i]; if i > 0 || sp.closed { indices.push((i + n - 1) % n); @@ -766,6 +770,11 @@ mod tests { assert!(!segments_unchanged(&doc_at(a, b), &p), "{a} {b}"); } assert!(!segments_unchanged(&Document::new(500.0, 500.0), &p)); + // The second line edited down to a closed subpath without segments: changed. + let mut emptied = d.clone(); + let (second, ..) = place_of(&p["places"][1]).unwrap(); + emptied.node_mut(second).and_then(|n| n.path_data_mut()).unwrap().subpaths[0] = SubPath::polyline(&[], true); + assert!(!segments_unchanged(&emptied, &p)); // Parameters the tool did not write. for key in ["places", "first", "second"] { let mut q = p.clone(); diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index b0d45c2389..a0be51829f 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -113,6 +113,12 @@ fn circle(app: &VectorcraftApp, open: &mut Open, fields: &DialogFields) -> Resul found.map(|points| (r, points)).ok_or_else(no_circle) } +/// Why the active document cannot take a new circle now: its target layer is locked or hidden. The draw would be +/// refused, with or without a preview. +fn target_refusal(app: &VectorcraftApp) -> Option { + app.session.doc().ok()?.target_parent().err().map(|e| e.to_string()) +} + /// The words the dialog shows for `why` ([`circle`]'s error), in the interface's language. fn shown(why: &str) -> String { if why == tangent_circle::NO_CIRCLE { tl!(tangent_circle::NO_CIRCLE).to_string() } else { crate::i18n::msg(why) } @@ -140,7 +146,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }; let _ = preview.run(app, previewed.0, "Tangent Circle", DRAW, &previewed.1); open.preview = preview; - open.note = found.err(); + // A target layer locked or hidden after the circle previewed refuses the draw: OK stays off. The preview stays, + // since rolling it back would also roll back the edit that locked or hid the layer. + open.note = found.err().or_else(|| target_refusal(app)); let ready = open.note.as_deref().map_or(Ok(()), |why| Err(Label::from(shown(why)))); app.addon_dialogs.tangent_radius = Some(open); host.with(|h| { @@ -362,6 +370,31 @@ mod tests { assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); } + #[test] + fn a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off() { + let mut app = app_with_lines(&[100, 140]); + let paths = count(&app); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(note(&app), None); + assert_eq!(count(&app), paths + 1); + // A control request locks the only layer while the dialog is open: no layer takes the circle, and OK is off. + app.run("layer.setProps", json!({"locked": true})).unwrap(); + let steps = undo_steps(&app); + frame(&mut app); + assert!(note(&app).is_some_and(|n| n.contains("locked")), "{:?}", note(&app)); + press_ok_while_off(&mut app); + assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps)); + // Unlocked again at the same radius: previewed, and OK draws the circle. + app.run("layer.setProps", json!({"locked": false})).unwrap(); + frame(&mut app); + assert_eq!(note(&app), None); + assert_eq!(count(&app), paths + 1); + assert!(press_ok(&mut app), "{}", app.ui.status); + assert_eq!(count(&app), paths + 1); + } + #[test] fn a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle() { let mut app = app_with_lines(&[100, 140]); diff --git a/docs/mcp.md b/docs/mcp.md index 089c971747..3e95f10cc0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15003,7 +15003,8 @@ Tools: which sets the radius, draws at once. The dialog's Radius starts at the radius of the circle found, and each radius previews the circle of that radius touching the second segments nearest the click, anywhere along the first segment (at the radius it opened with, the circle found). A radius that gives no circle there shows the note and leaves OK - off, as do an edit to either segment's path after the click and another active document; one outside 0.01 to + off, as do an edit to either segment's path after the click and another active document; a circle the target layer + cannot take (locked or hidden) shows why and leaves OK off; a radius outside 0.01 to 1000000 pt, typed or set, shows the radius error and leaves OK off, except the radius the dialog opened with. `ui.dialog.set` gives an error for a radius that is not a number. OK draws the circle in one undo step, with `shape.circleThroughPoints`, and with `autoUpdateDefault` on also sets `radius` to the radius given when diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9ff0b33a31..9ad4f4f030 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3057,7 +3057,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. -Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_click_found_radius_outside_the_tool_range_can_be_drawn` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. +Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) From d4acadfce9991e7bbec04db90007cb35e47aab9c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 17:39:26 -0800 Subject: [PATCH 07/42] Tangent Circle Tool: the radius dialog leaves another document's interaction alone After a switch to another document, the radius dialog forgets its preview instead of rolling back, since the switch already rolled it back in the document clicked in. Rolling back would cancel an interaction of the document now active. --- .../addons/pathtools/tangent_circle_radius.rs | 54 ++++++++++++++++--- docs/target-app-parity.md | 2 +- 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index a0be51829f..f96ada64eb 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -38,6 +38,8 @@ pub(crate) struct Open { /// under its rows with OK off; `None` while there is one. note: Option, preview: LivePreview, + /// The document that was active when the preview last ran (`DocState::uid`). + shown_in: Option, } /// Open the dialog on what the tool found (its [`tangent_circle::RADIUS_DIALOG`] parameters). @@ -49,8 +51,8 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { return; }; // An open the host replaces leaves its preview behind unless it is rolled back here. - if let Some(old) = app.addon_dialogs.tangent_radius.take() { - old.preview.cancel(app); + if let Some(mut old) = app.addon_dialogs.tangent_radius.take() { + take_preview(app, &mut old).cancel(app); } let lengths = general_lengths(app); let fields = DialogFields::from_pairs([("radius", FieldValue::Number(radius))]); @@ -60,13 +62,14 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { ParamDialog::new(KIND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true) }); let cancel: Box = Box::new(|app| { - if let Some(open) = app.addon_dialogs.tangent_radius.take() { - open.preview.cancel(app); + if let Some(mut open) = app.addon_dialogs.tangent_radius.take() { + take_preview(app, &mut open).cancel(app); } }); match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) { Some(id) => { - app.addon_dialogs.tangent_radius = Some(Open { id, click: p.clone(), doc, tried: None, note: None, preview: LivePreview::default() }); + app.addon_dialogs.tangent_radius = + Some(Open { id, click: p.clone(), doc, tried: None, note: None, preview: LivePreview::default(), shown_in: doc }); } None => app.status("no window"), } @@ -79,6 +82,19 @@ fn doc<'a>(app: &'a VectorcraftApp, open: &Open) -> Option<&'a Document> { app.session.doc().ok().filter(|s| s.uid == clicked).map(|s| &*s.doc) } +/// The id of the active document (`DocState::uid`). +fn active_uid(app: &VectorcraftApp) -> Option { + app.session.doc().ok().map(|s| s.uid) +} + +/// The dialog's live preview, taken out of `open`. With another document active than the one it previewed in, the +/// preview is forgotten instead: the switch already rolled it back there, and rolling back here would cancel an +/// interaction of the document now active. +fn take_preview(app: &VectorcraftApp, open: &mut Open) -> LivePreview { + let preview = std::mem::take(&mut open.preview); + if open.shown_in == active_uid(app) { preview } else { LivePreview::default() } +} + /// Whether `r` is in the tool's radius range. fn in_range(r: f64) -> bool { let (lo, hi) = tangent_circle::RADIUS_RANGE; @@ -137,7 +153,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { app.addon_dialogs.tangent_radius = Some(open); return; }; - let mut preview = std::mem::take(&mut open.preview); + let mut preview = take_preview(app, &mut open); let found = circle(app, &mut open, &fields); // Without a circle the preview rolls back; the preview reports its own failures on the status line. let previewed = match &found { @@ -146,6 +162,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { }; let _ = preview.run(app, previewed.0, "Tangent Circle", DRAW, &previewed.1); open.preview = preview; + open.shown_in = active_uid(app); // A target layer locked or hidden after the circle previewed refuses the draw: OK stays off. The preview stays, // since rolling it back would also roll back the edit that locked or hid the layer. open.note = found.err().or_else(|| target_refusal(app)); @@ -370,6 +387,31 @@ mod tests { assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); } + #[test] + fn a_switch_to_another_document_leaves_its_interaction_alone() { + let mut app = app_with_lines(&[100, 140]); + let paths = count(&app); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + // Another document comes to the front (which rolls the preview back in the first) and starts an interaction + // of its own before the dialog's next frame: the dialog leaves that interaction running. + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.begin_interaction("Other").unwrap(); + app.session.preview("path.create", &json!({"anchors": [{"x": 10, "y": 10}, {"x": 50, "y": 10}]})).unwrap(); + frame(&mut app); + assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE)); + assert!(app.session.in_interaction()); + assert_eq!(count(&app), 1); + // Cancel leaves it running too. + cancel(&app, dialog_id(&app)); + frame(&mut app); + assert!(!is_open(&app)); + assert!(app.session.in_interaction()); + assert_eq!(count(&app), 1); + } + #[test] fn a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off() { let mut app = app_with_lines(&[100, 140]); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9ad4f4f030..28033fbc9b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3057,7 +3057,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. -Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. +Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off`, `a_switch_to_another_document_leaves_its_interaction_alone` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) From e70619bc4a527420db46050b6fad3b04e75cb124 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:31:12 -0800 Subject: [PATCH 08/42] Tangent Circle Tool: a second click replaces the open radius dialog A click that asks for the radius while the dialog is still open (as a control request can send) closes the open dialog and rolls its preview back, and the new dialog takes over its held answer. Before, the new dialog lost its state to the old dialog's cancel and its OK could not draw. --- .../addons/pathtools/tangent_circle_radius.rs | 47 ++++++++++++++++++- docs/target-app-parity.md | 2 +- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index f96ada64eb..50032e300d 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -50,8 +50,18 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { app.status("no window"); return; }; - // An open the host replaces leaves its preview behind unless it is rolled back here. + // A dialog still open from an earlier click closes without an answer, and its preview is rolled back. The new + // dialog has its id (the dialog's kind), so the earlier dialog's held answer, with its OK and cancel hook, serves + // the new one. + let mut held = None; if let Some(mut old) = app.addon_dialogs.tangent_radius.take() { + if let Some(host) = app.dialogs() { + host.with(|h| { + h.cancel_by_id(&ctx, old.id); + let _ = h.take_by_id::(old.id); + }); + held = Some(host); + } take_preview(app, &mut old).cancel(app); } let lengths = general_lengths(app); @@ -66,7 +76,11 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { take_preview(app, &mut open).cancel(app); } }); - match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) { + let opened = match held { + Some(host) => Some(host.with(|h| h.open(dialog.held_ok()))), + None => open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }), + }; + match opened { Some(id) => { app.addon_dialogs.tangent_radius = Some(Open { id, click: p.clone(), doc, tried: None, note: None, preview: LivePreview::default(), shown_in: doc }); @@ -387,6 +401,35 @@ mod tests { assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); } + #[test] + fn a_second_click_replaces_the_open_dialog() { + let mut app = app_with_lines(&[100, 140]); + let (paths, steps) = (count(&app), undo_steps(&app)); + let open_ids = |app: &VectorcraftApp| app.dialogs().unwrap().with(|h| h.open_dialogs().iter().map(|d| d.id).collect::>()); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + // The first line stays picked: another click on the second (as a control request can send while the dialog + // is open) asks again in one dialog, previewing one circle. + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(open_ids(&app).len(), 1); + assert!(is_open(&app)); + assert_eq!(count(&app), paths + 1); + // Cancel closes it and rolls its preview back, with no undo step. + cancel(&app, dialog_id(&app)); + frame(&mut app); + assert!(!is_open(&app)); + assert!(open_ids(&app).is_empty()); + assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); + // Asked again, OK draws one circle in one undo step. + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert!(press_ok(&mut app), "{}", app.ui.status); + assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1)); + } + #[test] fn a_switch_to_another_document_leaves_its_interaction_alone() { let mut app = app_with_lines(&[100, 140]); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 28033fbc9b..a5dd8d1db7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3057,7 +3057,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangentCircle`; Object › Plug-ins › Path Precision Tools and the All Tools drawer) draws a circle on two clicked path segments: tangent to the first at the point clicked (its center on the normal there) and touching the second segment or one beside it on its subpath, the touch nearest the pointer winning. Shift gives the circle the tool's radius, and a drag from the second segment sets the radius to the drag's length (Shift: steps of 1, 2 or 5 times a power of 10 pt, at least 4 screen pixels; Cmd/Ctrl: a tenth of the movement); with a radius the circle may touch the first segment anywhere along it. Before the click the circle shows with its center, radii and radius, or a note says there is none. The circles are found by sampling the distance to the second segments along the first segment's normal (or along the first segment, for a radius) and taking the places where it equals the radius (samples, bisection where it crosses, and a search where it only touches). Left out are circles whose nearest point of the second segments is not on the circle (within a millionth of the radius: where the first segment turns back on itself the distance jumps past the radius without a touch), circles that cross the first segment, circles that touch both segments at one point, circles without a finite radius above 0, circles too small or too large for three of their points to give them back in floating point, and circles that would reach past the canvas; a circle found twice (the same center, touching the first segment at the same point) is kept once. The circle is a new ellipse with the current paint, one undo step; the first segment stays picked until it is drawn, also when drawing fails or the press is canceled, and the circles are looked for again when a live preview, or one that was canceled, changes either segment without an undo step (a changed first segment is forgotten). Tests: `tangent_circle::tests` in `vectorcraft-pathops` (parallel and crossing lines, a curved second segment, a corner's fillet, lines twice the radius apart, a touch between the places tried, the ends of a line with its handles on its anchors, a circle that crosses the first segment, a first segment that turns back, no circle), `addons::tangent_circle::tests` in `vectorcraft-tools` (two clicks, Shift and the radius option, a drag with Shift and Cmd/Ctrl, no circle and Escape, a canceled press, a canceled preview, a circle its three points cannot draw, a circle past the canvas), the session test for a failed draw in `vectorcraft-engine` and the Path Precision Tools menu, options, drawer and catalog tests in `vectorcraft-ui-egui`. Commands: `docs/mcp.md` › Path Precision Tools add-on. -Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off`, `a_switch_to_another_document_leaves_its_interaction_alone` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. +Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off`, `a_switch_to_another_document_leaves_its_interaction_alone`, `a_second_click_replaces_the_open_dialog` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) From 45b671a22b8857a33318ea4612f9ff5ef43ccaf0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:13:31 -0800 Subject: [PATCH 09/42] Tangent Circle Tool: the radius dialog keeps its preview after a failed OK OK hands the dialog's live preview a copy to commit, so a draw that is refused leaves the dialog owning the interaction it started, and Cancel or a radius with no circle still ends it. New test: a_failed_ok_keeps_the_preview_for_cancel. docs/target-app-parity.md and the module doc now say that Auto-Update Default sets the tool's Shift radius only for a radius from 0.01 to 1,000,000 pt. --- .../addons/pathtools/tangent_circle_radius.rs | 39 +++++++++++++++++-- docs/target-app-parity.md | 2 +- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index 50032e300d..e77ea59286 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -4,7 +4,7 @@ //! nearest the click ([`tangent_circle::radius_circle`]). A radius that gives no circle there shows //! the tool's note and leaves OK off, as does an edit to either segment after the click. OK draws //! the circle with `shape.circleThroughPoints` in one undo step, and with Auto-Update Default on -//! also sets the tool's `radius` to the one given; Cancel draws nothing. +//! also sets the tool's `radius` to the one given when it is in the tool's range; Cancel draws nothing. use craft::ui::contract::Bind; use craft::ui::dialog::DialogId; @@ -202,8 +202,8 @@ fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { } }; let auto = app.session.tool_options_of(tangent_circle::ID).get("autoUpdateDefault").and_then(Value::as_bool) == Some(true); - let preview = std::mem::take(&mut open.preview); - if let Err(e) = preview.commit(app, DRAW, points) { + // A failed commit leaves the interaction running: the dialog keeps its preview, so Cancel still ends it. + if let Err(e) = open.preview.clone().commit(app, DRAW, points) { app.addon_dialogs.tangent_radius = Some(open); return Err(e); } @@ -382,6 +382,39 @@ mod tests { assert_eq!(count(&app), paths); } + #[test] + fn a_failed_ok_keeps_the_preview_for_cancel() { + let mut app = app_with_lines(&[100, 140]); + let (paths, steps) = (count(&app), undo_steps(&app)); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + // The layer the preview started from is locked before OK, so OK's draw is refused and the dialog stays open. + { + let st = app.session.doc_mut().unwrap(); + let layer = st.doc.layers[0].id; + let it = st.interaction.as_mut().unwrap(); + std::sync::Arc::make_mut(&mut it.doc).node_mut(layer).unwrap().locked = true; + } + let id = dialog_id(&app); + assert!(confirm(&app, id), "OK is on"); + frame(&mut app); + assert!(is_open(&app)); + assert!(app.session.in_interaction()); + // The dialog still owns the interaction: a radius with no circle there ends it. + set(&app, id, "radius", json!(25)); + frame(&mut app); + assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE)); + assert!(!app.session.in_interaction()); + // Cancel closes it with nothing drawn and no undo step. + cancel(&app, id); + frame(&mut app); + assert!(!is_open(&app)); + assert!(!app.session.in_interaction()); + assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); + } + #[test] fn a_click_found_radius_outside_the_tool_range_can_be_drawn() { // Lines 2,400,000 pt apart: a click on each finds the circle of radius 1,200,000, past the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 49f56abbf7..8953bf2a73 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3078,7 +3078,7 @@ A VectorCraft addition, so no area score moves. The Tangent Circle Tool (`tangen The tool's options dialog also sets the preview and how a segment is picked, the options the help page lists (https://docs.astutegraphics.com/subscribe/tangent-circle-tool): Circle Center and Circle Radii Lines (`center`, `radii`) show or hide the center cross and the radii, Color (`color`: red, blue, magenta, green, black or gray) colors the circle, the cross, the radii and the note, Snap Tolerance (`snapTolerance`, screen pixels) is how near the pointer picks a segment with Smart Guides on, the Smart Guides Snapping Tolerance counting when it is larger, and Snap When Smart Guides Are Off (`snapWithoutGuides`) keeps that reach with Smart Guides off; without it the Selection Tolerance applies. Of the segments within reach the nearest is picked. The defaults (both shown, red, 3 px, snapping on) and the 0 to 25 px range are VectorCraft's own; they are kept with the preferences, and `tool.setOption` gives an error for a value an option does not take. Tests: `addons::tangent_circle::tests` in `vectorcraft-tools` (the preview options, the snapping reach, the options' values) and `the_tangent_circle_options_set_the_preview_and_snapping` in `vectorcraft-ui-egui`. -Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off`, `a_switch_to_another_document_leaves_its_interaction_alone`, `a_second_click_replaces_the_open_dialog` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. +Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius when it is from 0.01 to 1,000,000 pt. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_failed_ok_keeps_the_preview_for_cancel`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off`, `a_switch_to_another_document_leaves_its_interaction_alone`, `a_second_click_replaces_the_open_dialog` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) From 2978eb831a6d72ba765c654f2c8a8e872272496f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:47:35 -0800 Subject: [PATCH 10/42] Tangent Circle Tool: test Cancel straight after a refused OK --- .../addons/pathtools/tangent_circle_radius.rs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index e77ea59286..7a58e65095 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -415,6 +415,33 @@ mod tests { assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); } + #[test] + fn cancel_right_after_a_failed_ok_rolls_the_preview_back() { + let mut app = app_with_lines(&[100, 140]); + let (paths, steps) = (count(&app), undo_steps(&app)); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + { + let st = app.session.doc_mut().unwrap(); + let layer = st.doc.layers[0].id; + let it = st.interaction.as_mut().unwrap(); + std::sync::Arc::make_mut(&mut it.doc).node_mut(layer).unwrap().locked = true; + } + let id = dialog_id(&app); + assert!(confirm(&app, id), "OK is on"); + frame(&mut app); + assert!(is_open(&app)); + assert!(app.session.in_interaction()); + // Cancel is the next press after the refused OK, with no radius change or other frame in between. + cancel(&app, id); + frame(&mut app); + assert!(!is_open(&app)); + assert!(!app.session.in_interaction()); + assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); + } + #[test] fn a_click_found_radius_outside_the_tool_range_can_be_drawn() { // Lines 2,400,000 pt apart: a click on each finds the circle of radius 1,200,000, past the From 776a1fd6cda5e5eb358c8c81eb95a01e6c481830 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 06:39:32 -0800 Subject: [PATCH 11/42] Test262: match Promise async markers by argument --- crates/js/tests/test262.rs | 41 ++++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index bd8c406b79..e03708fc6a 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -918,31 +918,46 @@ fn promise_builtins_run() { handle.join().unwrap(); } -/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global -/// `print` that collects its output; an `async` test passes when it prints -/// `Test262:AsyncTestComplete`. +#[test] +fn promise_async_completion_requires_an_exact_print_argument() { + assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true).is_err()); + assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true).is_err()); + assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true).is_ok()); + assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true).is_ok()); +} + +#[test] +fn promise_async_failure_checks_each_print_argument() { + assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true).is_err()); + assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true).is_ok()); +} + +/// Runs one Promise test with a global `print` that collects every argument. An `async` test +/// needs an exact `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix. fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { let options = Options { es2015: true, ..Options::default() }; let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); - let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); let out = printed.clone(); realm.define_function("print", move |args| { - let line = match args.first() { - Some(JsValue::String(s)) => s.clone(), - Some(other) => format!("{other:?}"), - None => String::new(), - }; - out.borrow_mut().push_str(&line); - out.borrow_mut().push('\n'); + let mut printed = out.borrow_mut(); + for arg in args { + printed.push(match arg { + JsValue::String(s) => s.clone(), + other => format!("{other:?}"), + }); + } Ok(JsValue::Undefined) }); let result = realm.run(script); if asynchronous && result.is_ok() && negative_type.is_none() { let printed = printed.borrow(); - return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { + return if printed.iter().any(|arg| arg == "Test262:AsyncTestComplete") + && !printed.iter().any(|arg| arg.starts_with("Test262:AsyncTestFailure")) + { Ok(()) } else { - Err(format!("printed {:?}", printed.trim())) + Err(format!("printed {printed:?}")) }; } match (result, negative_type) { From bb3ceb56b81cd9c9ebb3466ab1c03731b96689e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 10:57:43 -0800 Subject: [PATCH 12/42] Charge Symbol registry hashing and correct key buffer reservations --- Cargo.lock | 2 +- crates/js/src/builtins/symbol.rs | 7 ++++--- crates/js/src/lib.rs | 3 ++- crates/js/src/symbol_tests.rs | 28 ++++++++++++++++++++++++++++ docs/mcp.md | 3 +++ docs/target-app-parity.md | 2 ++ 6 files changed, 40 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 653aa64e73..905d33b8fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8480,7 +8480,7 @@ dependencies = [ "proptest", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", ] diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index b671f51e42..b709a1caf1 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -5,7 +5,7 @@ //! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only. use super::{arg, constructor, create_at, data, method, native, new_array}; -use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes}; +use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES}; use crate::interp::{Hint, Interp, JsResult}; use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown}; use crate::value::{Str, Value}; @@ -87,11 +87,12 @@ fn symbol_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) - fn symbol_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let key = interp.to_str(&arg(args, 0))?; let units = crate::string_builtins::flat_charged(interp, &key)?; + crate::string_builtins::charge_units(interp, units.len())?; if let Some(v) = interp.symbols.registry.get(&*units) { return Ok(v.clone()); } - let extra = REGISTRY_ENTRY_BYTES.saturating_add(string_bytes(units.len())); - let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, extra)?; + crate::string_builtins::charge_units(interp, units.len())?; + let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, REGISTRY_ENTRY_BYTES)?; interp.symbols.registry.insert(units, Value::Symbol(sym.clone())); Ok(Value::Symbol(sym)) } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 17f2b1de0f..f903a9519f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -77,7 +77,8 @@ //! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a //! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator //! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry -//! entry counts against the heap limit. +//! entry counts against the heap limit. Registry lookups and insertions take fuel for the key's +//! code units, and a registered description shares the key's existing buffer. //! //! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section //! 25.6, ): the constructor, `then`, diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index 2ddd86828a..c91a493424 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -57,6 +57,34 @@ fn symbol_for_and_key_for_use_the_registry() { throws("Symbol.for(Symbol())", "TypeError"); } +#[test] +fn symbol_registry_hashing_charges_flat_keys_on_hits_and_misses() { + for hit in [false, true] { + let mut realm = es2015(Limits::default()); + let key = "x".repeat(32_768); + assert_eq!(realm.run(&format!("var registryKey = '{key}';")), Ok(JsValue::Undefined)); + if hit { + assert_eq!(realm.run("typeof Symbol.for(registryKey)"), Ok(JsValue::String("symbol".into()))); + } + realm.set_limits(Limits { fuel: 500, ..Limits::default() }); + assert!(matches!(realm.run("Symbol.for(registryKey)"), Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. })), "hit={hit}"); + realm.set_limits(Limits { fuel: 10_000, ..Limits::default() }); + assert_eq!(realm.run("Symbol.for(registryKey) === Symbol.for(registryKey)"), Ok(JsValue::Bool(true))); + } +} + +#[test] +fn symbol_registry_keeps_a_flat_key_buffer_only_once() { + let mut realm = es2015(Limits::default()); + let key = "x".repeat(32_768); + assert_eq!(realm.run(&format!("var sharedKey = '{key}';")), Ok(JsValue::Undefined)); + let used = realm.collect_garbage(); + let room = crate::heap::SYMBOL_BYTES + crate::symbol::REGISTRY_ENTRY_BYTES + 4_096; + realm.set_limits(Limits { heap_bytes: used + room, ..Limits::default() }); + assert_eq!(realm.run("var registered = Symbol.for(sharedKey); Symbol.keyFor(registered) === sharedKey"), Ok(JsValue::Bool(true))); + assert!(realm.collect_garbage() <= used + room); +} + #[test] fn implicit_conversion_of_a_symbol_throws_a_type_error() { throws("Symbol() + ''", "TypeError"); diff --git a/docs/mcp.md b/docs/mcp.md index a12daa1b46..08bbc6d0c1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2695,6 +2695,9 @@ vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' ``` `script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. + +In an ES2015 realm, `Symbol.for` lookups and insertions take fuel for the key's code units. A registered description +shares the key's existing string buffer. File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d56d4fd4cd..bf6293240a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -32,6 +32,8 @@ ## Feature submission evidence +`Symbol.for` lookups and insertions take fuel for the key's code units, including registry hits on flat strings. A registered description shares the key's existing buffer. Regressions in `crates/js/src/symbol_tests.rs` cover hits, misses, and registering a rooted flat key when the heap has room for metadata but not another key buffer. + `vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings. History panel row context menus (2026-11-20, G12): Right-clicking any state offers New Document from State, Step to This State, and Clear History. Creating a document uses the clicked snapshot without stepping the source document; Step to This State uses undo/redo and is disabled on the current row; Clear History removes undo and redo steps without changing artwork and is disabled when history is empty. Headless tests in `crates/ui-egui/src/panels/history.rs` cover opening an earlier row menu, snapshot creation, backward/forward jumps, and clearing history. The snapshot chosen when the menu opens is retained while it stays open; pending tool edits are settled before resolving that snapshot to its new row; a discarded snapshot reports that it is unavailable instead of acting on a neighboring row. Jumps settle pending typing before counting undo/redo steps. Shift+F10 opens the focused row menu; Escape dismisses it and restores row focus. Switching documents dismisses the menu before it can act on another document. Headless tests cover these keyboard and document-switch paths. The list and menu use shared Craft UI controls. Scores and estimates unchanged. From bcb9b7b4cd3614c55c938b76f805813b0afcbfae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 08:22:59 -0800 Subject: [PATCH 13/42] Restore future shape settings when Control bar edits cancel --- crates/ui-egui/src/addons/shapes.rs | 291 +++++++++++++++++++++++++++- docs/mcp.md | 8 +- docs/ui-parity.md | 3 +- 3 files changed, 296 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index a134adeab4..e5fde5725e 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -1,11 +1,12 @@ //! The 3D Box and customizable shapes add-on in the interface: its submenu (Object › Plug-ins › //! 3D Box), which selects the 3D Box tool, and the context-sensitive Control bar options shown //! when a shape tool (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `spiral`, -//! `box3d`) is active. +//! `box3d`) is active. Canceling a numeric edit restores its future-tool options, including coupled +//! scalar and per-corner radii; a retired edit cannot restore options into a different tool. use std::ops::RangeInclusive; -use craft::behavior::{IconId, NumberCodec}; +use craft::behavior::{CancelReason, EditEvent, GestureId, IconId, NumberCodec}; use craft::menu::Node; use craft::ui::buttons::{Button, ToggleButton}; use craft::ui::choice::Segmented; @@ -16,7 +17,7 @@ use craft::ui::layout_components::Row; use craft::ui::runtime::env::{Env, LengthUnits, UnitKind}; use craft::ui::text::NumberField; use egui::Ui; -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use vectorcraft_geom::shapes::EllipseMode; use vectorcraft_tools::addons::box3d::{self, CustomShape}; @@ -171,7 +172,7 @@ fn number( response = field.take().map(|field| field.show(ui).edit); }); if let Some(response) = response { - edits::apply_edits(app, &response, EditPath::Preview, |app, value, phase| { + shape_number_edits(app, ui.ctx(), key, &response, |app, value, phase| { if let Some(value) = *value { apply(app, value, phase); } @@ -180,6 +181,104 @@ fn number( }); } +#[derive(Clone)] +struct ShapeToolGesture { + id: GestureId, + tool: String, + target: Option<(u64, u64, Vec)>, + opening: Map, + latest: Value, +} + +fn shape_target(app: &VectorcraftApp) -> Option<(u64, u64, Vec)> { + app.session.active().map(|st| (st.uid, st.reverts, st.selection.objects.clone())) +} + +/// Tool options are outside the document preview snapshot. A canceled scrub restores this +/// field's complete option group, including settings that the rollback changes indirectly. +fn shape_number_edits( + app: &mut VectorcraftApp, + ctx: &egui::Context, + field: &'static str, + response: &EditResponse>, + mut apply: impl FnMut(&mut VectorcraftApp, &Option, Live), +) { + let keys: &[&str] = match field { + "arc-start" => &["arcStart", "arcMode"], + "arc-end" => &["arcEnd", "arcMode"], + "rect-r" => &["cornerRadius", "cornerRadii"], + "rect-tl" | "rect-tr" | "rect-br" | "rect-bl" => &["cornerRadii", "cornerRadius"], + "poly-corners" => &["sides", "points"], + "poly-spoke" => &["starRatio"], + "poly-round" => &["rounded"], + "poly-rand" => &["randomized"], + "spiral-turns" => &["turns"], + "spiral-div" => &["divergence"], + "spiral-inner" => &["innerRadius"], + _ => std::slice::from_ref(&field), + }; + let key = response.response.id.with("shape-tool-gesture"); + let mut held = ctx.data(|data| data.get_temp::(key)); + for event in response.events.iter() { + if let EditEvent::Begin { id, .. } = event { + let latest = app.session.tool_options(); + held = Some(ShapeToolGesture { + id: *id, + tool: app.session.tool_id().to_owned(), + target: shape_target(app), + opening: keys.iter().filter_map(|key| latest.get(*key).cloned().map(|value| ((*key).to_owned(), value))).collect(), + latest, + }); + } + let restore = if let EditEvent::Cancel { id, before, reason, .. } = event { + if held.as_ref().is_some_and(|snapshot| snapshot.id == *id) { + held.take().filter(|snapshot| { + before.is_some() + && !reason.document_moved() + && *reason != CancelReason::Removed + && snapshot.tool == app.session.tool_id() + && snapshot.target == shape_target(app) + && snapshot.latest == app.session.tool_options() + }) + } else { + None + } + } else { + None + }; + edits::apply_event(app, event, &EditPath::Preview, &mut apply); + if let Some(snapshot) = restore { + // Radius writes the array with symmetry on; the array writes the scalar either way. + // Each row's order restores its full representation rather than sorted JSON keys. + for key in keys { + if let Some(value) = snapshot.opening.get(*key) + && let Err(error) = app.run("tool.setOption", json!({"tool": snapshot.tool, "key": key, "value": value})) + { + app.status(error); + break; + } + } + } + match event { + EditEvent::Update { id, .. } => { + if let Some(snapshot) = held.as_mut().filter(|snapshot| snapshot.id == *id) { + let latest = app.session.tool_options(); + snapshot.latest = latest; + } + } + EditEvent::Commit { id, .. } if held.as_ref().is_some_and(|snapshot| snapshot.id == *id) => held = None, + EditEvent::Set { .. } => held = None, + _ => {} + } + } + ctx.data_mut(|data| { + data.remove::(key); + if let Some(snapshot) = held { + data.insert_temp(key, snapshot); + } + }); +} + /// A click's change of the shape: the tool's options, and the selected live shapes in one step. fn apply_shape(app: &mut VectorcraftApp, tool_kvs: &[(&str, Value)], live_patch: Value) { shape_edit(app, tool_kvs, live_patch, Live::Released); @@ -423,6 +522,190 @@ fn mode_str(m: EllipseMode) -> &'static str { } } +#[cfg(test)] +mod cancel_tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers, vec2}; + + fn window(app: &mut VectorcraftApp, ui: &mut Ui) { + app.tick(ui.ctx()); + app.ui(ui); + } + + fn application() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + app.run("window.control", json!({})).unwrap(); + app + } + + fn radius(panel: &Panel, node: vectorcraft_doc::NodeId) -> [f64; 4] { + let app = panel.app(); + let shape = CustomShape::read_for_update(app.session.active().unwrap().doc.node(node).unwrap(), false).unwrap(); + let CustomShape::Rectangle { radii, .. } = shape else { panic!("the fixture is a live rectangle") }; + radii + } + + #[test] + fn a_canceled_radius_scrub_restores_future_tool_options_and_selected_geometry() { + for tool in ["roundedRectangle", "box3d"] { + for selected in [false, true] { + for cancel in [false, true] { + let mut app = application(); + let node = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 80, "radius": 3.5})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("tool.select", json!({"tool": tool})).unwrap(); + let values = if tool == "box3d" { + json!({"shape": "rectangle", "cornerSymmetry": true, "cornerRadius": 7.25, "cornerRadii": [7.25, 8.25, 9.25, 10.25]}) + } else { + json!({"cornerRadius": 7.25}) + }; + app.run("tool.setOption", json!({"values": values})).unwrap(); + if tool == "box3d" { + app.run("tool.setOption", json!({"key": "cornerRadii", "value": [7.25, 8.25, 9.25, 10.25]})).unwrap(); + assert_eq!(app.session.tool_options()["cornerRadii"], json!([7.25, 8.25, 9.25, 10.25])); + } + app.run("select.set", json!({"ids": if selected { vec![node] } else { vec![] }})).unwrap(); + let options = app.session.tool_options(); + let original = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, window); + panel.room(vec2(2200.0, 1000.0)); + panel.frame(); + panel.frame(); + panel.drag_hold_role("Radius", Role::LABEL, vec2(12.0, 0.0)); + let changed = panel.app().session.tool_options(); + assert_ne!(changed, options, "the actual side-label scrub updates the future shape settings"); + if selected { + assert_ne!(radius(&panel, vectorcraft_doc::NodeId(node)), [3.5; 4], "the selected shape previews the scrub"); + } + if cancel { + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!( + panel.app().session.tool_options(), + options, + "Escape restores the exact original tool settings, including coupled radii" + ); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + panel.release(); + assert_eq!( + panel.app().session.tool_options(), + if cancel { options.clone() } else { changed.clone() }, + "release after Escape cannot reapply the scrub" + ); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + usize::from(selected && !cancel)); + if selected && !cancel { + panel.app().run("edit.undo", json!({})).unwrap(); + } + assert_eq!(panel.app().session.active().unwrap().doc, original); + + // A normal subsequent canvas drag uses the settings that the field left behind. + let from = panel.app().canvas_view().unwrap().rect.min + vec2(120.0, 120.0); + panel.drag_between(from, from + vec2(100.0, 80.0), Modifiers::NONE); + let created = panel.app().session.active().unwrap().selection.objects[0]; + assert_ne!(created.0, node, "the canvas drag creates new art rather than grabbing the selected shape's widgets"); + let expected = if cancel { &options } else { &changed }; + let radii = if tool == "box3d" && expected["cornerSymmetry"].as_bool() == Some(false) { + std::array::from_fn(|i| expected["cornerRadii"][i].as_f64().unwrap()) + } else { + [expected["cornerRadius"].as_f64().unwrap(); 4] + }; + assert_eq!(radius(&panel, created), radii, "the next shape uses the accepted or restored defaults"); + } + } + } + } + + #[test] + fn a_retired_shape_scrub_cannot_restore_options_into_the_new_tool() { + let mut app = application(); + app.run("tool.select", json!({"tool": "roundedRectangle"})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadius", "value": 7.25})).unwrap(); + let mut panel = Panel::new(app, window); + panel.room(vec2(2200.0, 1000.0)); + panel.frame(); + panel.frame(); + panel.drag_hold_role("Radius", Role::LABEL, vec2(12.0, 0.0)); + assert_ne!(panel.app().session.tool_options()["cornerRadius"], json!(7.25)); + panel.app().run("tool.select", json!({"tool": "ellipse"})).unwrap(); + let before = panel.app().session.tool_options(); + let document = panel.app().session.active().unwrap().doc.clone(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.frame(); + panel.key(Key::Escape, Modifiers::NONE); + panel.release(); + assert_eq!(panel.app().session.tool_id(), "ellipse"); + assert_eq!(panel.app().session.tool_options(), before, "retired Radius events cannot edit the replacement tool"); + assert_eq!(panel.app().session.active().unwrap().doc, document); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + + #[test] + fn a_canceled_corner_edit_restores_a_scalar_changed_only_by_rollback() { + let mut app = application(); + app.run("tool.select", json!({"tool": "box3d"})).unwrap(); + app.run("tool.setOption", json!({"values": {"shape": "rectangle", "cornerSymmetry": false}})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadii", "value": [7.25, 8.25, 9.25, 10.25]})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadius", "value": 4.125})).unwrap(); + let before = app.session.tool_options(); + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, window); + panel.room(vec2(2200.0, 1000.0)); + panel.frame(); + panel.click_role("TL", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("4.125"); + panel.frame(); + let proposed = panel.app().session.tool_options(); + assert_ne!(proposed["cornerRadii"], before["cornerRadii"]); + assert_eq!(proposed["cornerRadius"], before["cornerRadius"], "the edit leaves the hidden scalar unchanged"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(panel.app().session.tool_options(), before, "rollback must restore the scalar even when only restoring the array would change it"); + assert_eq!(panel.app().session.active().unwrap().doc, document); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + + #[test] + fn canceled_individual_corner_scrubs_preserve_the_distinct_hidden_scalar_radius() { + for label in ["TL", "TR"] { + for cancel in [false, true] { + let mut app = application(); + app.run("tool.select", json!({"tool": "box3d"})).unwrap(); + app.run("tool.setOption", json!({"values": {"shape": "rectangle", "cornerSymmetry": false}})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadii", "value": [7.25, 8.25, 9.25, 10.25]})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadius", "value": 4.125})).unwrap(); + let before = app.session.tool_options(); + assert_eq!(before["cornerRadius"], json!(4.125)); + assert_eq!(before["cornerRadii"], json!([7.25, 8.25, 9.25, 10.25])); + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, window); + panel.room(vec2(2200.0, 1000.0)); + panel.frame(); + panel.frame(); + panel.drag_hold_role(label, Role::LABEL, vec2(12.0, 0.0)); + let proposed = panel.app().session.tool_options(); + assert_ne!(proposed["cornerRadii"], before["cornerRadii"]); + assert_ne!(proposed["cornerRadius"], before["cornerRadius"], "the array setter also changes the hidden scalar"); + if cancel { + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options(), before, "both the array and its distinct scalar restore before release"); + } + panel.release(); + assert_eq!(panel.app().session.tool_options(), if cancel { before } else { proposed }); + assert_eq!(panel.app().session.active().unwrap().doc, document); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + } + } +} + #[cfg(test)] mod tests { use craft::behavior::IconId; diff --git a/docs/mcp.md b/docs/mcp.md index 808f600e69..bcd96973f9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # VectorCraft MCP server -> **Last updated:** 2026-11-18 · **Change:** Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. +> **Last updated:** 2026-11-27 · **Change:** Shape Control bar: canceled numeric edits restore future tool settings and coupled corner radii; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). @@ -8480,6 +8480,11 @@ and files saved without it open with it off. {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"Letter","alignNewObjectsToPixelGrid":true}}} ``` +The shape Control bar's numeric edits preview changes to selected shapes and future tool settings together. +Cancel restores both, including the separate scalar radius and per-corner radii. Accept keeps the new settings; +Undo restores the selected artwork. A canceled edit whose tool or document ownership has ended cannot overwrite +the new tool's settings. + ## Live Corners `object.setLiveShape {id?, ids?, radius?, kind?, corners?, rectanglesOnly?, items?}` sets the corners of any path (one undo step): a live @@ -17024,6 +17029,7 @@ the error text. The interactive fallback applies only to ordinary File > Save, n | Date | Change | |---|---| +| 2026-11-27 | Shape Control bar: canceled numeric edits restore future-tool settings and coupled radii along with selected artwork; retired edits cannot overwrite a different tool. Native scrub, keyboard, next-shape and Undo cases covered. Scores and estimates unchanged. | | 2026-11-18 | Production Preflight: output and artboard scope, four check summaries, clickable canvas ids, effective PPI and explicit unchecked resolution coverage. | | 2026-11-14 | Built-in Tech Circuit brush library (id `tech-circuit`): Circuit Trace, Bus Lines and Terminal Nodes; ten built-in libraries. | | 2026-11-13 | The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides; Snap to Grid and Snap to Pixel still move its ends (#7252). | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9b146bfcd4..b4dfe0adcc 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (Shape Control bar: canceled numeric edits restore future tool settings and coupled corner radii; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -70,6 +70,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-27 | minor | Shape Control bar: canceled numeric edits restore future-tool settings and coupled radii along with selected artwork; retired edits cannot overwrite a different tool. Native scrub, keyboard, next-shape and Undo cases covered. Scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | From 5433e02d8e2512f1ffd478cedf39d44bb74a1e3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 13:21:04 -0800 Subject: [PATCH 14/42] Selection: a click inside an unfilled closed shape selects it With Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection now pick a closed path or compound path that has no fill by a click inside its closed subpaths. Before, such a shape could only be picked on its path, and a click inside started a marquee. The inside counts only where no other object is hit: a click first looks for what paints at the point, the same as before, and only then for the topmost unfilled closed shape around it, so art drawn inside a frame is still picked before the frame. Select Behind lists those shapes after the objects that paint there, and Direct Selection in a dynamic symbol's art picks parts in the same order. Open paths, guides and clipping paths are still picked by their path only, and Outline view is unchanged. With Object Selection by Path Only on, the inside of an unfilled shape takes no click, as before. Three tests clicked inside an unfilled square and expected nothing to be selected: the Selection and Direct Selection center point tests and the outside-stroke reach test. They now run with Object Selection by Path Only on, and the Direct Selection and stroke reach tests also check that the click selects the square with it off. Fixes #9175 --- crates/doc/src/hit.rs | 130 +++++++++++++++++--- crates/doc/src/hit/tests.rs | 163 +++++++++++++++++++++++++ crates/engine/src/tests/strokereach.rs | 6 + crates/mcp/src/tests.rs | 26 ++++ crates/tools/src/context.rs | 8 +- crates/tools/src/direct/tests.rs | 9 +- crates/tools/src/select/tests.rs | 5 +- crates/ui-egui/src/canvas/outline.rs | 9 +- docs/mcp.md | 3 + docs/target-app-parity.md | 2 + 10 files changed, 332 insertions(+), 29 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6d5cb0f1a5..a69308968c 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -81,6 +81,11 @@ pub struct HitOptions { /// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`]) /// hit the art on a layer whose Preview is off as painted, not in outline. pub ignore_layer_preview: bool, + /// The selection tools: where a click hits nothing else, a closed path or compound path with + /// no fill is hit inside its closed subpaths, the topmost first, as a filled one is. Off with + /// [`Self::path_only`] and in outline. Clipping paths and guides are still hit on their + /// outline only. [`hit_test`] and [`objects_at`] try every other object first. + pub unfilled_interiors: bool, } impl Default for HitOptions { @@ -94,6 +99,7 @@ impl Default for HitOptions { clip_outlines: false, area_type_interior: false, ignore_layer_preview: false, + unfilled_interiors: false, scope: None, } } @@ -417,11 +423,35 @@ impl Drop for DrawnOff { } } +thread_local! { + /// Whether a clipping path is being tested ([`InMask`]). + static IN_MASK: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While a guard lives, a clipping path is tested: it is not hit inside by its interior alone +/// ([`takes_interior`]). +struct InMask { + was: bool, +} + +impl InMask { + fn set() -> Self { + Self { was: IN_MASK.replace(true) } + } +} + +impl Drop for InMask { + fn drop(&mut self) { + IN_MASK.set(self.was); + } +} + /// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a /// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to -/// the region it clips to. +/// the region it clips to. It is also under an [`InMask`] guard. fn plain(mask: bool, f: impl FnOnce() -> T) -> T { let _off = mask.then(DrawnOff::set); + let _mask = mask.then(InMask::set); f() } @@ -636,17 +666,23 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option bool, editable_only: bool) -> Option { + let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only); + if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline { + return painted; + } + hit_test_walk(doc, p, opt, skip, editable_only) +} + +/// One walk of [`hit_test_skipping`], with `opt` as given. +fn hit_test_walk(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option { let _walk = ArtWalk::open(); let finish = |mut h: Hit| { h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents)); @@ -1378,7 +1425,10 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: & return false; } } - hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))) + hit_order(n, children, p).any(|i| { + let _mask = (i == 0 && n.clips()).then(InMask::set); + children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)) + }) } _ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)), } @@ -1467,6 +1517,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio match &n.kind { NodeKind::Path { path, rule, .. } => { let has_fill = n.appearance.has_visible_fill(); + let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt); + let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill); if opt.outline && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) { @@ -1501,7 +1553,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio return Some(HitKind::Stroke); } if !near_decoration { - return None; + return inside(); } } let bp = path.to_bezpath(); @@ -1511,7 +1563,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) { return Some(HitKind::Fill); } - None + inside() } NodeKind::Compound { children, rule } => { // Painted strokes follow the whole compound path (alignment, dashes, width profiles): @@ -1529,7 +1581,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { return Some(HitKind::Outline); } - (!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) + if n.appearance.has_visible_fill() { + return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill); + } + let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p); + (takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { @@ -1601,6 +1657,30 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } } +/// Is path or compound path `n`, which has no visible fill, hit inside its closed subpaths +/// ([`HitOptions::unfilled_interiors`])? Not a clipping path ([`InMask`]) or a guide. +fn takes_interior(n: &Node, opt: HitOptions) -> bool { + opt.unfilled_interiors + && !opt.outline + && !opt.path_only + && !IN_MASK.get() + && !matches!(n.kind, NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. }) +} + +/// The closed subpaths of `paths` whose control points' box holds `p`, as one path. A path outside +/// that box winds zero times round `p`, so this path's fill holds `p` as all the closed subpaths' +/// fill does. Open subpaths are left out: they bound no area. +fn closed_subpaths_at<'a>(paths: impl IntoIterator, p: Point) -> BezPath { + let holds = |b: Rect| b.x0 <= p.x && p.x <= b.x1 && b.y0 <= p.y && p.y <= b.y1; + let mut bp = BezPath::new(); + for pd in paths.into_iter().filter(|pd| pd.control_bounds().is_some_and(holds)) { + for sp in pd.subpaths.iter().filter(|sp| sp.closed) { + sp.to_bezpath_into(&mut bp); + } + } + bp +} + /// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a /// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a /// stroke along its shape, a fill inside it except with Selection by Path Only. @@ -1877,13 +1957,23 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a /// symbol instance or no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { - let _walk = ArtWalk::open(); + let walk = ArtWalk::open(); let outline = opt.outline || below_preview_off(doc, inst, opt.scope); let art = InstanceArt::drawn(doc, inst, outline)?; let symbols = doc.kept_symbol_boxes(); - let mut path = vec![]; - let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true }; - find.find(&art.art, &mut path, None, outline).map(|_| path) + let pick = |opt: HitOptions| { + let mut path = vec![]; + let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true }; + find.find(&art.art, &mut path, None, outline).map(|_| path) + }; + // As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit. + pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| { + if !opt.unfilled_interiors || opt.path_only || outline { + return None; + } + walk.restart(); + pick(opt) + }) } /// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make. diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index a16b3ad149..5aa7dac4ee 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -38,6 +38,168 @@ fn unfilled_interior_misses() { assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some()); } +/// The selection tools' options with unfilled closed paths hit inside. +const INTERIORS: HitOptions = HitOptions { unfilled_interiors: true, ..SELECTING }; + +/// A path of `points` with a black stroke and no fill, inserted at the top of the first layer. +fn stroked(d: &mut Document, points: &[(f64, f64)], closed: bool) -> NodeId { + let l = d.layers[0].id; + let id = d.alloc_id(); + let pts: Vec = points.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed)); + d.insert(Some(l), 99, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap(); + id +} + +const FRAME: [(f64, f64); 4] = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + +#[test] +fn an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline() { + let mut d = Document::new(200.0, 200.0); + let frame = stroked(&mut d, &FRAME, true); + let at = |opt: HitOptions| hit_test(&d, Point::new(50.0, 50.0), opt).map(|h| h.leaf); + assert_eq!(at(INTERIORS), Some(frame)); + assert_eq!(at(SELECTING), None, "without the option, the interior misses"); + assert_eq!(at(HitOptions { path_only: true, ..INTERIORS }), None, "Object Selection by Path Only"); + assert_eq!(at(HitOptions { outline: true, ..INTERIORS }), None, "Outline view"); + assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![frame]); + assert!(objects_at(&d, Point::new(150.0, 50.0), INTERIORS, None).is_empty(), "outside it"); +} + +#[test] +fn an_open_path_is_not_hit_inside() { + let mut d = Document::new(200.0, 200.0); + stroked(&mut d, &FRAME, false); + assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None); +} + +/// What a click paints over comes first: an object drawn inside an unfilled frame above it is hit +/// where it paints, and the frame elsewhere inside; Select Behind lists the frame after it. +#[test] +fn art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let dot = d.alloc_id(); + d.insert(Some(l), 0, Node::path(dot, shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art())).unwrap(); + let frame = stroked(&mut d, &FRAME, true); + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf); + assert_eq!(at(&d, 50.0), Some(dot)); + assert_eq!(at(&d, 20.0), Some(frame)); + assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![dot, frame]); + // The topmost of two unfilled frames is hit inside both. + let inner = stroked(&mut d, &[(10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)], true); + assert_eq!(at(&d, 20.0), Some(inner)); + assert_eq!(at(&d, 5.0), Some(frame)); +} + +#[test] +fn an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look())); + let (id, outer, hole) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let members = vec![ring(outer, Rect::new(0.0, 0.0, 100.0, 100.0)), ring(hole, Rect::new(30.0, 30.0, 70.0, 70.0))]; + let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: FillRule::EvenOdd }); + compound.appearance = look().into(); + d.insert(Some(l), 0, compound).unwrap(); + let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf); + assert_eq!(at(15.0), Some(id)); + assert_eq!(at(50.0), None, "in the hole"); +} + +#[test] +fn guides_and_clipping_paths_are_not_hit_inside() { + let mut d = Document::new(200.0, 200.0); + let guide = stroked(&mut d, &FRAME, true); + if let Some(NodeKind::Path { guide: g, .. }) = d.node_mut(guide).map(|n| &mut n.kind) { + *g = true; + } + assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None, "a guide"); + // A clip group whose art covers only part of its unfilled clipping path. + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut mask = Node::path(clip, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, Paint::None, 0.0)); + if let NodeKind::Path { clipping, .. } = &mut mask.kind { + *clipping = true; + } + let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), Appearance::default_art()); + d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(mask), Arc::new(picture)], clip: true })).unwrap(); + let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf); + assert_eq!(at(25.0), Some(art)); + assert_eq!(at(75.0), None, "inside the mask where no art paints"); + assert!(objects_at(&d, Point::new(75.0, 50.0), INTERIORS, None).is_empty()); +} + +/// A repeat's copies of an unfilled frame are hit inside, and the copies of a clip group's unfilled +/// compound clipping path are not. +#[test] +fn a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks() { + let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let kind = crate::pattern::RepeatKind::Grid { + h_spacing: 20.0, + v_spacing: 20.0, + rows: 1, + cols: 2, + grid_type: crate::pattern::TileType::Grid, + flip_rows: false, + flip_cols: false, + }; + let repeat = |d: &mut Document, source: Node| { + let r = d.alloc_id(); + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind: kind.clone(), source: vec![Arc::new(source)] }))) + .unwrap(); + r + }; + // Copies at 0..40 and 60..100. + let mut d = Document::new(300.0, 200.0); + let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), look()); + let r = repeat(&mut d, frame); + assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r)); + assert_eq!(hit_test(&d, Point::new(50.0, 20.0), INTERIORS), None, "between the copies"); + let mut d = Document::new(300.0, 200.0); + let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look())); + let members = vec![ring(d.alloc_id(), Rect::new(0.0, 0.0, 40.0, 40.0)), ring(d.alloc_id(), Rect::new(5.0, 5.0, 35.0, 35.0))]; + let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero }); + mask.appearance = look().into(); + let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 40.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]); + clip.set_clips(true); + let r = repeat(&mut d, clip); + assert_eq!(hit_test(&d, Point::new(65.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r), "on the clipped art"); + assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS), None, "inside the mask where no art paints"); +} + +/// Direct Selection in a dynamic symbol's art picks parts as a click on the document does: what +/// paints first, then an unfilled frame inside; an unfilled compound clipping path by its outline. +#[test] +fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art()); + let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look()); + let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look())); + let (mask_id, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let members = vec![ring(a, Rect::new(150.0, 0.0, 250.0, 100.0)), ring(b, Rect::new(160.0, 10.0, 240.0, 90.0))]; + let mut mask = Node::new(mask_id, NodeKind::Compound { children: members, rule: FillRule::NonZero }); + mask.appearance = look().into(); + let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 0.0, 180.0, 100.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]); + clip.set_clips(true); + let root = Node::group(d.alloc_id(), vec![Arc::new(dot), Arc::new(frame), Arc::new(clip)]); + d.symbols.push(crate::Symbol { dynamic: true, name: "Framed".into(), art: Arc::new(root) }); + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Framed".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + let n = d.node(inst).unwrap(); + let at = |x: f64| symbol_part_at(&d, n, Point::new(x, 50.0), INTERIORS); + assert_eq!(at(50.0), Some(vec![0]), "the dot under the frame"); + assert_eq!(at(20.0), Some(vec![1]), "inside the frame"); + assert_eq!(at(220.0), None, "inside the clipping path where no art paints"); +} + #[test] fn long_plain_stroke_hits_its_middle_and_curved_end() { let mut d = Document::new(200.0, 200.0); @@ -1464,6 +1626,7 @@ const SELECTING: HitOptions = HitOptions { clip_outlines: true, area_type_interior: false, ignore_layer_preview: false, + unfilled_interiors: false, scope: None, }; diff --git a/crates/engine/src/tests/strokereach.rs b/crates/engine/src/tests/strokereach.rs index 1154073a3b..a04388af89 100644 --- a/crates/engine/src/tests/strokereach.rs +++ b/crates/engine/src/tests/strokereach.rs @@ -52,6 +52,9 @@ fn a_click_outside_an_outside_stroke_selects_it() { s.execute("paint.setFill", &json!({"none": true})).unwrap(); s.execute("stroke.set", &json!({"weight": 20, "align": "outside"})).unwrap(); s.execute("select.none", &json!({})).unwrap(); + // Object Selection by Path Only: the inside of the unfilled square takes no click of its own, + // so only the stroke is tested. + s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); // 0.8 × the weight outside the path: past where a centred stroke (plus the tolerance) reaches. assert_eq!(click(&mut s, 84.0, 200.0), [r]); s.execute("select.none", &json!({})).unwrap(); @@ -59,6 +62,9 @@ fn a_click_outside_an_outside_stroke_selects_it() { s.execute("stroke.set", &json!({"ids": [r.0], "align": "center"})).unwrap(); s.execute("select.none", &json!({})).unwrap(); assert!(click(&mut s, 84.0, 200.0).is_empty(), "a centred stroke doesn't reach"); + // With it off, a click inside the unfilled square selects it (#9175). + s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + assert_eq!(click(&mut s, 116.0, 200.0), [r]); } #[test] diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c1a661c4e3..f36f35522a 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1940,6 +1940,32 @@ fn selection_preferences_apply_to_pointer_gestures() { assert_eq!(click(&mut s, 7, 250.0, json!({})), json!([front]), "the path does"); } +/// A Selection tool click inside a closed shape with no fill selects it (#9175), and with Object +/// Selection by Path Only on it selects nothing. +#[test] +fn a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only() { + let mut s = server(); + let r = call( + &mut s, + 1, + "draw_shape", + json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 100, "fill": "none", "stroke": "#000000"}), + ); + let id = serde_json::from_str::(&text_of(&r)).unwrap()["id"].as_u64().unwrap(); + let click = |s: &mut Server, n: u64| { + let r = call(s, n, "run_command", json!({"command": "select.none", "params": {}})); + assert_eq!(r["isError"], false, "{r}"); + let events = json!([{"kind": "down", "x": 150, "y": 150}, {"kind": "up", "x": 150, "y": 150}]); + let r = call(s, n + 1, "pointer_gesture", json!({"tool": "selection", "events": events})); + assert_eq!(r["isError"], false, "{r}"); + serde_json::from_str::(&text_of(&r)).unwrap()["selection"].clone() + }; + assert_eq!(click(&mut s, 2), json!([id])); + let r = call(&mut s, 4, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); + assert_eq!(r["isError"], false, "{r}"); + assert_eq!(click(&mut s, 5), json!([]), "path only"); +} + #[test] fn pointer_gesture_forwards_backquote_on_each_event() { let mut s = server(); diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 67658b4ea9..d168e7ca87 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -463,16 +463,20 @@ impl ToolContext<'_> { clip_outlines: false, area_type_interior: false, ignore_layer_preview: false, + unfilled_interiors: false, } } /// [`Self::hit_options`] for the selection tools (Selection, Direct Selection, Group - /// Selection): a clipping path is also hit on its outline ([`HitOptions::clip_outlines`]). + /// Selection): a clipping path is also hit on its outline ([`HitOptions::clip_outlines`]), and + /// where nothing else is hit, an unfilled closed path is hit inside unless Object Selection by + /// Path Only is on ([`HitOptions::unfilled_interiors`]). /// Only for what a press or a hover selects: a double-click, loaded text or a guide's release /// acts on what is drawn and takes [`Self::hit_options`]. /// /// [`HitOptions::clip_outlines`]: vectorcraft_doc::hit::HitOptions::clip_outlines + /// [`HitOptions::unfilled_interiors`]: vectorcraft_doc::hit::HitOptions::unfilled_interiors pub fn selection_hit_options(&self) -> vectorcraft_doc::hit::HitOptions { - vectorcraft_doc::hit::HitOptions { clip_outlines: true, ..self.hit_options() } + vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..self.hit_options() } } } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a39bf3766f..f049ab09bc 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1735,13 +1735,18 @@ fn the_centre_point_selects_and_moves_the_object_whole() { let moved = json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(Vec2::new(20.0, -10.0))), "copy": false}); assert_eq!(a, vec![Action::Begin("Move".into()), Action::Preview("object.transform".into(), moved)]); assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 140.0)), vec![Action::Commit]); - // Unselected, the centre isn't shown and a press there starts a marquee. + // Unselected, the centre isn't shown and a press there starts a marquee (with Object Selection + // by Path Only, where the inside of the unfilled square takes no press). let none = Selection::default(); let mut t = DirectSelectionTool::new(false); - let c = cx(&d, &none, &p); + let c = ToolContext { path_only: true, ..cx(&d, &none, &p) }; assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 140.0)); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Marquee(_)))); + // Without it, a press inside the unfilled square selects it (#9175). + let mut t = DirectSelectionTool::new(false); + let c = cx(&d, &none, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); } /// Group Selection: E pressed during a marquee drag makes it select the objects entirely inside diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index ff95ef68ce..d575fda573 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2917,14 +2917,15 @@ fn a_double_click_on_a_symbol_instance_edits_its_symbol() { /// #4891 for the Selection tool: a press on a selected object's centre point (Attributes › Show /// Center) moves the selection, also where no art is painted (an unfilled shape), which the press -/// would otherwise take for a marquee; anywhere else a press still starts one. +/// would otherwise take for a marquee; anywhere else a press still starts one. With Object +/// Selection by Path Only, so that the inside of the unfilled shape takes no press of its own. #[test] fn a_press_on_the_centre_point_moves_an_unfilled_shape() { let (d, id) = doc_with_live_rect(); let mut s = Selection::default(); s.add(id); let p = paint(); - let c = cx(&d, &s, &p); + let c = ToolContext { path_only: true, ..cx(&d, &s, &p) }; let centre = Point::new(150.0, 150.0); let mut t = SelectionTool::default(); assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move); diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 03b8e4da67..0d70e1a78a 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -218,10 +218,13 @@ pub(super) fn hit_at(app: &VectorcraftApp, p: Point, zoom: f64) -> Option Option { - hit_with(app, p, zoom, |doc, p, opt| vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { clip_outlines: true, ..opt })) + hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..opt }) + }) } /// `test` on the active document at document point `p`, with the options the selection tools hit diff --git a/docs/mcp.md b/docs/mcp.md index 1bbe49574d..2e60f1dd75 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9034,6 +9034,9 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture handle or segment for Direct Selection, the Anchor Point, Add and Delete Anchor Point and Scissors tools, and the Pen with Alt. A handle shorter than that leaves its anchor to be picked when pressed nearer the anchor. - `objectSelectionByPathOnly`: a click inside a filled path or compound path doesn't select it, one on its path does. + Off (the default), a selection tool click inside the closed subpaths of a path or compound path with no fill selects + it when no other object is hit there, the topmost such path first; guides and clipping paths are still picked by + their path only (#9175). - `ctrlClickSelectsBehind` (on by default): a Selection tool click with `mods: {cmd: true}` (Command on macOS, Ctrl elsewhere) selects the object under the selected one there, the next such click the one under that, then the topmost again. Cmd held to borrow the selection tool from another tool clicks as usual. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e15f6be884..0d3221a843 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -694,6 +694,8 @@ since 2026-10-01. **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +- **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when no other object is hit there; among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view is unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. + - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. From 51302b2de057a9bb48c722a351c6fb6727b6fa47 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:29:40 -0800 Subject: [PATCH 15/42] Tests: the installed profile root test runs in its own process profile::tests::the_installed_root_is_used_once_and_must_be_absolute (from #9233) installs the launch's profile root, which a OnceLock holds for the rest of the process. Under cargo test the other tests of the vectorcraft and vectorcraft-cli binaries run on threads of that process and read the settings folder from it. When the root was installed while prefs_dir::tests::the_font_scans_read_the_fonts_folder_next_to_the_settings ran, the Fonts folder it had set and the settings folder it read next differed, and the test failed. nextest runs each test in its own process, so CI passed it. The installed-root test now runs again in a child process of the test binary, as crates/engine/src/tests.rs's in_own_process does, and the font test asserts that no root was installed beside it. With one test thread the font test runs after the installed-root test, so without the change it fails on every run. --- apps/vectorcraft/src/prefs_dir.rs | 2 ++ apps/vectorcraft/src/profile.rs | 29 +++++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 8f1b50dd58..b2d79faaed 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -145,6 +145,8 @@ mod tests { #[test] fn the_font_scans_read_the_fonts_folder_next_to_the_settings() { + // No test installs a launch's root in this process, so the settings folder stays the same here. + assert_eq!(profile::data_root(), None, "a test installed a launch's root beside the others"); install_fonts(); let fonts = prefs_dir().map(|dir| dir.join("Fonts")); assert!(fonts.is_some(), "a home folder to keep the settings in"); diff --git a/apps/vectorcraft/src/profile.rs b/apps/vectorcraft/src/profile.rs index 9b3a671c70..ad14e07a86 100644 --- a/apps/vectorcraft/src/profile.rs +++ b/apps/vectorcraft/src/profile.rs @@ -457,10 +457,35 @@ mod tests { } } - /// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per - /// process (nextest gives every test its own). + /// Runs the test `name` of this module again in a child process of the test binary → whether + /// this is that child. For a test that installs the process-wide root, which every test running + /// beside it would then read as the settings folder. + fn in_own_process(name: &str) -> bool { + const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS"; + if std::env::var_os(CHILD).is_some() { + return true; + } + // The test's path without the crate's name: the desktop app and `vectorcraft-cli` both build this file. + let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path); + let path = format!("{module}::{name}"); + let output = + std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", &path, "--nocapture"]).env(CHILD, "1").output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "{path} failed in its own process:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + false + } + + /// Installs the process-wide root, which a `OnceLock` holds once per process, so the test runs in + /// a process of its own. #[test] fn the_installed_root_is_used_once_and_must_be_absolute() { + if !in_own_process("the_installed_root_is_used_once_and_must_be_absolute") { + return; + } let dir = temp("installed-root"); assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused"); install_data_root(dir.to_path_buf()).unwrap(); From 37567e8c5adfb0c34df1feb759fc979fada5b540 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:46:36 -0800 Subject: [PATCH 16/42] Nightly: an ended session unlocks its lease A nightly session's lease is a file lock, which the system frees only when every copy of its handle is closed or the lock is unlocked. A child process that any thread starts holds a copy of every handle until it runs its program. When a session ended during that time, by its controlled return or by the caught panic that frees the lease for the successor a graphics restart starts, the next launch found the lease held and kept no session record. Under cargo test, three nightly_session tests failed this way while the installed-root test started its child process. Session now unlocks the lease when it is dropped. A new test holds a copy of the lease's handle while a session completes and while one is dropped, and the next session takes the lease each time. --- apps/vectorcraft/src/nightly_session.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/apps/vectorcraft/src/nightly_session.rs b/apps/vectorcraft/src/nightly_session.rs index 5e24527592..741335a2ee 100644 --- a/apps/vectorcraft/src/nightly_session.rs +++ b/apps/vectorcraft/src/nightly_session.rs @@ -22,6 +22,15 @@ pub struct Session { previous_unclean: bool, } +impl Drop for Session { + /// Frees the lease when the session ends. A child process that any thread starts holds a copy of + /// the lease's handle until it runs its program, and the lock is only freed by closing every copy + /// or by unlocking. + fn drop(&mut self) { + let _ = self._lease.unlock(); + } +} + fn regular_or_missing(path: &Path) -> io::Result { match std::fs::symlink_metadata(path) { Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), @@ -258,6 +267,21 @@ mod tests { assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record"); } + #[test] + fn an_ended_session_frees_the_lease_while_a_copy_of_its_handle_is_open() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap(); + // A child process that is starting holds such a copy. + let first_copy = first._lease.try_clone().unwrap(); + first.complete().unwrap(); + let second = Session::begin(Some(&fixture.0), "second", None).unwrap(); + assert!(second.is_some(), "a completed session frees the lease"); + let second_copy = second.as_ref().map(|session| session._lease.try_clone().unwrap()); + drop(second); + assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease"); + drop((first_copy, second_copy)); + } + #[test] fn cleanup_never_removes_an_unknown_changed_record() { let fixture = Fixture::new(); From ee3e7611b467df7752794974a3ac041220c6a0c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:54:40 -0800 Subject: [PATCH 17/42] GPU: an ended start unlocks the start file The start file's lock had the same fault as the nightly lease: it was freed only when the file was closed, so a child process that held a copy of the handle until it ran its program kept the file locked. The next start then took the file for another copy of the app that was starting, and did not read or write it. Under cargo test, gpu::tests::a_damaged_or_unreadable_start_file_is_ignored failed this way while the installed-root test started its child process. StartFile now unlocks the file when it is dropped, and a new test holds a copy of the file's handle while a start ends. The test guard from e94b74eea4b (by mockydevs), whose write side was removed in #8800, kept only its read side and no longer stopped any test from starting a program. The unlock replaces it, so the guard has been removed. --- apps/vectorcraft/src/gpu.rs | 9 ++++++++ apps/vectorcraft/src/gpu/tests.rs | 35 ++++++++++++++++++++----------- apps/vectorcraft/src/main.rs | 14 ------------- 3 files changed, 32 insertions(+), 26 deletions(-) diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index 200bbf3095..198e7dcc85 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -629,6 +629,15 @@ struct StartFile { record: StartRecord, } +impl Drop for StartFile { + /// Frees the lock when the start releases the file. A child process that any thread starts holds + /// a copy of the file's handle until it runs its program, and the lock is only freed by closing + /// every copy or by unlocking. + fn drop(&mut self) { + let _ = self.file.unlock(); + } +} + impl StartFile { /// Open `dir`'s [`START_FILE`], with the record the last start left in it (`None` when there is /// none or it can't be read). `Ok(None)` when another copy of the app holds it. diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index fe4a4ddcc5..792518993d 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -613,9 +613,7 @@ fn a_normal_exit_or_another_failure_does_not_restart() { assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into())); } -/// A log folder of its own for each test, and the guard that keeps other tests from starting a -/// program while it runs: the test releases the start file's lock and takes it again, and a child -/// starting meanwhile would keep it held (`crate::no_spawns`). +/// A log folder of its own for each test. struct TestDir(tempfile::TempDir); impl std::ops::Deref for TestDir { @@ -632,10 +630,23 @@ impl AsRef for TestDir { } } -fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) { - let spawns = crate::no_spawns(); - let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap(); - (TestDir(dir), spawns) +fn start_dir(tag: &str) -> TestDir { + TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap()) +} + +/// A start that ends frees the start file even while another handle to it is open, as a child +/// process that is starting holds one: the next start reads the file instead of taking it for +/// another copy of the app that is starting. +#[test] +fn an_ended_start_frees_the_start_file_while_a_copy_of_its_handle_is_open() { + let dir = start_dir("copy"); + let starting = Startup::default(); + starting.track(&dir, None, false); + let copy = starting.start.lock().unwrap().as_ref().map(|start| start.file.try_clone().unwrap()); + assert!(copy.is_some(), "the start holds the file"); + starting.ended(); + assert!(StartFile::open(&dir).unwrap().is_some(), "an ended start frees the start file"); + drop(copy); } /// What a start in `dir` leaves out; it then ends without crashing. @@ -661,7 +672,7 @@ fn issue_2243() -> Vec { /// it, without a status-bar note. #[test] fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() { - let (dir, _spawns) = start_dir("crash"); + let dir = start_dir("crash"); let c = issue_2243(); let first = Startup::default(); assert_eq!(first.track(&dir, None, false), LeftOut::default()); @@ -691,7 +702,7 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() { /// an error, a restart on another adapter), leaves nothing out of the next. #[test] fn a_start_that_showed_its_first_frame_or_ended_is_cleared() { - let (dir, _spawns) = start_dir("shown"); + let dir = start_dir("shown"); let c = issue_2243(); for end in [Startup::presented as fn(&Startup), Startup::ended] { let first = Startup::default(); @@ -714,7 +725,7 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() { /// macOS, where wgpu has none. #[test] fn a_crash_while_listing_lists_opengl_alone() { - let (dir, _spawns) = start_dir("listing"); + let dir = start_dir("listing"); let first = Startup::default(); first.track(&dir, None, false); drop(first); @@ -740,7 +751,7 @@ fn a_crash_while_listing_lists_opengl_alone() { /// start shows its first frame on the adapter that crashed, the adapter counts again. #[test] fn wgpu_backend_or_adapter_name_ignores_the_crashes() { - let (dir, _spawns) = start_dir("explicit"); + let dir = start_dir("explicit"); let c = issue_2243(); let first = Startup::default(); first.track(&dir, None, false); @@ -760,7 +771,7 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() { /// are ignored: the start goes on with nothing left out. #[test] fn a_damaged_or_unreadable_start_file_is_ignored() { - let (dir, _spawns) = start_dir("damaged"); + let dir = start_dir("damaged"); std::fs::create_dir_all(&dir).unwrap(); let damaged: [&[u8]; 9] = [ b"", diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 8907fe4bd1..872753f9d7 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -1034,19 +1034,5 @@ fn main() -> std::process::ExitCode { } } -/// Tests only: while a test starts another program, the child briefly holds a copy of every file -/// this process has open, until it runs that program. A file lock held through such a copy outlives -/// its own handle, so a GPU start test that released the start file and opened it again found it -/// still locked, as if another copy of the app were running, and failed. A test that starts a -/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`]. -#[cfg(all(test, feature = "wgpu"))] -static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(()); - -/// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]). -#[cfg(all(test, feature = "wgpu"))] -fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> { - CHILD_SPAWN.read().unwrap_or_else(std::sync::PoisonError::into_inner) -} - #[cfg(all(test, feature = "wgpu"))] mod tests; From 05cce479804807ac1fe3d4f48e74fd347243480f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 17:45:05 -0800 Subject: [PATCH 18/42] Keep parity status and revision history unchanged --- docs/ui-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b4dfe0adcc..d0017e029a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (Shape Control bar: canceled numeric edits restore future tool settings and coupled corner radii; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -70,7 +70,6 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-27 | minor | Shape Control bar: canceled numeric edits restore future-tool settings and coupled radii along with selected artwork; retired edits cannot overwrite a different tool. Native scrub, keyboard, next-shape and Undo cases covered. Scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | @@ -361,6 +360,7 @@ tools, never checked side by side) isn't captured row by row. | Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | | Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | | Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and, with Measurement Labels on, the radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | +| Shapes panel restores canceled control gestures | done | Escape restores the opening field values, including coupled radii and settings for the next shape. | ## Modifier keys and temporary tools From a335fbbf02b3a68e41bf0ebf81ffeff306f53231 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:42:51 -0800 Subject: [PATCH 19/42] Docs: unfilled-interior selection scope and fill eligibility The Path Only preference entry in docs/mcp.md now says the click inside an unfilled closed path does not select it in Outline view. Both docs state the condition as a click that hits no object's fill, stroke or path there, so the topmost of two overlapping unfilled paths is still picked. The #6625 fill eligibility entry now says hidden-only and None interiors are picked with Path Only off when nothing else is hit. --- docs/mcp.md | 3 ++- docs/target-app-parity.md | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 2e60f1dd75..e5b9296a0d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9035,7 +9035,8 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture Pen with Alt. A handle shorter than that leaves its anchor to be picked when pressed nearer the anchor. - `objectSelectionByPathOnly`: a click inside a filled path or compound path doesn't select it, one on its path does. Off (the default), a selection tool click inside the closed subpaths of a path or compound path with no fill selects - it when no other object is hit there, the topmost such path first; guides and clipping paths are still picked by + it when the click hits no object's fill, stroke or path there, the topmost such path first, except in Outline view; + guides and clipping paths are still picked by their path only (#9175). - `ctrlClickSelectsBehind` (on by default): a Selection tool click with `mods: {cmd: true}` (Command on macOS, Ctrl elsewhere) selects the object under the selected one there, the next such click the one under that, then the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0d3221a843..40b24d967d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -692,9 +692,9 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. -- **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when no other object is hit there; among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view is unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. +- **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no object's fill, stroke or path there; among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view is unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. From efb791113927cb2c221d8a7ce680682a728a9837 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:46:40 -0800 Subject: [PATCH 20/42] Scripts: assigning documents throws in strict mode and is ignored otherwise The global `documents` has only a getter. The docs and the module and test comments said only that assigning it keeps its value. They now say that the assignment is ignored outside strict mode and throws a TypeError in strict mode code or with `#strict on`, and the test also checks the `#strict on` case. --- crates/engine/src/script/dom.rs | 3 ++- crates/engine/src/tests/script_dom.rs | 5 ++++- docs/mcp.md | 5 +++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 46ca2824d4..cd2307d642 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -28,7 +28,8 @@ //! false then. Assigning to such a name throws the same error. //! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the //! active document's selection. A top-level `var selection = ...` does the same and does -//! not make a variable of the script. Assigning `documents` keeps its value. +//! not make a variable of the script. An assignment to `documents` is ignored outside strict +//! mode and throws a `TypeError` in strict mode code or with `#strict on`. //! - Collections list documents in tab order. The objectReferences page says `documents[0]` is //! always the active document; VectorCraft does not follow that yet. //! - `pageItems` lists every object, with the objects inside groups and compound paths after the diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c1aa77e6a6..2f7bf70a1d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1841,7 +1841,8 @@ fn objects_of_the_object_model_print_their_class_and_name() { } /// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and -/// assigning one assigns the member: `selection` selects, `documents` keeps its value. +/// assigning one assigns the member: `selection` selects, and `documents` keeps its value outside +/// strict mode and throws a `TypeError` in strict mode code or with `#strict on`. #[test] fn the_application_members_can_be_named_without_app() { let (mut s, a, b) = doc(); @@ -1868,6 +1869,8 @@ fn the_application_members_can_be_named_without_app() { assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document")); let e = failure(&mut s, "'use strict'; documents = 5;"); assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}"); + let e = failure(&mut s, "#strict on\ndocuments = 5;"); + assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}"); // With no document open, reading `activeDocument` throws as `app.activeDocument` does. let mut s = Session::new(); assert!(failure(&mut s, "activeDocument;").contains("No active document")); diff --git a/docs/mcp.md b/docs/mcp.md index 1bbe49574d..e99add4aa5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2777,8 +2777,9 @@ other files through `$`: [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level - `var selection = ...` does the same and does not make a variable of the script. Assigning `documents` keeps its - value. `app.documents` + `var selection = ...` does the same and does not make a variable of the script. An assignment to `documents` + leaves its value unchanged. Outside strict mode the assignment is ignored, and in strict mode code + (`'use strict'`) or with `#strict on` it throws a `TypeError`. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of From 944ba1c0c18a7cac086ec2fe633176a5bc6fd9b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:49:16 -0800 Subject: [PATCH 21/42] Direct Selection: a press on a member of a selected group keeps the group With a group selected, Direct Selection treated a click on one of its paths as a click on an unselected path: it selected that path alone, so a drag moved only that path. The tools checked whether the path itself was in the selection and ignored a selected group around it. A path inside a selected object now counts as selected whole: - A click on its fill keeps the group selected, and a drag from its fill or one of its anchors moves the group whole. - A click on one of its anchors or segments selects that anchor or segment alone, as for a selected path. - Its anchors show the selected-anchor cursor and highlight, and an object above the group does not take a press on one. - Group Selection adds the group above the outermost selected one, and keeps the selection when that is the top group. This applies to the Cmd/Ctrl press the Selection tool lends Direct Selection too. --- crates/tools/src/direct.rs | 113 +++++++++++++++++++++---------- crates/tools/src/direct/tests.rs | 77 +++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 157 insertions(+), 34 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 15c2f354d4..e3dc1ad1e4 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -18,6 +18,10 @@ //! the drag makes it select only the objects entirely inside it, whole. //! In isolation mode both pick only the isolated object and what is inside it: anchors, segments, //! paths and groups outside it stay put. +//! An object inside a selected group counts as selected whole: a click on its fill keeps the group +//! selected, a drag from its fill or one of its anchors moves the group whole, and a click on an +//! anchor or a segment selects that anchor or segment alone. With Group Selection a click there +//! adds the next group up, if any. //! Both move objects selected as a whole as the Selection tool does, snapping alike. When the //! selection also holds direct-selected anchors or segments, a drag from an object moves those //! anchors and the objects selected whole, as an anchor drag does, and while Alt is held it @@ -53,7 +57,7 @@ //! moves its anchors. use std::borrow::Cow; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde_json::{Value, json}; use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view}; @@ -556,12 +560,14 @@ fn line_end_leave(cx: &ToolContext, grab: Point) -> Option { /// objects behind it (#3405). fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, Point)> { let mut owners = anchor_owners(cx, |n| matches!(n.kind, NodeKind::Path { .. }) || is_area_type(n) || is_path_type(n)); - owners.sort_by_key(|id| !cx.selection.contains(*id)); + // The members of a selected group count as selected. + let selected = in_selection_all(cx); + owners.sort_by_key(|id| !selected.contains(id)); // 1. Check selected objects first. Selected objects are NEVER occluded (#1508). let mut unselected_idx = owners.len(); for (i, &id) in owners.iter().enumerate() { - if !cx.selection.contains(id) { + if !selected.contains(&id) { unselected_idx = i; break; } @@ -621,12 +627,26 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { if spines.iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) || spine_segment_in(&spines, p, seg_tol).is_some() { return true; } - // The editable paths' control bounds are listed once per document state and selection; a - // hover measures only the paths whose bounds it is near. - let boxes = crate::select::selected_part_boxes(cx, || { + selected_part_boxes(cx).iter().any(|&(id, b)| { + b.inflate(tol, tol).contains(p) + && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { + #[cfg(test)] + MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); + nearest_anchor(&pd, p, tol, None).is_some() + }) + }) +} + +/// The editable paths of the selected objects and inside them (a selected group's members), with +/// their control bounds: each selected object's paths topmost first, in selection order. The list +/// is made once per document state and selection; a hover measures only the paths whose bounds it +/// is near. +fn selected_part_boxes(cx: &ToolContext) -> std::sync::Arc<[(NodeId, vectorcraft_geom::Rect)]> { + crate::select::selected_part_boxes(cx, || { let editable = cx.doc.editable(); let mut v = vec![]; for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { + let from = v.len(); walk_pickable_from(root, &mut |n| { if editable(n.id) && let Some(b) = editable_path(n).and_then(|pd| pd.control_bounds()) @@ -634,16 +654,9 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { v.push((n.id, b)); } }); + v[from..].reverse(); } v.into() - }); - boxes.iter().any(|&(id, b)| { - b.inflate(tol, tol).contains(p) - && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { - #[cfg(test)] - MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); - nearest_anchor(&pd, p, tol, None).is_some() - }) }) } @@ -820,13 +833,37 @@ struct SegmentHit { fn next_group(cx: &ToolContext, ancestry: &[NodeId]) -> Option { // Skip the layer and its sublayers: they are not objects. let layers = ancestry.iter().take_while(|id| cx.doc.node(**id).is_some_and(Node::is_layer)).count().max(1); - ancestry + let chain: Vec = ancestry .iter() .skip(layers) .rev() .copied() .take_while(|id| in_scope(cx.doc, cx.isolation, *id) && !cx.doc.node(*id).is_some_and(Node::is_layer)) - .find(|id| !cx.selection.contains(*id)) + .collect(); + // The groups inside a selected group are selected with it: the next one is above the outermost + // selected one. + let outermost = chain.iter().rposition(|id| cx.selection.contains(*id)); + chain.get(outermost.map_or(0, |i| i + 1)).copied() +} + +/// Is `id` selected as an object: itself, or inside a selected group or other selected object? A +/// press on a member of a selected group keeps the group selected, and a drag moves the group +/// whole, as for a path that is itself selected. +fn in_selection(cx: &ToolContext, id: NodeId) -> bool { + !cx.selection.objects.is_empty() + && (cx.selection.contains(id) || cx.doc.ancestry(id).is_some_and(|a| a.iter().any(|x| cx.selection.contains(*x)))) +} + +/// The selected objects and the objects inside them that Direct Selection may pick: the objects +/// among those [`walk_pickable`] visits that [`in_selection`] accepts. +fn in_selection_all(cx: &ToolContext) -> HashSet { + let mut set = HashSet::new(); + for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { + walk_pickable_from(root, &mut |n| { + set.insert(n.id); + }); + } + set } /// Is an object of instance `id`'s art selected ([`vectorcraft_doc::Selection::symbol_part`]), @@ -1327,7 +1364,7 @@ impl DirectSelectionTool { // anchors on mouse over finds them: walking every path on each hover is too slow. let hit = hit_test(cx.doc, p, cx.selection_hit_options()); if let Some((id, _)) = hovered_anchor_with_hit(cx, p, hit.as_ref()) { - return Some(if cx.selection.contains(id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor }); + return Some(if in_selection(cx, id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor }); } if hit_frame_edge(cx, p, tol).is_some() { return None; @@ -1339,7 +1376,7 @@ impl DirectSelectionTool { return None; } let h = hit?; - let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none(); + let whole = in_selection(cx, h.leaf) && cx.selection.partial(h.leaf).is_none(); let curved = matches!(h.kind, HitKind::Stroke | HitKind::Outline) && segment_at(cx, h.leaf, p).is_some_and(|s| s.curved); (!whole && curved).then_some(Cursor::ReshapeSegment) } @@ -1355,7 +1392,11 @@ fn hovered_anchor(cx: &ToolContext, p: Point) -> Option<(NodeId, Point)> { fn hovered_anchor_with_hit(cx: &ToolContext, p: Point, hit: Option<&Hit>) -> Option<(NodeId, Point)> { let tol = cx.point_tol(); let under = hit.map(|h| cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)).unwrap_or(h.leaf)); - cx.selection.objects.iter().copied().filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| { + // The paths inside a selected group come before an object above them, as a press takes them + // ([`hit_anchor`]). + let selected = if cx.selection.objects.is_empty() { None } else { Some(selected_part_boxes(cx)) }; + let near = selected.iter().flat_map(|boxes| boxes.iter()).filter(|(_, b)| b.inflate(tol, tol).contains(p)).map(|&(id, _)| id); + near.filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| { let path = cx.doc.node(id).and_then(editable_path)?; nearest_anchor(&path, p, tol, None).map(|(.., a)| (id, a)) }) @@ -1476,7 +1517,9 @@ impl DirectSelectionTool { h.ancestry.push(part); h.leaf = part; } - let target = if cx.selection.contains(h.leaf) { next_group(cx, &h.ancestry).unwrap_or(h.leaf) } else { h.leaf }; + // On an object selected itself or inside a selected group, a click adds the next group up, + // and keeps the selection when the outermost group is selected already. + let inside = in_selection(cx, h.leaf); let mut deselect = None; let mut out = vec![]; if ev.mods.shift { @@ -1485,15 +1528,13 @@ impl DirectSelectionTool { if cx.selection.contains(h.leaf) { deselect = Some(h.leaf); } else { - out.push(Action::Exec("select.toggle".into(), json!({"id": target.0}))); - } - } else if !cx.selection.contains(target) { - if cx.selection.contains(h.leaf) { - // A completed click climbs the group; a drag moves only the selected art. - self.click_group = Some(target); - } else { - out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]}))); + out.push(Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))); } + } else if !inside { + out.push(Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))); + } else if let Some(target) = next_group(cx, &h.ancestry) { + // A completed click climbs the group; a drag moves only the selected art. + self.click_group = Some(target); } self.state = State::MoveObject { start: p, grab: None, hold: hold_point(cx, &h, p), began: false, deselect }; out @@ -1534,15 +1575,16 @@ impl DirectSelectionTool { // already selected whole, an Alt-click adds the next enclosing group on release. if ev.mods.alt { self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, began: false, deselect: None }; - let whole = cx.selection.contains(id) && cx.selection.partial(id).is_none(); + let whole = in_selection(cx, id) && cx.selection.partial(id).is_none(); if whole && !ev.mods.shift { self.click_group = cx.doc.ancestry(id).and_then(|a| next_group(cx, &a)); } return if whole { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] }; } - // A path with all its anchors selected is stored whole (no partial entry). + // A path with all its anchors selected is stored whole (no partial entry), and so is each + // path inside a selected group. let already = - cx.selection.contains(id) && !cx.selection.segments.contains_key(&id) && cx.selection.partial(id).is_none_or(|s| s.contains(&(si, ai))); + in_selection(cx, id) && !cx.selection.segments.contains_key(&id) && cx.selection.partial(id).is_none_or(|s| s.contains(&(si, ai))); // Paths all selected whole move as objects, held by this anchor, so Alt can turn // the copy on and off during the drag as with the Selection tool. self.state = if already && cx.selection.anchors.is_empty() { @@ -1620,7 +1662,7 @@ impl DirectSelectionTool { // A segment pick keeps its endpoints available for movement without selecting // the anchors themselves. Dragging reshapes a curve, else moves it. Alt picks // the whole path (and Alt-drag copies it), as with Group Selection. - let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none() && !part_picked(cx, h.leaf); + let whole = in_selection(cx, h.leaf) && cx.selection.partial(h.leaf).is_none() && !part_picked(cx, h.leaf); if !ev.mods.alt && matches!(h.kind, HitKind::Stroke | HitKind::Outline) && let Some(s) = segment_at(cx, h.leaf, p) @@ -1656,7 +1698,8 @@ impl DirectSelectionTool { return vec![Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))]; } self.frame.clear(); - if !cx.selection.contains(h.leaf) || cx.selection.partial(h.leaf).is_some() || part_picked(cx, h.leaf) { + // A press inside a selected group keeps the group: a drag moves it whole. + if !whole { return vec![Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))]; } vec![] @@ -1857,7 +1900,9 @@ impl DirectSelectionTool { (true, ..) => vec![Action::Commit], (false, Some(id), _, _) => vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))], (false, None, Some((id, si, ai)), _) => { - if has_multiple_selected_anchors(cx) { + // The key anchor is on a path selected itself (`select.key`); a click on an anchor of + // a path inside a selected group selects that anchor alone. + if cx.selection.contains(id) && has_multiple_selected_anchors(cx) { if cx.selection.key_anchor == Some((id, (si, ai))) { vec![Action::Exec("select.key".into(), json!({}))] } else { diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a39bf3766f..1b03ad81d0 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1306,6 +1306,83 @@ fn group_selection_distinguishes_selected_leaf_drags_from_clicks() { assert!(t.pointer(&context, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty()); } +/// A path inside a selected group counts as selected whole. With Direct Selection a click on its +/// fill keeps the group, a drag from its fill or an anchor moves the group whole, and a click on an +/// anchor selects that anchor alone; its anchors show the selected-anchor cursor and an object +/// above the group does not take a press on one. With Group Selection a click adds the next group +/// up and keeps the selection at the outermost one, and a drag moves the selection. +#[test] +fn a_press_inside_a_selected_group_keeps_the_group() { + let (mut d, inside, _, inner, outer) = nested_group_doc(); + let p = paint(); + let mut s = Selection::default(); + s.set([outer]); + let moves = |a: &[Action]| matches!(a, [Action::Begin(n), Action::Preview(c, _)] if n == "Move" && c == "object.transform"); + for group in [false, true] { + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(group); + let down = PointerEvent::new(PointerKind::Down, 150.0, 150.0); + assert!(t.pointer(&c, &down).is_empty(), "a press on the fill (group: {group})"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty(), "a click on the fill (group: {group})"); + assert!(t.pointer(&c, &down).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 180.0, 165.0)); + assert!(moves(&a), "a drag from the fill (group: {group}): {a:?}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 180.0, 165.0)), vec![Action::Commit]); + } + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + let corner = PointerEvent::new(PointerKind::Down, 100.0, 100.0); + assert!(t.pointer(&c, &corner).is_empty(), "a press on an anchor"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 115.0)); + assert!(moves(&a), "a drag from an anchor: {a:?}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 115.0)); + t.pointer(&c, &corner); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), + vec![Action::Exec("select.anchors".into(), json!({"id": inside.0, "anchors": [[0, 0]], "mode": "set"}))], + "a click on an anchor" + ); + assert_eq!(DirectSelectionTool::new(false).cursor(&c, Point::new(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty(), "a press on a segment"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0)); + assert!(matches!(a.as_slice(), [Action::Exec(c, v)] if c == "select.segments" && v["id"] == inside.0), "a click on a segment: {a:?}"); + // Group Selection climbs from a selected inner group to the group around it. + let mut climb = Selection::default(); + climb.set([inner]); + let c = cx(&d, &climb, &p); + let mut t = DirectSelectionTool::new(true); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)), vec![Action::Exec("select.add".into(), json!({"ids": [outer.0]}))]); + // With two anchors of a path beside the group selected too, the click still selects the anchor + // alone: the key anchor is on a path selected itself. + let l = d.layers[0].id; + let beside = d.alloc_id(); + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0)); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::path(beside, rect, vectorcraft_doc::Appearance::default_art())).unwrap(); + let mut mixed = Selection::default(); + mixed.set([outer, beside]); + mixed.anchors.insert(beside, BTreeSet::from([(0, 0), (0, 1)])); + let c = cx(&d, &mixed, &p); + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&c, &corner).is_empty()); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), + vec![Action::Exec("select.anchors".into(), json!({"id": inside.0, "anchors": [[0, 0]], "mode": "set"}))], + "a click on an anchor with anchors of {beside:?} selected" + ); + // An opaque object above the group, over the anchor. + let cover = d.alloc_id(); + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 250.0, 250.0)); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::path(cover, rect, vectorcraft_doc::Appearance::default_art())).unwrap(); + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + assert_eq!(hovered_anchor(&c, Point::new(100.0, 100.0)), Some((inside, Point::new(100.0, 100.0))), "the anchor under {cover:?} is highlighted"); + assert_eq!(t.cursor(&c, Point::new(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); + assert!(t.pointer(&c, &corner).is_empty(), "a press on an anchor under {cover:?}"); + assert!(moves(&t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 115.0)))); +} + /// Isolation mode: a marquee and an anchor click take the path inside the isolated group and /// leave the path beside it. Group Selection stops at the isolated group instead of adding /// the group around it. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a54102e675..465681c751 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -844,6 +844,7 @@ since 2026-10-01. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. - **Escape in more tool drags:** Escape during an Anchor Point drag, a Mesh tool drag, a Direct Selection drag of a mesh point, a corner widget or the brackets of type on a path, or a Shape Builder drag cancels it: the art goes back to how the press found it, no undo step is added, the release does nothing, and the tool stays chosen. Escape during a Measure tool drag brings back the measurement before it. Regression tests: `escape_cancels_*` in `draw2/anchor/tests.rs`, `meshedit.rs`, `direct/tests.rs`, `builder/tests.rs` and `xform/measure.rs`, and `escape_cancels_an_anchor_point_mesh_shape_builder_or_measure_drag` in `tests/toolescape.rs`. - **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of a path is selected (the path selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. The other corners' widgets then hide; a Shift-click on another corner's anchor adds that corner and shows its widget, and a Shift-click on a showing widget deselects its corner. Adding a corner by Shift-clicking its widget while it is hidden stays open (#1232). Corner widgets are chosen by clicking one and Shift-clicking the others ([Logos By Nick, rounded corners in Illustrator](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. +- **A press inside a selected group** (VectorCraft's own rule): with Direct Selection, a path inside a selected group counts as selected whole. A click on its fill keeps the group selected, a drag from its fill or one of its anchors moves the group whole, and a click on an anchor or a segment selects it alone. The path's anchors show the selected-anchor cursor and highlight, and an object above the group does not take a press on one. Group Selection adds the group above the outermost selected one. This also applies to the Cmd/Ctrl press the Selection tool lends Direct Selection. Test: `direct::tests::a_press_inside_a_selected_group_keeps_the_group`. - **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF. - **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`). - **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html). From 74f5b8c1bdb0a4ac6a1a37fa4eb68b0e5b94f0c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 21:25:32 -0800 Subject: [PATCH 22/42] Nightly: a session that fails to start unlocks its lease Session::begin locked the lease and could then return an error while checking or writing the record, before a Session existed. On those paths the lease file was dropped without unlocking, so a child process that was starting kept the lock held. The lock now lives in a Lease guard that unlocks on drop, and it covers the ended session and both error paths. New tests hold a copy of the handle while the record path is a folder and while the record cannot be written. --- apps/vectorcraft/src/nightly_session.rs | 83 ++++++++++++++++++++----- 1 file changed, 66 insertions(+), 17 deletions(-) diff --git a/apps/vectorcraft/src/nightly_session.rs b/apps/vectorcraft/src/nightly_session.rs index 741335a2ee..b7416541ef 100644 --- a/apps/vectorcraft/src/nightly_session.rs +++ b/apps/vectorcraft/src/nightly_session.rs @@ -16,18 +16,35 @@ static SESSION: Mutex> = Mutex::new(None); static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub struct Session { - _lease: File, + _lease: Lease, path: PathBuf, own_record: Vec, previous_unclean: bool, } -impl Drop for Session { - /// Frees the lease when the session ends. A child process that any thread starts holds a copy of - /// the lease's handle until it runs its program, and the lock is only freed by closing every copy - /// or by unlocking. +/// The profile's [`LEASE`], open and locked. +struct Lease(File); + +impl Lease { + /// Lock `root`'s [`LEASE`]: `None` when another window of the same profile holds it. + fn take(root: &Path) -> io::Result> { + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => Ok(Some(Self(lease))), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), + Err(std::fs::TryLockError::Error(error)) => Err(error), + } + } +} + +impl Drop for Lease { + /// Frees the lease when the session ends, or when a session could not be started after the lock + /// was taken. A child process that any thread starts holds a copy of the lease's handle until it + /// runs its program, and the lock is only freed by closing every copy or by unlocking. fn drop(&mut self) { - let _ = self._lease.unlock(); + let _ = self.0.unlock(); } } @@ -82,14 +99,13 @@ impl Session { if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); } - let lease_path = root.join(LEASE); - regular_or_missing(&lease_path)?; - let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; - match lease.try_lock() { - Ok(()) => {} - Err(std::fs::TryLockError::WouldBlock) => return Ok(None), - Err(std::fs::TryLockError::Error(error)) => return Err(error), - } + let Some(lease) = Lease::take(root)? else { return Ok(None) }; + Self::record(lease, root, version, commit).map(Some) + } + + /// Write this launch's record while `lease` is held. On an error `lease` is dropped, which + /// unlocks it. + fn record(lease: Lease, root: &Path, version: &str, commit: Option<&str>) -> io::Result { let path = root.join(RECORD); let previous_unclean = regular_or_missing(&path)?; let own_record = serde_json::to_vec(&serde_json::json!({ @@ -99,7 +115,7 @@ impl Session { "commit": commit.filter(|value| !value.is_empty()), }))?; atomic_write_no_follow(&path, &own_record)?; - Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + Ok(Self { _lease: lease, path, own_record, previous_unclean }) } pub fn previous_unclean(&self) -> bool { @@ -272,16 +288,49 @@ mod tests { let fixture = Fixture::new(); let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap(); // A child process that is starting holds such a copy. - let first_copy = first._lease.try_clone().unwrap(); + let first_copy = first._lease.0.try_clone().unwrap(); first.complete().unwrap(); let second = Session::begin(Some(&fixture.0), "second", None).unwrap(); assert!(second.is_some(), "a completed session frees the lease"); - let second_copy = second.as_ref().map(|session| session._lease.try_clone().unwrap()); + let second_copy = second.as_ref().map(|session| session._lease.0.try_clone().unwrap()); drop(second); assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease"); drop((first_copy, second_copy)); } + /// `root`'s lease, locked as [`Session::begin`] locks it, and a copy of its handle such as a + /// child process that is starting holds. + fn locked_with_a_copy(root: &Path) -> (Lease, File) { + let lease = Lease::take(root).unwrap().unwrap(); + let copy = lease.0.try_clone().unwrap(); + (lease, copy) + } + + #[test] + fn a_session_that_cannot_check_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() { + let fixture = Fixture::new(); + std::fs::create_dir(fixture.0.join(RECORD)).unwrap(); + let (lease, copy) = locked_with_a_copy(&fixture.0); + assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "a folder is not a record"); + std::fs::remove_dir(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to check its record frees the lease"); + drop(copy); + } + + #[test] + fn a_session_that_cannot_write_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() { + let fixture = Fixture::new(); + // A folder at the temporary file's name makes the write fail after the record was checked. + let temporary = fixture.0.join(format!(".{RECORD}.{}.tmp", std::process::id())); + std::fs::create_dir(&temporary).unwrap(); + let (lease, copy) = locked_with_a_copy(&fixture.0); + assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "the record cannot be written"); + assert!(!fixture.0.join(RECORD).exists()); + std::fs::remove_dir(&temporary).unwrap(); + assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to write its record frees the lease"); + drop(copy); + } + #[test] fn cleanup_never_removes_an_unknown_changed_record() { let fixture = Fixture::new(); From f0b6f5208aece024d9d0d762828fdbff841923bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:35:31 -0800 Subject: [PATCH 23/42] Tangent Circle Tool: a second click opens the radius dialog as a new held dialog The dialog host now ties each held record to one opening of a dialog, and drops a record whose dialog was opened again under the same id. Reopening the radius dialog straight through the host left the new opening with no record, so its Cancel never cleared the open dialog (a_second_click_replaces_the_open_dialog failed). The dialog now opens the replacement with open_held_with, which gives it its own OK and cancel hook. --- .../src/addons/pathtools/tangent_circle_radius.rs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs index 7a58e65095..92ad231a96 100644 --- a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -51,16 +51,13 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { return; }; // A dialog still open from an earlier click closes without an answer, and its preview is rolled back. The new - // dialog has its id (the dialog's kind), so the earlier dialog's held answer, with its OK and cancel hook, serves - // the new one. - let mut held = None; + // dialog has the same id (the dialog's kind), and its own held answer and cancel hook replace the earlier ones. if let Some(mut old) = app.addon_dialogs.tangent_radius.take() { if let Some(host) = app.dialogs() { host.with(|h| { h.cancel_by_id(&ctx, old.id); let _ = h.take_by_id::(old.id); }); - held = Some(host); } take_preview(app, &mut old).cancel(app); } @@ -76,11 +73,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { take_preview(app, &mut open).cancel(app); } }); - let opened = match held { - Some(host) => Some(host.with(|h| h.open(dialog.held_ok()))), - None => open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }), - }; - match opened { + match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) { Some(id) => { app.addon_dialogs.tangent_radius = Some(Open { id, click: p.clone(), doc, tried: None, note: None, preview: LivePreview::default(), shown_in: doc }); From 94afe08ebaaeb81aa5fe2046b4acb0fbc00ba573 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 23:26:28 -0800 Subject: [PATCH 24/42] Docs: unfilled-interior selection skips bounds hits and Preview-off layers A symbol instance, text, a blend or an envelope is hit anywhere in its bounds, and that hit keeps a click from reaching an unfilled path below. Art on a layer whose Preview is off is hit in outline, so its unfilled paths are not picked from inside. --- docs/mcp.md | 6 +++--- docs/target-app-parity.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index e5b9296a0d..3df356488c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9035,9 +9035,9 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture Pen with Alt. A handle shorter than that leaves its anchor to be picked when pressed nearer the anchor. - `objectSelectionByPathOnly`: a click inside a filled path or compound path doesn't select it, one on its path does. Off (the default), a selection tool click inside the closed subpaths of a path or compound path with no fill selects - it when the click hits no object's fill, stroke or path there, the topmost such path first, except in Outline view; - guides and clipping paths are still picked by - their path only (#9175). + it when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, + is hit anywhere in its bounds), the topmost such path first, except in Outline view and on a layer whose Preview is + off; guides and clipping paths are still picked by their path only (#9175). - `ctrlClickSelectsBehind` (on by default): a Selection tool click with `mods: {cmd: true}` (Command on macOS, Ctrl elsewhere) selects the object under the selected one there, the next such click the one under that, then the topmost again. Cmd held to borrow the selection tool from another tool clicks as usual. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 40b24d967d..9181fe2d78 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -694,7 +694,7 @@ since 2026-10-01. **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. -- **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no object's fill, stroke or path there; among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view is unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. +- **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. From ada0e99dfc63c5a9061a140c1a0759a48e9a0800 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:18:09 -0800 Subject: [PATCH 25/42] CI: the cold cache clear fails on a late warm leg before its job times out The script's 160-minute wait is timed from the cache warm leg's start, and the leg starts only after gate / select legs and a free runner. The job's 200-minute timeout left 40 minutes for that; a push to main on 2026-11-28 took 44 minutes from the run's start to the leg's start. A later start ended the job with a timeout instead of the script's error. The script now fails with its own error when the leg has not started 120 minutes after the script started, and the job's timeout is 290 minutes, longer than the start wait and the 160-minute save wait together. A test reads both timeouts from ci.yml and checks them against the script's limits. --- .github/workflows/ci.yml | 9 +++--- scripts/ci-clear-rolling-cache-tests.py | 40 +++++++++++++++++++++---- scripts/ci-clear-rolling-cache.py | 37 ++++++++++++++++++----- 3 files changed, 68 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b61d2429d0..e7ae30d3ca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,14 +89,15 @@ jobs: # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). # When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run - # failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg - # starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves - # 40 minutes for that. + # failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a + # free runner: the script fails when the leg has not started within 120 minutes, and then waits + # up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the + # script reports a leg that starts late with its own error before the job times out. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' runs-on: ubuntu-24.04 - timeout-minutes: 200 + timeout-minutes: 290 permissions: actions: write steps: diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index 734073aba3..8ccc8a5adc 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -9,6 +9,7 @@ import importlib.util import io import os from pathlib import Path +import re import subprocess import unittest from unittest import mock @@ -78,15 +79,42 @@ class Deadline(unittest.TestCase): before_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS - 60) after_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS + 60) self.assertGreater((before_limit - self.began).total_seconds(), clear.GIVE_UP_SECONDS) - self.assertFalse(clear.gave_up(late, before_limit, self.began)) - self.assertTrue(clear.gave_up(late, after_limit, self.began)) + self.assertFalse(clear.gave_up(late, before_limit)) + self.assertTrue(clear.gave_up(late, after_limit)) + self.assertFalse(clear.start_overdue(late, after_limit, self.began)) def test_a_leg_that_never_starts_is_timed_from_the_script_start(self): queued = warm_job("queued", started_at="2026-11-28T03:38:00Z") - later = self.began + timedelta(seconds=clear.GIVE_UP_SECONDS + 60) - self.assertFalse(clear.gave_up(None, self.began + timedelta(minutes=10), self.began)) - self.assertTrue(clear.gave_up(None, later, self.began)) - self.assertTrue(clear.gave_up(queued, later, self.began)) + before_limit = self.began + timedelta(seconds=clear.START_SECONDS - 60) + after_limit = self.began + timedelta(seconds=clear.START_SECONDS + 60) + self.assertFalse(clear.start_overdue(None, before_limit, self.began)) + self.assertTrue(clear.start_overdue(None, after_limit, self.began)) + self.assertTrue(clear.start_overdue(queued, after_limit, self.began)) + self.assertFalse(clear.gave_up(queued, after_limit)) + + +class Workflow(unittest.TestCase): + ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text() + + def timeout_minutes(self, job): + """The first `timeout-minutes` under `job` in ci.yml.""" + lines = self.ci.splitlines() + start = lines.index(f" {job}:") + 1 + for line in lines[start:]: + if re.match(r" \S", line): + break + match = re.match(r"\s+timeout-minutes: (\d+)$", line) + if match: + return int(match.group(1)) + self.fail(f"no timeout-minutes under {job}") + + def test_the_job_outlasts_the_start_wait_and_the_save_wait(self): + # Five minutes are left for the steps before the script and for the deletion. + spare = self.timeout_minutes("cold-cache-clear") * 60 - clear.START_SECONDS - clear.GIVE_UP_SECONDS + self.assertGreaterEqual(spare, 5 * 60) + + def test_the_save_wait_outlasts_the_gate(self): + self.assertGreater(clear.GIVE_UP_SECONDS, self.timeout_minutes("gate") * 60) class Jobs(unittest.TestCase): diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index e9b52d2493..3c27809187 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -16,8 +16,8 @@ save step started saves nothing: its old entries stay, and this exits 1, so "Re- runs it again beside the re-run leg. A save step that is canceled or fails after the old entries were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure in a later post step does not count once the save step has succeeded. This also exits 1 when the -leg has not reached its save, or its save has not finished, GIVE_UP_SECONDS after the leg started. -An absent warm leg is treated as finished only +leg has not started START_SECONDS after this script started, and when the leg has not reached its +save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only when the most recent earlier attempt that lists it reports success and the current attempt lists no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling because reusable-workflow dependencies may still be scheduling it. @@ -46,6 +46,12 @@ PAGE_SIZE = 100 # Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold # leg that starts late and runs to its limit still reaches its save before this gives up. GIVE_UP_SECONDS = 160 * 60 +# How long the leg may take to start, timed from this script's start: the leg waits for +# `gate / select legs` and then for a runner, which took 44 minutes on a push to main on +# 2026-11-28. The `cold-cache-clear` job's `timeout-minutes` in ci.yml is longer than +# START_SECONDS and GIVE_UP_SECONDS together, so this exits with its own error before the job +# times out. +START_SECONDS = 120 * 60 STOPPED = ('failure', 'cancelled', 'timed_out') # Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. TOLERATED_FAILURES = ('Trim the cache entry to this build',) @@ -85,11 +91,22 @@ def save_finished(job): return job.get('status') == 'completed' or (step is not None and step['status'] == 'completed') -def gave_up(job, now, began): - """True once GIVE_UP_SECONDS have passed since the warm leg started, or since `began` (this - script's start) while the leg has not started.""" +def started_at(job): + """The warm leg's start time, or None while the leg has not started.""" started = job.get('started_at') if job and job.get('status') in ('in_progress', 'completed') else None - return (now - (parse_time(started) if started else began)).total_seconds() > GIVE_UP_SECONDS + return parse_time(started) if started else None + + +def start_overdue(job, now, began): + """True once START_SECONDS have passed since `began` (this script's start) and the warm leg + has not started.""" + return started_at(job) is None and (now - began).total_seconds() > START_SECONDS + + +def gave_up(job, now): + """True once GIVE_UP_SECONDS have passed since the warm leg started.""" + started = started_at(job) + return started is not None and (now - started).total_seconds() > GIVE_UP_SECONDS def all_caches(fetch): @@ -171,7 +188,11 @@ def main(): return 1 print('the cache warm leg finished without a save step; nothing deleted') return - if gave_up(job, datetime.now(timezone.utc), began): + now = datetime.now(timezone.utc) + if start_overdue(job, now, began): + print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') + return 1 + if gave_up(job, now): print('::error::the cache warm leg never reached its save; nothing deleted') return 1 time.sleep(POLL_SECONDS) @@ -190,7 +211,7 @@ def main(): print(result.stderr, end='', file=sys.stderr) return result.returncode while not save_finished(job): - if gave_up(job, datetime.now(timezone.utc), began): + if gave_up(job, datetime.now(timezone.utc)): print(f'::error::{SAVE_LOST}') return 1 time.sleep(POLL_SECONDS) From 5044b75ccf1c2e8e16b9467a15ef5100711579bd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:38:02 -0800 Subject: [PATCH 26/42] Info panels: empty readouts offer no Copy action A panel readout that cannot be copied (an empty value, a disabled row or a value clipped out of view) still told screen readers it had a Copy action, and the action did nothing. An empty Link Info row, such as Color Space for a placed document, showed it. The Copy description and click action are now added only when a click on the value would copy. New tests in panel_readout_copy.rs: - empty_link_info_values_do_not_offer_copy: the empty Color Space row of a placed .vectorcraft link has no Copy action, and a forged click on it copies nothing. - info_readout_copy_requires_the_press_and_release_inside_its_bounds: on the Info panel's W readout, a press outside followed by a release inside copies nothing, with the release in the same frame or the next. - link_info_stays_visible_while_a_long_image_list_scrolls: with 32 images in each thumbnail size, Link Info stays in place and copyable while the list scrolls to its end. Follows #8826 by @yoriswind. --- crates/ui-egui/src/panels/doc_info.rs | 11 +- crates/ui-egui/tests/panel_readout_copy.rs | 138 +++++++++++++++++++++ 2 files changed, 145 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index f63f831cc4..41ec089303 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -97,10 +97,13 @@ pub(crate) fn copy_shown(ui: &mut Ui, shown: &egui::Response, value: &str) -> bo None => d.remove::(press_id), }); } - ui.ctx().accesskit_node_builder(shown.id, |node| { - node.set_description(tl!("Copy")); - node.add_action(egui::accesskit::Action::Click); - }); + // A value that cannot be copied (empty, disabled or clipped away) offers no Copy action. + if eligible { + ui.ctx().accesskit_node_builder(shown.id, |node| { + node.set_description(tl!("Copy")); + node.add_action(egui::accesskit::Action::Click); + }); + } let activated = ui.input(|i| i.num_accesskit_action_requests(shown.id, egui::accesskit::Action::Click) > 0); eligible && (activated diff --git a/crates/ui-egui/tests/panel_readout_copy.rs b/crates/ui-egui/tests/panel_readout_copy.rs index 5b5e048d09..e3145401ae 100644 --- a/crates/ui-egui/tests/panel_readout_copy.rs +++ b/crates/ui-egui/tests/panel_readout_copy.rs @@ -369,6 +369,114 @@ fn panel_readout_info_names_and_truncated_link_metadata_copy_full_displayed_text copy_long_link_value(&mut a); } +#[test] +fn empty_link_info_values_do_not_offer_copy() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + + let mut a = App::new(); + let folder = vectorcraft_testkit::TempDir::new("empty-link-readout"); + let path = folder.join("Original.vectorcraft"); + // The linked file is saved from this test's two generated rectangles. + let bytes = vectorcraft_format::save_with(&a.app.session.active().unwrap().doc, &vectorcraft_format::SaveOptions::default()).unwrap(); + std::fs::write(&path, bytes).unwrap(); + let placed = a.app.run("file.place", json!({"path": path})).unwrap(); + let info = a.app.run("links.info", json!({"id": placed["ids"][0]})).unwrap(); + assert_eq!(info["document"], true, "the fixture places the original document as a link"); + assert!(info["colorMode"].is_null(), "the linked document has no image color-mode value"); + a.panel("links"); + // A tall float shows every Link Info row, so no row is clipped away. + a.app.run("window.panel.float", json!({"panel": "links", "x": 520, "y": 120, "width": 300, "height": 700})).unwrap(); + a.app.run("window.panel.activate", json!({"panel": "links"})).unwrap(); + let out = a.settle(); + let nodes = &out.platform_output.accesskit_update.as_ref().unwrap().nodes; + assert!( + nodes.iter().any(|(_, node)| node.value() == Some("Original.vectorcraft") && node.supports_action(Action::Click)), + "the nonempty Name remains copyable" + ); + let empty: Vec<_> = nodes.iter().filter(|(_, node)| node.label() == Some("Color Space")).collect(); + assert!(!empty.is_empty(), "the actual Color Space row is present"); + assert!(empty.iter().all(|(_, node)| node.description() != Some("Copy")), "the empty Color Space value must not advertise Copy"); + let values: Vec<_> = empty.iter().filter(|(_, node)| node.value() == Some("")).collect(); + assert!(!values.is_empty(), "the actual empty value is present in the accessibility tree"); + assert!(values.iter().all(|(_, node)| !node.supports_action(Action::Click)), "the empty value has no copy action"); + let requests = empty + .iter() + .map(|(id, _)| { + Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node: *id, target_tree: TreeId::ROOT, data: None }) + }) + .collect(); + let before = a.snapshot(); + let sets = a.app.ui.status_sets; + assert!(copies(&a.frame(requests)).is_empty(), "a forged empty-value action does not copy"); + assert_no_delayed_copy(&mut a, "empty value"); + assert_eq!(a.app.ui.status_sets, sets, "an empty-value action reports no copy"); + assert_eq!(a.snapshot(), before, "an empty-value action leaves the document and history intact"); +} + +#[test] +fn link_info_stays_visible_while_a_long_image_list_scrolls() { + use egui::accesskit::{Action, Role}; + + // Each layout places 32 generated images before scrolling and copying. + for size in ["none", "small", "medium", "large"] { + let mut a = App::new(); + for index in 0..32 { + place_original_png(&mut a, &format!("Original-image-{index:02}.png")); + } + let selected = "Original-image-31.png"; + a.app.run("ui.links.thumbnails", json!({"size": size})).unwrap(); + a.panel("links"); + a.app.run("window.panel.float", json!({"panel": "links", "x": 520, "y": 120, "width": 220, "height": 700})).unwrap(); + a.app.run("window.panel.activate", json!({"panel": "links"})).unwrap(); + let out = a.settle(); + let nodes = &out.platform_output.accesskit_update.as_ref().unwrap().nodes; + let body = nodes + .iter() + .filter(|(_, node)| node.role() == Role::TabPanel) + .map(|(_, node)| location_node_rect(node)) + .find(|rect| (rect.left() - 520.0).abs() < 1.0) + .unwrap(); + let name_rect = |out: &egui::FullOutput| { + let fields: Vec<_> = out + .platform_output + .accesskit_update + .as_ref() + .unwrap() + .nodes + .iter() + .filter(|(_, node)| node.label() == Some("Name") && node.value() == Some(selected) && node.supports_action(Action::Click)) + .collect(); + assert_eq!(fields.len(), 1, "{size}: the selected image has one visible Name copy target"); + let rect = location_node_rect(&fields[0].1); + assert!(body.contains_rect(rect), "{size}: the selected image's Name remains inside the panel"); + rect + }; + let before = name_rect(&out); + let row = nodes.iter().find(|(_, node)| node.role() == Role::ListItem && node.label() == Some(selected)).unwrap(); + let row = location_node_rect(&row.1); + let snapshot = a.snapshot(); + let first_visible = |out: &egui::FullOutput| { + out.platform_output.accesskit_update.as_ref().unwrap().nodes.iter().any(|(_, node)| { + node.role() == Role::ListItem && node.label() == Some("Original-image-00.png") && body.contains_rect(location_node_rect(node)) + }) + }; + assert!(!first_visible(&out), "{size}: the list starts with its oldest image scrolled out of view"); + let mut scrolled = out; + for _ in 0..32 { + a.frame(vec![Event::PointerMoved(row.center())]); + a.frame(vec![craft::ui::testing::pointer::wheel(-body.height() * 32.0)]); + scrolled = a.settle(); + assert_eq!(name_rect(&scrolled), before, "{size}: scrolling the list keeps Link Info in place"); + if first_visible(&scrolled) { + break; + } + } + assert!(first_visible(&scrolled), "{size}: scrolling the list reaches its oldest image"); + copy_at(&mut a, before.center(), selected); + assert_eq!(a.snapshot(), snapshot, "{size}: scrolling and copying leave the drawing and history unchanged"); + } +} + fn assert_no_delayed_copy(a: &mut App, kind: &str) { let copied = copies(&a.deadline()); assert!(copied.is_empty(), "{kind}: unexpected delayed copy {copied:?}"); @@ -705,3 +813,33 @@ fn review_4714788866_readout_copy_requires_an_inside_primary_press() { assert_no_delayed_copy(&mut a, "accepted inside readout press"); assert_eq!(a.snapshot(), before); } + +#[test] +fn info_readout_copy_requires_the_press_and_release_inside_its_bounds() { + for same_frame in [true, false] { + let mut a = App::new(); + let out = a.panel("info"); + let value = "W: 37 pt"; + let id = review_8826_readout_node(&out, value); + let node = &out.platform_output.accesskit_update.as_ref().unwrap().nodes.iter().find(|(key, _)| *key == id).unwrap().1; + let bounds = location_node_rect(node); + let outside = egui::pos2(bounds.left() - 1.0, bounds.center().y); + let inside = egui::pos2(bounds.left() + 1.0, bounds.center().y); + assert!(!bounds.contains(outside) && bounds.contains(inside)); + assert!(outside.distance(inside) < a.ctx.options(|o| o.input_options.max_click_dist), "CONTROL: the motion is a click, not a drag"); + let before = a.snapshot(); + let sets = a.app.ui.status_sets; + let mut events = vec![Event::PointerMoved(outside), button(outside, true)]; + if !same_frame { + assert!(copies(&a.frame(events)).is_empty()); + events = Vec::new(); + } + events.extend([Event::PointerMoved(inside), button(inside, false)]); + let release = a.frame(events); + assert!(copies(&release).is_empty(), "a press outside cannot copy on a release inside; same frame: {same_frame}"); + assert_no_delayed_copy(&mut a, "outside press"); + assert_eq!(a.app.ui.status_sets, sets, "the rejected gesture does not report a copy"); + assert_eq!(a.snapshot(), before, "the rejected gesture preserves the document, selection and history"); + copy_at(&mut a, bounds.center(), value); + } +} From ab260718f59578e4f73071de326dc050de995970 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:45:19 -0800 Subject: [PATCH 27/42] CI: the cold cache clear fails when the warm leg starts after the start limit start_overdue only looked at a leg that had not started, so a leg that started 5 seconds past START_SECONDS and reached its save was let through and the old entries were deleted. The script now exits 1 before the save check when the leg's start time is more than START_SECONDS after the script started. --- scripts/ci-clear-rolling-cache-tests.py | 23 +++++++++++++++++++++++ scripts/ci-clear-rolling-cache.py | 9 +++++++++ 2 files changed, 32 insertions(+) diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index 8ccc8a5adc..a284579d16 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -92,6 +92,13 @@ class Deadline(unittest.TestCase): self.assertTrue(clear.start_overdue(queued, after_limit, self.began)) self.assertFalse(clear.gave_up(queued, after_limit)) + def test_a_leg_that_starts_after_the_start_limit_fails(self): + at = lambda seconds: warm_job("in_progress", started_at=(self.began + timedelta(seconds=seconds)).isoformat()) + self.assertTrue(clear.started_late(at(clear.START_SECONDS + 5), self.began)) + self.assertFalse(clear.started_late(at(clear.START_SECONDS - 10), self.began)) + self.assertFalse(clear.started_late(warm_job("queued"), self.began)) + self.assertFalse(clear.started_late(None, self.began)) + class Workflow(unittest.TestCase): ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text() @@ -215,6 +222,22 @@ class AfterDeletion(unittest.TestCase): canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")]) self.assertEqual(self.run_main(canceled), 1) + def test_a_leg_that_starts_late_and_saves_deletes_nothing(self): + # Clock.now() is 04:00, so the leg starts 120 minutes 5 seconds after the script. + late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T06:00:05Z") + deleted = [] + + def run(args, **kwargs): + deleted.append(args[-1]) + return subprocess.CompletedProcess(args, 0, "", "") + + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", lambda url: {"jobs": ME + [late]}), mock.patch.object(clear.subprocess, "run", run), \ + mock.patch.object(clear.time, "sleep"), mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), \ + contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(clear.main(), 1) + self.assertEqual(deleted, []) + def test_a_save_that_fails_after_the_deletion_exits_1(self): failed = warm_job("completed", "failure", [("Gate", "completed", "success"), ("Post Setup", "completed", "failure")]) self.assertEqual(self.run_main(failed), 1) diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index 3c27809187..3b913d68f7 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -103,6 +103,12 @@ def start_overdue(job, now, began): return started_at(job) is None and (now - began).total_seconds() > START_SECONDS +def started_late(job, began): + """True when the warm leg started more than START_SECONDS after `began` (this script's start).""" + started = started_at(job) + return started is not None and (started - began).total_seconds() > START_SECONDS + + def gave_up(job, now): """True once GIVE_UP_SECONDS have passed since the warm leg started.""" started = started_at(job) @@ -167,6 +173,9 @@ def main(): while True: jobs = gh(jobs_url) or {} job = warm_job(jobs.get('jobs', [])) + if started_late(job, began): + print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') + return 1 if job and saving(job): break if job is None: From e8ab35ad0cb0d85fde227a9bc685078de0fde1dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:48:26 -0800 Subject: [PATCH 28/42] Outline view: a group measures a Preview-off sublayer in the sublayer's mode A layer whose Preview is off draws a placed document in it as the crossed box, and effects that change geometry reshape that box. Two cull-bounds paths measured such a sublayer in the mode around it instead: - A group with effects of its own (a drop shadow, for example) is measured by fx::cull_bounds, which did not enter each layer's own mode. The group was culled where the sublayer's moved crossed box was in view. Each layer in that walk is now measured in the mode its Layer Options give it. - A group's cached bounds were keyed only on whether placed documents are crossed. Turning Show Images in Outline Mode on or off changes a Preview-off sublayer's mode without changing that, so the group kept its old bounds. Every object other than a path is now keyed on the full layer mode. --- crates/render/src/fx/bounds.rs | 3 ++ crates/render/src/renderer/nodes.rs | 16 +++---- crates/render/src/tests/placed_document.rs | 51 ++++++++++++++++++++++ 3 files changed, 60 insertions(+), 10 deletions(-) diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index be4cfb5f77..c8b37acbc7 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -672,6 +672,9 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO /// linear part. With `brush` true, the members of a group or layer are measured with the room /// their brushed strokes leave for brush art ([`member_cull_bounds`]). fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: bool) -> Option { + // A layer is measured in the mode its Layer Options draw it in, as the renderer measures the + // members of a group or layer without effects ([`crate::Renderer::bounds_of`]). + let _mode = crate::placed_document::enter_layer(n); let inner = |c: &Node| cull_bounds_in(symbols, c, after_reshape, false); let member = |c: &Node| member_cull_bounds(symbols, c, after_reshape, brush); // The art that a group's or layer's crop marks or Vector Halftone draw holds its members. The diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index b34f562ca1..8267ef278a 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -7,22 +7,18 @@ use super::{ use crate::kept_paths::{self, KeptPath}; use crate::node_checks::{holds_measured_three_d, measures_three_d}; use crate::placed_document::{InMode, LayerMode, enter_layer}; -use vectorcraft_doc::placed_document::crossed; /// The key of `a`'s cull bounds in [`Renderer::geom`]: its address, and in its lowest bits what the -/// bounds depend on besides `a`. For a layer that is the mode its sublayers are measured in -/// ([`LayerMode`], [`enter_layer`]); for an object other than a path, whether placed documents are -/// crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the art its effects make from a -/// placed document in it is the crossed box then. A node's address is aligned to 8 bytes, so no -/// other node has that key. +/// bounds depend on besides `a`. For an object other than a path that is the mode it is measured in +/// ([`LayerMode`]): it sets the mode of the layers in it ([`enter_layer`]), a group's included, and +/// whether placed documents are crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the +/// art its effects make from a placed document in it is the crossed box then. Placed documents are +/// crossed only in a mode. A node's address is aligned to 8 bytes, so no other node has that key. fn geom_key(a: &Node) -> usize { let at = std::ptr::from_ref(a) as usize; match a.kind { NodeKind::Path { .. } | NodeKind::Compound { .. } => at, - NodeKind::Layer { .. } => { - at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2) - } - _ => at | usize::from(crossed()), + _ => at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2), } } diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 738fd44488..fcb402ca51 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -335,6 +335,57 @@ fn outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a sublayer whose Preview is off"); } +#[test] +fn a_group_is_measured_again_when_show_images_in_outline_mode_changes_for_a_sublayer_in_it() { + // As above, in a sublayer whose Preview is off, held in a group. With Show Images in Outline + // Mode the file that can't be read draws nothing; turned off, the sublayer draws the moved box + // crossed, and the same renderer measures the group again. + let mut d = doc_with("outline-cull-2", b"bad"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let placed = d.remove(NodeId(50)).unwrap(); + let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { children, preview, .. } = &mut sub.kind { + children.push(placed); + *preview = false; + } + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::group(NodeId(91), vec![Arc::new(sub)])).unwrap(); + let view = Affine::translate((0.0, -55.0)); + let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + d.setup.outline_images = true; + r.render(&d, 100, 100, view, &preview); + d.setup.outline_images = false; + let crossed = r.render(&d, 100, 100, view, &preview); + assert!(crossed.pixel(30, 5)[0] < 200, "the moved box is drawn crossed"); + assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, view, &preview).pixels, "as a new renderer draws it"); +} + +#[test] +fn a_group_with_a_drop_shadow_measures_a_sublayer_in_it_in_the_sublayers_own_mode() { + // As above, in a sublayer whose Preview is off, held in a group with a Drop Shadow effect: the + // sublayer draws the moved box crossed, and the group's cull bounds reach it. + let mut d = doc_with("outline-cull-3", b"bad"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let placed = d.remove(NodeId(50)).unwrap(); + let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { children, preview, .. } = &mut sub.kind { + children.push(placed); + *preview = false; + } + let shadow = serde_json::json!({"x": 0, "y": 0, "blur": 0, "opacity": 0}); + let mut g = Node::group(NodeId(91), vec![Arc::new(sub)]); + g.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: shadow, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let view = Affine::translate((0.0, -55.0)); + let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let r = Renderer::new().render(&d, 100, 100, view, &preview); + assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a group with a drop shadow"); +} + #[test] fn an_edit_in_outline_mode_redraws_where_the_effects_move_the_crossed_box() { // A file that can't be read, in the box (10, 10)–(90, 50): a Transform effect added to it moves From 2b83acd239efd9882b60e6e85dc0f353ca98cf15 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:07:50 -0800 Subject: [PATCH 29/42] Document Setup: menus and fields apply a value only once it is chosen or committed Language, the Grid Colors menu, the two grid color hex fields and the bleed fields read the value each control reported in the frame, which includes a highlighted menu entry and a draft still being typed. A language highlighted with the arrow keys replaced the quotes, and Escape left them replaced; a highlighted Grid Colors preset replaced both colors; a partly typed hex code or bleed changed the dialog's values before Enter or Tab. The four reads now take the committed value, as New Document does. --- crates/ui-egui/src/dialogs/document_setup.rs | 149 ++++++++++++++++++- 1 file changed, 142 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 0c6e1b5f56..94ff0e8339 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -316,7 +316,6 @@ fn bleed_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext let bare_points = fields.bool("numbersWithoutUnitsArePoints").unwrap_or(true); let lengths = crate::fields::bare_points(LengthUnits::new(UnitKind::Points, unit_kind(unit), 72.0), bare_points); let parts = bleed_of(fields).map(|b| Mixed::Same(Some(b))); - // PLAN: assumed the linked fields' output reads as `out.edit.value()`, as the shape dialog uses it. let out = LinkedFields::<4>::new(tl!("Bleed:"), Bind::given(parts), Bind::bound(&mut linked)) .mode(LinkMode::Equal) .layout(LinkedLayout::Columns) @@ -324,7 +323,7 @@ fn bleed_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext .range(0.0..=MAX_BLEED) .lengths(lengths) .show(ui); - if let Some([Mixed::Same(Some(t)), Mixed::Same(Some(b)), Mixed::Same(Some(l)), Mixed::Same(Some(r))]) = out.edit.value().copied() { + if let Some([Mixed::Same(Some(t)), Mixed::Same(Some(b)), Mixed::Same(Some(l)), Mixed::Same(Some(r))]) = out.edit.events.committed().copied() { fields.set("bleed", FieldValue::List([t, b, l, r].map(FieldValue::Number).to_vec())); } if fields.bool("bleedLinked") != Some(linked) { @@ -397,7 +396,8 @@ fn grid_colors_row(setup: DocSetup) -> Param { let mut picked = None; let (mut wells, mut edits) = ([None; 2], [None; 2]); let shown = Stack::new().show(ui, |ui, _| { - picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); + picked = + Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).events.committed().cloned(); Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { let number = (i + 1).to_string(); @@ -411,7 +411,7 @@ fn grid_colors_row(setup: DocSetup) -> Param { let [r, g, b, _] = color.to_rgba8(1.0); let srgb = box_color(color); wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); - edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); + edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).events.committed().copied(); } }); }); @@ -548,7 +548,7 @@ fn typography() -> Vec { fn language_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext) -> egui::Response { let languages: Vec> = LANGUAGES.iter().map(|(l, _, _)| Entry::new(l.to_string(), l.to_string())).collect(); let current = fields.text("language").unwrap_or_default().to_string(); - let picked = Select::new(tl!("Language:"), Bind::given(current), &languages).show(ui).value().cloned(); + let picked = Select::new(tl!("Language:"), Bind::given(current), &languages).show(ui).events.committed().cloned(); if let Some(language) = picked { if let Some(q) = language_quotes(&language) { fields.set("quotes.double", q.double.iter().collect::()); @@ -581,15 +581,18 @@ fn color(mode: ColorMode) -> Vec { #[cfg(test)] mod tests { use craft::theme::Srgba; + use craft::ui::contract::Role; use craft::ui::dialog::{DialogId, HeldOk, dialog_id}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedPropertiesDialog}; - use egui::{Pos2, Rect, vec2}; + use egui::{Key, Modifiers, Pos2, Rect, vec2}; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint, cms}; - use vectorcraft_doc::{ColorMode, NodeId}; + use vectorcraft_doc::setup::{GRID_COLOR_PRESETS, LANGUAGES}; + use vectorcraft_doc::{ColorMode, NodeId, Quotes}; use vectorcraft_engine::Session; use crate::VectorcraftApp; + use crate::tests::panel_harness::Panel; /// The dialog's id. fn id() -> DialogId { @@ -656,6 +659,138 @@ mod tests { app.session.active().unwrap().history.undo.len() } + /// Document Setup open on `tab` over a 200 × 200 document, drawn in the panel harness. + fn setup_panel(tab: &str) -> Panel { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1280.0, 1100.0)); + panel.app().run("file.documentSetup", json!({})).unwrap(); + set(&panel.app(), panel.ctx(), "tab", json!(tab)); + panel.frame(); + panel.frame(); + panel + } + + /// The dialog's values in the panel harness. + fn panel_values(panel: &Panel) -> serde_json::Map { + super::json_map(&fields(&panel.app())) + } + + /// Clicks OK in the panel harness: the dialog closes with the values applied. + fn panel_ok(panel: &mut Panel) { + panel.click("OK"); + let app = panel.app(); + assert!(!is_open(&app), "{}", app.ui.status); + } + + /// A language highlighted in the Language menu changes neither the language nor the quotes, and + /// Escape closes the menu with the dialog open and its values as they were. + #[test] + fn a_highlighted_language_changes_nothing_until_it_is_chosen() { + let mut panel = setup_panel("Type"); + let before = panel_values(&panel); + panel.click_role("Language", Role::COMBO_BOX); + panel.key(Key::End, Modifiers::NONE); + assert_eq!(panel_values(&panel), before, "a highlighted language changes no field"); + panel.key(Key::Escape, Modifiers::NONE); + assert!(is_open(&panel.app()), "Escape closes the menu, not the dialog"); + assert_eq!(panel_values(&panel), before, "Escape leaves the language and quotes as they were"); + panel_ok(&mut panel); + let setup = panel.app().session.active().unwrap().doc.setup.clone(); + assert_eq!((setup.language.as_str(), setup.quotes), (LANGUAGES[0].0, Quotes::ENGLISH)); + } + + /// A language chosen with Enter brings its quotes, and OK applies both. + #[test] + fn a_language_chosen_with_enter_brings_its_quotes() { + let mut panel = setup_panel("Type"); + let (language, _, quotes) = LANGUAGES[LANGUAGES.len() - 1]; + panel.click_role("Language", Role::COMBO_BOX); + panel.key(Key::End, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + let values = panel_values(&panel); + assert_eq!(values["language"], json!(language)); + assert_eq!(values["quotes.double"], json!(quotes.double.iter().collect::())); + assert_eq!(values["quotes.single"], json!(quotes.single.iter().collect::())); + panel_ok(&mut panel); + let setup = panel.app().session.active().unwrap().doc.setup.clone(); + assert_eq!((setup.language.as_str(), setup.quotes), (language, quotes)); + } + + /// A preset highlighted in the Grid Colors menu changes no color, and Escape closes the menu with + /// the dialog open and the grid colors as they were. + #[test] + fn a_highlighted_grid_colors_preset_changes_nothing_until_it_is_chosen() { + let mut panel = setup_panel("Transparency"); + let before = panel_values(&panel); + panel.click_role("Grid Colors:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(panel_values(&panel), before, "a highlighted preset changes no field"); + panel.key(Key::Escape, Modifiers::NONE); + assert!(is_open(&panel.app()), "Escape closes the menu, not the dialog"); + assert_eq!(panel_values(&panel), before, "Escape leaves the grid colors as they were"); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); + } + + /// A Grid Colors preset chosen with Enter sets both colors, and OK applies them. + #[test] + fn a_grid_colors_preset_chosen_with_enter_sets_both_colors() { + let mut panel = setup_panel("Transparency"); + panel.click_role("Grid Colors:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + let medium = GRID_COLOR_PRESETS[1].1; + assert_eq!(dialog_grid(&panel.app()), medium.to_vec()); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, medium); + } + + /// A hex code typed into a grid color's field changes no color while it is a draft; Tab commits + /// it, and OK applies it. + #[test] + fn a_grid_color_hex_draft_applies_once_committed() { + let mut panel = setup_panel("Transparency"); + let before = panel_values(&panel); + panel.click_role("Grid Colors: 1", Role::TEXT_INPUT); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("123456"); + assert_eq!(panel_values(&panel), before, "the typed draft changes no field"); + panel.key(Key::Tab, Modifiers::NONE); + assert_eq!(dialog_grid(&panel.app()), ["#123456", LIGHT[1]].map(hex).to_vec()); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, ["#123456", LIGHT[1]].map(hex)); + } + + /// A bleed typed into Top changes no side while it is a draft; Tab commits it to the four linked + /// sides, and OK applies them. + #[test] + fn a_bleed_draft_applies_once_committed() { + let mut panel = setup_panel("General"); + let before = panel_values(&panel); + panel.click("Top"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("3"); + assert_eq!(panel.value("Top").as_deref(), Some("3"), "the field holds the typed draft"); + assert_eq!(panel_values(&panel), before, "the typed draft changes no field"); + panel.key(Key::Tab, Modifiers::NONE); + assert_eq!(super::bleed_of(&fields(&panel.app())), [3.0; 4]); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.bleed, [3.0; 4]); + } + + /// A bleed draft still in the focused field when OK is clicked is applied. + #[test] + fn ok_applies_the_focused_bleed_draft() { + let mut panel = setup_panel("General"); + panel.click("Top"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("3"); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.bleed, [3.0; 4]); + } + fn check_source_document(edit_artboards: bool) { let (mut app, ctx) = new_app(); let source = app.session.active().unwrap().uid; From 658151d45cd4472828da889445aa7db428641bac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:08:44 -0800 Subject: [PATCH 30/42] Docs: Outline view row says which layers draw placed documents crossed in Preview mode The Outline view row in docs/ui-parity.md said Preview mode draws linked images and placed documents as before. On screen, a layer whose Preview is off draws in outline in Preview mode, so its placed documents are crossed and its linked images show their crossed frames. A template layer in Outline mode draws them as Preview mode does. The row now says so. --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index de4dbdbc48..bceff53d7b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -558,7 +558,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | | Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: while the artboards show, the canvas outside the artboards is white in every interface brightness and Canvas Color, and the artboards keep their paper and edges and draw no shadows. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | | Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | -| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Preview mode and output draw them as before. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | +| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | From fda03c81ede18bf75aea82fa0b6b81ada0471be9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:55:53 -0800 Subject: [PATCH 31/42] .ai import: a placed EPS file whose bytes the editing data includes opens as a placed document A .ai file's editing data can include a placed EPS file's bytes between %%BeginDocument: and %%EndDocument. The reader did not read those bytes: in the %AI5_BeginPlace form the placed file showed only the preview the data keeps of it, or an unread placeholder box without one, and in the version 7 form the art the file draws came in as editable paths with a note that placed files weren't read. - The reader keeps those bytes (up to 256 MB) and makes the placed file a placed document of them, in the file's bounding box where the matrix puts it. It draws its art whether or not its file is found, and a native save keeps the bytes. The version 7 form's placed EPS art is no longer editable on open. - A placed file stays as before when its bytes are a DCS file (File > Place makes those linked images), have no bounding box of their own, carry a VectorCraft document (as VectorCraft's EPS export writes), don't read as an EPS file, or belong to a file named .ai or .ait. What reading the bytes warns of is in the open result. - One with a preview that an image variable binds stays the linked image showing its preview, as a placed PDF page does. - The link takes the size and hash of the bytes, so a file found unchanged is neither missing nor modified. - Drawing and the open check each read at most 8 placed EPS files inside one another, so a file whose included files include others opens. The open check draws the placed documents inside the bytes from their previews, and it reads each included file once at each depth. A file nested 12 levels deep opens with at most 8 drawing reads and 72 checks. - File > Package with Copy Fonts reads the type of a placed EPS file, as it reads a placed PDF page's, and of the EPS files it includes in turn, pattern art included. - On %_ lines the %_ that starts each line is taken off. Then one line end is taken off the end of the bytes when another line end comes before it: the one the %%BeginDocument: line ends with when the bytes end with it, otherwise the last one. An LF after a CR is kept with it when the file's first line ends with CRLF. Docs: docs/target-app-parity.md. --- crates/doc/src/placed_document.rs | 44 +++- crates/engine/Cargo.toml | 3 +- crates/engine/src/cmd/package.rs | 39 ++- crates/engine/src/cmd/place/document.rs | 35 ++- crates/engine/src/tests/package.rs | 76 ++++++ crates/engine/src/tests/placed_document.rs | 121 +++++++++ crates/engine/tests/import_fuzz.rs | 37 +++ crates/eps/Cargo.toml | 3 +- crates/eps/src/import.rs | 6 + crates/eps/src/import/ai.rs | 8 +- crates/eps/src/import/ai/read.rs | 37 ++- crates/eps/src/import/ai/read/art.rs | 270 ++++++++++++++++++++- crates/eps/src/import/ai/read/document.rs | 1 + crates/eps/src/import/ai/read/types.rs | 23 +- crates/eps/src/import/ai/tests.rs | 188 +++++++++++++- crates/eps/src/import/native.rs | 2 + crates/eps/src/import/native/build.rs | 45 +++- crates/eps/src/import/tests_illustrator.rs | 41 +++- crates/eps/src/import/tests_native.rs | 113 +++++++++ crates/eps/src/lib.rs | 12 + docs/target-app-parity.md | 1 + 21 files changed, 1054 insertions(+), 51 deletions(-) diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index d72048dc0a..ef627c6840 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -380,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>; static LOADER: OnceLock = OnceLock::new(); +std::thread_local! { + /// Open checks use previews rather than loading placed documents for drawing. + static PREVIEWS_ONLY: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Restores whether only previews are used when an open check ends, including on unwind. +struct PreviewsOnly(bool); + +impl Drop for PreviewsOnly { + fn drop(&mut self) { + PREVIEWS_ONLY.with(|p| p.set(self.0)); + } +} + +/// Run an open check using placed documents' previews instead of loading their art on this +/// thread. Nested checks keep the scope active until the outer check ends. This prevents an +/// open check and drawing from recursively loading each other's nested files. +pub fn with_previews(check: impl FnOnce() -> T) -> T { + let _scope = PreviewsOnly(PREVIEWS_ONLY.with(|p| p.replace(true))); + check() +} + /// Register how files are read (the first registration stays). pub fn set_loader(l: Loader) { // Already set: the same loader, registered by another session. @@ -454,8 +476,12 @@ impl Cache { } /// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a -/// placed document from. `None` when it can't be read (or no loader is registered). +/// placed document from. `None` when it can't be read, no loader is registered, or an open check +/// uses [`with_previews`]. pub fn read(p: &PlacedDocument, bytes: &Arc>) -> Option> { + if PREVIEWS_ONLY.with(std::cell::Cell::get) { + return None; + } if let Some(e) = cache().get(&p.key, false, Some(bytes)) { return Some(e); } @@ -738,6 +764,22 @@ mod tests { Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0))) } + /// Nested open checks skip both new and cached art, and restore ordinary reads afterward. + #[test] + fn open_checks_leave_placed_documents_for_drawing_afterward() { + set_loader(stub_loader); + let p = placed("open-check-1"); + let bytes = Arc::new(b"leaf".to_vec()); + with_previews(|| assert!(read(&p, &bytes).is_none())); + assert!(read(&p, &bytes).is_some()); + with_previews(|| { + assert!(read(&p, &bytes).is_none()); + with_previews(|| assert!(read(&p, &bytes).is_none())); + assert!(read(&p, &bytes).is_none()); + }); + assert!(read(&p, &bytes).is_some()); + } + /// A color-masked image in a placed document's art keeps its masked pixels under the prefixed /// names its resources get. #[test] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index eb751c26d2..4d576cf153 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -122,7 +122,8 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF, and the work its import takes. vectorcraft-pdf = { workspace = true, features = ["read-count"] } -# The work `.ai` blends take to be checked and made live. +# The work `.ai` blends take to be checked and made live, and how many included EPS open checks +# an open performs. vectorcraft-eps = { workspace = true, features = ["work-count"] } # How many times the symbol list is read to find symbols by name, and how many objects are # measured against locked artboards. diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index e959f126c0..83d9fab4d3 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -106,7 +106,7 @@ type PlacedPages = Vec<(u32, bool, vectorcraft_doc::PageBox)>; #[cfg(test)] thread_local! { - /// Tests: how many placed PDF or `.ai` pages [`page_fonts`] read on this thread. + /// Tests: how many placed PDF, `.ai` or EPS pages [`page_fonts`] read on this thread. pub(crate) static PAGES_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many linked `.vectorcraft` files had their preview and PDF read on this thread, /// to keep them in the rewritten copy. @@ -196,16 +196,41 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { } } -/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`); -/// none for other files. +/// The fonts of the type on `pages` of the PDF, `.ai` or EPS file `name` (`bytes`, found at +/// `path`), and on the placed documents that art holds (an EPS file whose bytes a legacy `.ai` or +/// EPS file includes), [`MAX_NESTED_PAGES`] deep; none for other files. fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet { + nested_page_fonts(name, bytes, path, pages, 0) +} + +/// The most placed documents [`page_fonts`] reads inside one another. +const MAX_NESTED_PAGES: usize = 8; + +/// [`page_fonts`], `depth` placed documents in. +fn nested_page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages, depth: usize) -> BTreeSet { let mut fonts = BTreeSet::new(); - if super::place::document::is_pdf(name, bytes) { + if super::place::document::is_pdf(name, bytes) || super::place::document::is_postscript(bytes) { for &(page, bounding, page_box) in pages { #[cfg(test)] PAGES_READ.with(|c| c.set(c.get() + 1)); - if let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) { - fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes)); + let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) else { continue }; + fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes)); + if depth + 1 >= MAX_NESTED_PAGES { + continue; + } + let mut inner = Vec::new(); + let patterns = a.doc.patterns.iter().flat_map(|p| p.art.iter().map(|n| &**n)); + for n in a.doc.layers.iter().map(|l| &**l).chain(a.doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(&a.nodes) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| { + if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind { + inner.push(p.clone()); + } + }); + } + for p in inner { + // Only the bytes the art keeps: its own file isn't looked for. + let Some(blob) = a.doc.images.get(&p.key).filter(|b| !b.is_proxy()) else { continue }; + fonts.extend(nested_page_fonts(p.link.name(), &blob.bytes, &p.link.path, &vec![(p.page(), p.bounding, p.page_box)], depth + 1)); } } } @@ -319,7 +344,7 @@ impl<'a> Collector<'a> { // Different linked documents can reuse the same stale absolute path yet // resolve it to distinct local assets. Keep a mapping per document. let mut local = BTreeMap::::new(); - // The fonts of the type on the PDF and `.ai` pages placed linked. + // The fonts of the type on the PDF, `.ai` and EPS pages placed linked. let mut placed_fonts = BTreeSet::new(); let mut placed = BTreeMap::::new(); let linked_files = |doc: &Document| match lookup { diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index a14b89fd25..f24242ed70 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -1,6 +1,7 @@ //! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file //! from a file, with `link`): one locked object showing an artboard of the document, a page of the -//! PDF or the EPS file's art, a [`PlacedDocument`]. +//! PDF or the EPS file's art, a [`PlacedDocument`]. An EPS file whose bytes a `.ai` file's editing +//! data includes opens as one too, read from those bytes. //! //! The object keeps the file's bytes (in the document's images, like image data) and the link; the //! art it shows is read from them the way placing the file without Link reads it @@ -223,6 +224,27 @@ impl Drop for Reading { } } +std::thread_local! { + /// How many placed documents [`read_document`] is reading inside one another on this thread. + static DRAWING: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A placed document being read for drawing ([`DRAWING`]): the count goes down when this goes. +struct Drawing; + +impl Drawing { + /// `None` when [`MAX_NESTED_READS`] are being read. + fn enter() -> Option { + DRAWING.with(|d| (d.get() < MAX_NESTED_READS).then(|| d.set(d.get() + 1))).map(|()| Drawing) + } +} + +impl Drop for Drawing { + fn drop(&mut self) { + DRAWING.with(|d| d.set(d.get().saturating_sub(1))); + } +} + /// `nodes` as one group, clipped to `clip` (its own ids: what drawing reads). fn group(nodes: Vec, clip: Option) -> Node { let mut children: Vec> = nodes.into_iter().map(Arc::new).collect(); @@ -234,11 +256,22 @@ fn group(nodes: Vec, clip: Option) -> Node { /// `p`'s file (`bytes`) read as the art it shows: how the document model reads placed documents /// ([`vectorcraft_doc::placed_document::set_loader`]). +/// `None` past [`MAX_NESTED_READS`] placed documents read inside one another: opening a file can +/// draw the placed documents in it, whose files can place others. pub(crate) fn read_document(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> { + let _drawing = Drawing::enter()?; + #[cfg(test)] + DOCUMENT_READS.with(|n| n.set(n.get() + 1)); let a = document_art(p.link.name(), bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, "draw").ok()?; Some((a.doc, group(a.nodes, a.clip), a.frame)) } +#[cfg(test)] +std::thread_local! { + /// Placed documents read for drawing on this thread, for tests that count work. + pub(crate) static DOCUMENT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// `p`'s file read again, while it is the file it was read from (how the document model gets it /// when only the preview is stored, [`vectorcraft_doc::placed_document::set_file_reader`]). pub(crate) fn read_file_again(p: &PlacedDocument) -> Option> { diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 344b5e436e..f0eeefd810 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -1115,6 +1115,82 @@ fn package_reads_no_placed_pdf_page_without_copy_fonts() { } } +/// With Copy Fonts on, Package reads the type of a placed EPS file whose bytes a `.ai` file's +/// editing data included, as it reads a placed PDF page's. +#[test] +fn package_reads_a_placed_eps_files_type_for_copy_fonts() { + use cmd::package::PAGES_READ; + use vectorcraft_testkit::ai; + let dir = Folder::new("package-placed-eps-fonts"); + let eps = + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Helvetica findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n"; + let src = dir.file("art/shape.eps"); + write(&src, eps.as_bytes()); + let src = src.replace('\\', "/"); + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n({src})`\n%%BeginDocument: {src}\n{eps}\n%%EndDocument\n~\n%AI5_EndPlace\n" + ); + let doc_path = dir.file("poster.ai"); + let page = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET"; + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)).as_bytes(), page)); + let mut s = session(); + open(&mut s, &doc_path); + let mut placed = 0; + s.doc().unwrap().doc.visit_placed(|_, _| placed += 1); + assert_eq!(placed, 1); + save(&mut s, &dir.file("poster.vectorcraft")); + let before = PAGES_READ.with(std::cell::Cell::get); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out"), "copyLinks": false, "copyFonts": true})); + assert_eq!(PAGES_READ.with(std::cell::Cell::get) - before, 1, "{r}"); + let listed = |r: &Value| r["fonts"].as_u64().unwrap_or(0) + r["skippedFonts"].as_array().map_or(0, |a| a.len() as u64); + assert_eq!(listed(&r), 1, "the type's font: {r}"); + + // Type only in an EPS file that the placed one, a legacy-format file, includes in turn. + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let typed = + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Courier findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n"; + let inner = format!("[1 0 0 1 0 0] 0 0 60 60 (inner.eps) `\n%%BeginDocument: inner.eps\n{typed}%%EndDocument\n~\n"); + let outer = format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n\ + %%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\ + {inner}LB\n%AI5_EndLayer--\nshowpage\n%%EOF\n" + ); + write(&dir.file("art/shape.eps"), outer.as_bytes()); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page)); + open(&mut s, &doc_path); + save(&mut s, &dir.file("poster.vectorcraft")); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out2"), "copyLinks": false, "copyFonts": true})); + assert_eq!(listed(&r), 1, "the inner file's font: {r}"); + + // The included file is only in a pattern definition, outside the page's nodes. + let pattern = format!("%AI3_BeginPattern: (Type)\n(Type) 0 0 60 60\n0 A\n0 Xw\n{inner}E\n%AI3_EndPattern\n"); + let outer = outer.replace(&inner, "").replace("%AI5_BeginLayer", &format!("{pattern}%AI5_BeginLayer")); + let a = cmd::place::document::document_art("shape.eps", outer.as_bytes(), Some(&src), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap(); + let pattern = a.doc.pattern("Type").expect("the pattern definition is read"); + let mut placements = 0; + for n in &pattern.art { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| { + assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)), "the type is only in the included file"); + if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind { + placements += 1; + let blob = &a.doc.images[&p.key]; + assert!(!blob.is_proxy()); + assert_eq!(blob.bytes.as_slice(), typed.as_bytes()); + } + }); + } + assert_eq!(placements, 1, "the pattern holds the included file"); + for n in &a.nodes { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::PlacedDocument(_)))); + } + write(&dir.file("art/shape.eps"), outer.as_bytes()); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page)); + open(&mut s, &doc_path); + save(&mut s, &dir.file("poster.vectorcraft")); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out3"), "copyLinks": false, "copyFonts": true})); + assert_eq!(listed(&r), 1, "the pattern's included file's font: {r}"); +} + /// `dir/art/badge.ai`, saved without its PDF part, its art placing each of `pics` (600 × 300 px, /// with a 2×1 preview) → its path. fn ai_placing(dir: &Folder, pics: &[&str]) -> String { diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 3458c5ae37..00f976ab3f 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -934,6 +934,127 @@ fn an_ai_file_that_places_itself_opens() { assert_eq!(found, [at], "{r}"); } +/// A placed EPS file whose bytes a `.ai` file's editing data includes (between `%%BeginDocument:` +/// and `%%EndDocument`) opens as a placed document of those bytes: it draws its art with its file +/// missing, and its file found unchanged is neither missing nor modified. A native save keeps the +/// bytes, so the copy reopens and draws without the file. +#[test] +fn a_placed_eps_file_included_in_an_ai_files_editing_data_draws_without_its_file() { + use vectorcraft_testkit::ai; + let dir = Folder::new("placed-eps-in-ai"); + // The file draws red and the page blue, so each check shows which one drew. + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor\n0 0 60 60 rectfill\n%%EOF\n"; + let (red, blue) = ([255, 0, 0], [0, 0, 255]); + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n(/no/such/folder/src/shape.eps)`\n\ + %%BeginDocument: /no/such/folder/src/shape.eps\n{eps}\n%%EndDocument\n%AI17_Begin_Content_if_version_gt:24 12\n\ + %AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n" + ); + let doc_path = dir.file("poster.ai"); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)); + write(&doc_path, &ai::ai(data.as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + let shown = |s: &Session| { + let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true); + let [r, g, b, _] = img.pixel(50, 50); + [r, g, b] + }; + let one = |s: &Session| { + let d = &s.doc().unwrap().doc; + let mut found = vec![]; + d.visit_placed(|n, p| found.push((n.id, p.clone()))); + let [(id, p)] = &found[..] else { panic!("one placed document: {found:?}") }; + (*id, p.clone(), d.images[&p.key].clone()) + }; + let mut s = session(); + + let r = open(&mut s, &doc_path); + assert_eq!(r["missingLinks"][0]["name"].as_str(), Some("shape.eps"), "{r}"); + let (id, p, blob) = one(&s); + assert_eq!((blob.bytes.as_slice(), blob.mime.as_str()), (eps.as_bytes(), "application/postscript")); + assert_eq!(p.link.relative.as_deref(), Some("src/shape.eps")); + let at = bounds(&s, id); + assert!((at.x0 - 20.0).abs() < 0.01 && (at.y0 - 20.0).abs() < 0.01 && (at.width() - 60.0).abs() < 0.01, "{at:?}"); + assert!(near(shown(&s), red), "its art draws: {:?}", shown(&s)); + + write(&dir.file("src/shape.eps"), eps.as_bytes()); + let r = open(&mut s, &doc_path); + assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}"); + assert!(near(shown(&s), red)); + + let copy = dir.file("copy.vectorcraft"); + save(&mut s, ©); + std::fs::remove_file(dir.file("src/shape.eps")).unwrap(); + open(&mut s, ©); + let (_, _, blob) = one(&s); + assert_eq!(blob.bytes.as_slice(), eps.as_bytes(), "the bytes are saved"); + assert!(near(shown(&s), red), "and draw: {:?}", shown(&s)); + + // A file named as PostScript of another kind, or with a name that doesn't say, draws the same. + for name in ["shape.ps", "shape", "shape.dat"] { + let named = place.replace("shape.eps", name); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &named)).as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + open(&mut s, &doc_path); + let (_, p, blob) = one(&s); + assert_eq!((p.link.name(), blob.mime.as_str()), (name, "application/postscript")); + assert!(near(shown(&s), red), "{name} draws: {:?}", shown(&s)); + } + + // Bytes that can't be read leave the placed file unread: the file is read from its PDF part, + // and the object comes in as what the page draws there. + let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, broken))).as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + let r = open(&mut s, &doc_path); + assert!(near(shown(&s), blue), "the page's art: {:?} {r}", shown(&s)); +} + +/// A synthetic EPS file that includes another placed EPS file, `depth` levels deep. +fn nested_included_eps(depth: usize) -> String { + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let mut eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor\n10 20 40 30 rectfill\n%%EOF\n".to_string(); + for _ in 0..depth { + eps = format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\ + %%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\ + [1 0 0 1 0 0] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\nLB\n%AI5_EndLayer--\nshowpage\n%%EOF\n" + ); + } + eps +} + +/// Open checks and drawing must not recursively multiply each other's work. +#[test] +fn placed_eps_files_included_open_work_is_bounded() { + let dir = Folder::new("placed-eps-open-work"); + let path = dir.file("deep.eps"); + write(&path, nested_included_eps(12).as_bytes()); + let mut s = session(); + let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get); + let checks = vectorcraft_eps::included_eps_reads(); + open(&mut s, &path); + let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get) - drawings; + let checks = vectorcraft_eps::included_eps_reads() - checks; + eprintln!("included EPS work: {drawings} drawing reads, {checks} open checks"); + // At most 8 drawing loads, each with at most 8 parses for checks, plus the outer import's 8. + // Repeated structural reads share completed checks within each chain. + assert!(drawings <= 8, "{drawings} drawing reads, {checks} open checks"); + assert!(checks <= 8 * 8 + 8, "{drawings} drawing reads, {checks} open checks"); + assert!(drawings > 0 && checks > 0, "both read paths were exercised"); +} + +/// A legacy-format file (version 7 specification §16) placing an EPS file whose bytes it includes, +/// which is such a file in turn, 300 deep: it opens, reading a bounded number of them. +#[test] +fn placed_eps_files_included_300_deep_open() { + let dir = Folder::new("placed-eps-300-deep"); + let path = dir.file("deep.eps"); + write(&path, nested_included_eps(300).as_bytes()); + let mut s = session(); + open(&mut s, &path); + let mut placed = 0; + s.doc().unwrap().doc.visit_placed(|_, _| placed += 1); + assert_eq!(placed, 1); +} + #[test] fn a_pdf_compatible_ai_file_places_linked_like_a_pdf() { let dir = Folder::new("placed-ai-linked"); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 906f26771a..636c19fb36 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4950,6 +4950,37 @@ proptest! { survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + /// A `.ai` whose placed EPS files have their bytes included between `%%BeginDocument:` and + /// `%%EndDocument` (one on `%_` lines, one with a nested document and counted data in it), + /// damaged, opened and drawn: their bytes are read as an EPS file when drawn. + #[test] + fn ai_placed_eps_files_with_included_bytes_never_panic( + cut in 0usize..4_000, + edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', '`', '~', 'E', 'D'])), 0..12), + ) { + use vectorcraft_testkit::ai; + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 40\n%%EndComments\n0 0 1 setrgbcolor\n0 0 60 40 rectfill\n%%EOF\n"; + let nested = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n%%BeginDocument: c.eps\nnewpath\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n"; + let place = |path: &str, matrix: &str, doc: &str| { + format!( + "%AI5_BeginPlace\n%%FileType: 0\n{matrix} 0 0 60 40 4 4 0\n({path})`\n%%BeginDocument: {path}\n{doc}\n%%EndDocument\n\ + %AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n" + ) + }; + let hidden: String = place("/tmp/b.eps", "[1 0 0 1 20 20]", eps).lines().map(|l| format!("%_{l}\n")).collect(); + let body = format!("{}{hidden}{}", place("/tmp/a.eps", "[1 0 0 1 20 20]", eps), place("/tmp/c.eps", "[1 0 0 1 0 0]", nested)); + let fixture = ai::editing_data(200.0, 100.0, &ai::layer("L", &body)); + // A session reads placed documents' files when they are drawn. + let _ = vectorcraft_engine::Session::new(); + let whole = vectorcraft_engine::cmd::fileio::load("x.ai", &ai::ai(fixture.as_bytes(), "0 0 1 rg 20 20 60 40 re f")); + let mut placed = 0; + whole.iter().for_each(|l| l.doc.visit_placed(|_, _| placed += 1)); + prop_assert!(placed == 3 && fixture.len() < 4_000, "{placed} placed documents, {} bytes: {:?}", fixture.len(), whole.map(|l| l.warnings)); + let text = mutate_text(&fixture, cut, &edits); + let file = ai::ai(text.as_bytes(), "0 0 1 rg 20 20 60 40 re f"); + survive("hostile .ai placed EPS files with included bytes", || vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc))?; + } + /// A `.ai` whose type (point type turned, vertical type, area type, threaded area type and type /// on a path, their stubs with the frames' paths, and the text document they name, as the `.ai` /// writer writes them) is damaged: read from its editing data alone and beside a page. @@ -6390,6 +6421,12 @@ fn arb_ai_token() -> impl Strategy { "\n%%BeginData: 14 Binary Bytes\n", "\n%%BeginBinary: 99999999999\n", "\n%%BeginData: 3 Hex Lines\n", + // A placed EPS file's bytes included in the data: one drawn, one with a box it can't + // take, one on `%_` lines. + "\n%%BeginDocument: a.eps\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n0 0 1 setrgbcolor 0 0 9 9 rectfill\n%%EndDocument\n", + "\n%%BeginDocument: a.eps\n%!PS\n%%BoundingBox: 0 0 1e308 -5\n%%EndDocument\n", + "\n%_%%BeginDocument: a.eps\n%_%!PS\n%_0 0 9 9 rectfill\n%_%%EndDocument\n", + "[1 0 0 1 0 0] 0 0 1e308 1e308 4 4 0 (a.eps) `", "\n%AI5_EndPlace\n", "Xm", "50 -50 -100 -100 5000 -2000 Xm", diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index 52413b8c28..6539bf6686 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -9,7 +9,8 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P workspace = true [features] -# `vectorcraft_eps::blend_work` for other crates' tests (dev-dependencies only). +# `vectorcraft_eps::blend_work` and `vectorcraft_eps::included_eps_reads` for other crates' tests +# (dev-dependencies only). work-count = [] [dependencies] diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 4458f29d2b..38fba94616 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -280,6 +280,12 @@ pub fn page(bytes: &[u8]) -> Result { Ok(Rect::new(0.0, 0.0, urx - llx, ury - lly)) } +/// An EPS or PostScript file's bounding box (`%%HiResBoundingBox` when it has one) in its own +/// space, as `[llx, lly, urx, ury]`, read from its comments; `None` without one. +pub(crate) fn bounding_box(bytes: &[u8]) -> Option<[f64; 4]> { + Dsc::read(program(bytes).ok()?).bbox +} + /// [`import`], an Illustrator EPS through the editing copy of its art only when `editing_data` /// (else what its page prints, as any EPS). pub fn import_with(bytes: &[u8], editing_data: bool) -> Result { diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 149728decf..525eb71f22 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -62,12 +62,12 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color, - read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, + BLEND_BUDGET, LINKED_PREVIEWS, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, + parsed_type_color, read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ - BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, - palette, read_beside, read_in, symbols, variables, + BindingRef, Brushes, PaletteSwatches, PlacedEps, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, + graphic_styles, palette, read_beside, read_in, symbols, variables, }; #[cfg(test)] pub(crate) use style::ART_STYLE_PARSES; diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 66cdb82adc..2e822ec772 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -57,8 +57,13 @@ //! The version 7 form (§16) has no `%AI5_BeginPlace`: `[matrix] llx lly urx ury (path)` and //! `` ` ``, then `%%IncludeFile:` or the file between `%%BeginDocument:` and `%%EndDocument`, //! then `~`; its box is the file's `%%BoundingBox`. Newer files have three more numbers before -//! the path. Operands of any other shape, a second `` ` `` before `~` or an included document -//! that doesn't end leave the placed file unread. +//! the path. A placed EPS file whose bytes are included between `%%BeginDocument:` and +//! `%%EndDocument` (DSC 3.0 p. 68) is a placed document that keeps those bytes and draws them, +//! its file found or not; its box is the +//! file's bounding box, which the matrix takes from the file's own space (y up) into art space, +//! as in the version 7 form. +//! Operands of any other shape, a second `` ` `` before `~` or an included document that +//! doesn't end leave the placed file unread. //! - Art with an appearance the format can't write as plain art (several fills or strokes, //! effects, brushes) comes first as that look, drawn (a group, or an image where an effect //! rasterizes it), then the object itself on `%_` @@ -148,7 +153,7 @@ mod raster; mod types; pub(crate) use art::join_and; -use art::preview_png; +use art::{included_document, preview_png}; pub use document::{ BindingRef, Brushes, PaletteSwatches, Symbols, VariableRead, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, symbols, variables, @@ -159,11 +164,12 @@ pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_typ #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; +pub(crate) use types::LINKED_PREVIEWS; pub(crate) use types::MAX_NODES; -pub use types::PlacedPage; -use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; +use types::{BrushArtColors, FLIP, Frame, GState, Kind, MAX_PLACED_DOCUMENT, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; #[cfg(test)] pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; +pub use types::{PlacedEps, PlacedPage}; pub(super) use types::{blend_mode, blend_name}; #[path = "legacy_text.rs"] @@ -212,6 +218,8 @@ pub struct Structure { pub placed_elsewhere: Vec<(NodeId, Affine)>, /// The placed files that are pages of PDF or `.ai` files. pub placed_pages: Vec, + /// Included EPS files whose previews wait for variable binding before conversion. + pub placed_eps: Vec, /// The live envelopes read from the editing data, by id, with the drawn art each took the place /// of: the importer puts that art back when the layers with the envelopes don't draw as the page. pub envelopes_drawn: Vec<(NodeId, Node)>, @@ -667,6 +675,8 @@ struct Reader<'a> { placed_elsewhere: Vec<(NodeId, Affine)>, /// See [`Structure::placed_pages`]. placed_pages: Vec, + /// See [`Structure::placed_eps`]. + placed_eps: Vec, unread_elsewhere: Vec<(NodeId, Rect)>, /// CMYK samples converted, by value. cmyk_cache: HashMap<[u8; 4], [u8; 3]>, @@ -901,6 +911,7 @@ impl<'a> Reader<'a> { placeholders: vec![], placed_elsewhere: vec![], placed_pages: vec![], + placed_eps: vec![], placed_tails: vec![], unread_elsewhere: vec![], mesh: None, @@ -939,6 +950,15 @@ impl<'a> Reader<'a> { } } + /// The line end just before `doc`, an included document the lexer has just read: the one that + /// ends its `%%BeginDocument:` line. `None` when `doc` isn't in the data read so far. + fn line_end_before(&self, doc: &[u8]) -> Option<&'static [u8]> { + let read = self.lex.slice(0, self.lex.offset()); + let at = doc.as_ptr().addr().checked_sub(read.as_ptr().addr())?; + let before = read.get(..at)?; + [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| before.ends_with(e)) + } + fn run(&mut self) -> Result<(), String> { while let Some(t) = self.lex.next_token() { if self.done { @@ -961,11 +981,14 @@ impl<'a> Reader<'a> { p.preview = preview_png(d); } } - // A placed file's document, included whole: its art isn't read here. When no - // `%%EndDocument` ends it, the placed file isn't read. + // A placed file's document, included whole: its art isn't read here, its bytes are + // kept for the placed file. When no `%%EndDocument` ends it, the placed file isn't + // read. Tok::Document(d) => { + let sep = d.and_then(|d| self.line_end_before(d)); if let Some(p) = self.place.as_mut() { p.broken |= d.is_none(); + p.document = d.filter(|d| d.len() <= MAX_PLACED_DOCUMENT).map(|d| included_document(d, hidden, sep)); } } } diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 030c70aa51..95606c9ebb 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -2,17 +2,88 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::raster::{self, Limits, Shape}; use super::types::{ - FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, - MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, + EPS_MIME, FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, + MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedEps, PlacedPage, PlacedTail, }; use super::{ Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, NodeId, NodeKind, Obj, OpacityMask, PageBox, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps, }; -use vectorcraft_doc::links::missing_placeholder; +use vectorcraft_doc::PlacedDocument; +use vectorcraft_doc::links::{hash_bytes, missing_placeholder}; use vectorcraft_doc::placed_document::key_for; +use vectorcraft_pdf::is_postscript; + +/// Open-check results by content and nesting depth: the remaining depth changes their warnings. +type EpsChecks = Vec<((String, usize), Option>)>; + +/// The most open-check results kept during one outer check; no file bytes are retained. +const MAX_EPS_CHECKS: usize = 64; + +std::thread_local! { + /// How many included EPS files [`readable_eps`] is reading inside one another on this thread. + static READING_EPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Checks completed during this thread's outer check, including files that do not read. + static EPS_CHECKS: std::cell::RefCell = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// An included EPS file being read by [`readable_eps`] ([`READING_EPS`]): the count goes down when +/// this goes. +struct ReadingEps; + +impl ReadingEps { + /// `None` when 8 are being read. + fn enter() -> Option { + READING_EPS.with(|d| (d.get() < 8).then(|| d.set(d.get() + 1))).map(|()| Self) + } +} + +impl Drop for ReadingEps { + fn drop(&mut self) { + READING_EPS.with(|d| d.set(d.get().saturating_sub(1))); + if READING_EPS.with(std::cell::Cell::get) == 0 { + EPS_CHECKS.with_borrow_mut(Vec::clear); + } + } +} + +/// The warnings of reading `bytes` as an EPS file, the way a placed document's art is read from +/// them (art left out after an operator that isn't read, for one); `None` when they don't read. +/// Past 8 included files read inside one another they count as readable without warnings; drawing +/// reads a bounded number of them in turn. The check uses previews for placed documents, so +/// drawing does not start another chain of checks inside this one. Repeated structural reads +/// share completed checks at the same depth until the outer check ends. +fn readable_eps(bytes: &[u8]) -> Option> { + let key = (hash_bytes(bytes), READING_EPS.with(std::cell::Cell::get)); + if let Some(warnings) = EPS_CHECKS.with_borrow(|c| c.iter().find(|(k, _)| *k == key).map(|(_, warnings)| warnings.clone())) { + return warnings; + } + let Some(_reading) = ReadingEps::enter() else { return Some(vec![]) }; + #[cfg(any(test, feature = "work-count"))] + crate::INCLUDED_EPS_READS.with(|n| n.set(n.get() + 1)); + let warnings = vectorcraft_doc::placed_document::with_previews(|| { + crate::import_names(bytes, true, false, crate::NameEncoding::default()).ok().map(|r| r.warnings) + }); + EPS_CHECKS.with_borrow_mut(|c| { + if c.len() >= MAX_EPS_CHECKS { + c.remove(0); + } + c.push((key, warnings.clone())); + }); + warnings +} impl<'a> Reader<'a> { + /// Do the bytes `eps` of an included EPS file read ([`readable_eps`])? When they do, what reading + /// them warns of is a warning of this file's too. + fn read_included(&mut self, eps: &[u8]) -> bool { + let Some(warnings) = readable_eps(eps) else { return false }; + for w in warnings { + self.warn(&format!("a placed EPS file: {w}")); + } + true + } + /// A text object (`/AI11Text`): an empty group standing for it, named after its story. pub(super) fn text_slot(&mut self, o: &Obj) -> Result<(), String> { if self.pattern.is_some() { @@ -838,8 +909,9 @@ impl<'a> Reader<'a> { } /// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that - /// shows the preview the data keeps of it, as a linked image whose file is missing does. One - /// without a preview, a path or a matrix isn't read. + /// shows the preview the data keeps of it, as a linked image whose file is missing does. An EPS + /// file whose bytes the data includes becomes a placed document of them ([`Self::placed_eps`]). + /// One without a preview or those bytes, a path or a matrix isn't read. pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> { // Where a symbol's art puts a placed file's pixels isn't known. if self.symbol.is_some() { @@ -847,11 +919,43 @@ impl<'a> Reader<'a> { self.left_out_of_symbol(); return Ok(()); } + let mut deferred = None; let (m, b, path, png, w, h, folder) = match self.place.take() { Some(Place { broken: true, .. }) => { self.unreadable("placed files", hidden); return Ok(()); } + Some(Place { matrix: Some(m), bounds: Some(b), path, document: Some(eps), preview, folder, .. }) + // A file without a bounding box of its own has its art read on a page of another + // size, which the placed box can't be matched to. + // One named `.ai` or `.ait` is read with the artboard its header gives rather than + // its bounding box, so it isn't read either. Bytes that don't read as an EPS file + // leave it as a placed file without them: its preview, or an unread one. + if !path.is_empty() + && !ai_named(&path) + && is_postscript(&eps) + // A native document's artboard, rather than its bounding box, frames what the loader reads. + && !native_eps(&eps) + && crate::dcs::read(&eps).is_none() + && sane(b) + && b.width() > 0.0 + && b.height() > 0.0 + && eps_box(&eps).is_some() + && self.read_included(&eps) => + { + let Some((placed, blob)) = self.placed_eps(m, path.clone(), eps, folder.clone(), hidden) else { return Ok(()) }; + if let Some((png, w, h)) = preview { + // No image variable binds pattern or brush art, which a reader of its own + // reads: there the placed document goes in at once. + if self.pattern.is_some() { + return self.add_placed_eps(placed, blob, hidden); + } + deferred = Some((placed, blob)); + (m, b, path, png, w, h, folder) + } else { + return self.add_placed_eps(placed, blob, hidden); + } + } Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)), folder, .. }) if !path.is_empty() => { (m, b, path, png, w, h, folder) } @@ -902,6 +1006,10 @@ impl<'a> Reader<'a> { .filter(|a| a.as_coeffs().iter().all(|v| v.is_finite())); let xf = self.space() * m * over_file; if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + // An included EPS file is still read when its preview can't be placed. + if let Some((placed, blob)) = deferred { + return self.add_placed_eps(placed, blob, hidden); + } self.unreadable("placed files", hidden); return Ok(()); } @@ -911,7 +1019,11 @@ impl<'a> Reader<'a> { let key = linked_key(&blob, &path); let fresh = !self.doc.images.contains_key(&key); self.doc.images.entry(key.clone()).or_insert(blob); - self.warn(LINKED_PREVIEWS); + // An included EPS file shows its preview only when an image variable binds it, which the + // importer notes then. + if deferred.is_none() { + self.warn(LINKED_PREVIEWS); + } let id = NodeId(self.doc.peek_next_id()); if let Some(shift) = elsewhere && self.placed_elsewhere.len() < MAX_PLACED_ELSEWHERE @@ -928,7 +1040,11 @@ impl<'a> Reader<'a> { self.placed_tails.push(PlacedTail { id, key: key.clone(), size: (b.width(), b.height()), fresh, depth }); let mut link = LinkInfo::new(path); link.relative = folder.and_then(|f| relative_path(&f, link.name())); - self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden) + self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)?; + if let Some((placed, blob)) = deferred { + self.placed_eps.push(PlacedEps { id, placed, blob }); + } + Ok(()) } /// The dictionary `o` after the placed file just read: with a page or a box in it, that file is @@ -962,6 +1078,54 @@ impl<'a> Reader<'a> { self.placed_pages.push(PlacedPage { id: tail.id, page, bounding, page_box, size: tail.size }); } + /// The placed EPS file at `path` whose bytes `eps` the data includes, its box (in its own space, + /// y up: the bounding box its comments give, [`eps_box`], which its art is read in) taken into + /// art space by `m`: a placed document showing that box, which keeps the bytes and draws them + /// whether or not its file is found. Its link has the size and hash of those bytes, so a file + /// found unchanged isn't reported as modified. The placed document has no preview, so a save + /// keeps the bytes. Not read without that box. + fn placed_eps(&mut self, m: Affine, path: String, eps: Vec, folder: Option, hidden: bool) -> Option<(PlacedDocument, ImageBlob)> { + let Some(b) = eps_box(&eps) else { + self.unreadable("placed files", hidden); + return None; + }; + // The placed document's box runs down from the file's top left corner. + let xf = self.space() * m * Affine::new([1.0, 0.0, 0.0, -1.0, b.x0, b.y1]); + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + self.unreadable("placed files", hidden); + return None; + } + let hash = hash_bytes(&eps); + let key = key_for(&hash, 1, false, PageBox::Crop); + let mut link = LinkInfo::new(path); + link.relative = folder.and_then(|f| relative_path(&f, link.name())); + (link.page, link.size, link.hash) = (Some(1), u64::try_from(eps.len()).ok(), Some(hash)); + let blob = ImageBlob { mime: EPS_MIME.into(), bytes: Arc::new(eps), proxy: None, file_font: Default::default() }; + let placed = PlacedDocument { + link, + key, + bounding: false, + page_box: PageBox::Crop, + width: b.width(), + height: b.height(), + xf, + placement: Default::default(), + }; + Some((placed, blob)) + } + + /// `placed` ([`Self::placed_eps`]) added as an object, its bytes `blob` kept under its key. + /// Placements of the same bytes share one blob. + fn add_placed_eps(&mut self, placed: PlacedDocument, blob: ImageBlob, hidden: bool) -> Result<(), String> { + self.doc.images.entry(placed.key.clone()).or_insert(blob); + let gs = self.gs.clone(); + let mut node = self.new_node(NodeKind::PlacedDocument(Box::new(placed)), &gs); + node.opacity = gs.opacity; + node.blend = gs.blend; + node.knockout_shape = gs.knockout_shape; + self.add(node, hidden) + } + pub(super) fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) && self.warnings.len() < 64 { self.warnings.push(w.to_string()); @@ -1083,6 +1247,65 @@ fn placed_crop(v: f64) -> Option<(bool, PageBox)> { } } +/// The bytes of a placed file the data includes (`doc`: between the `%%BeginDocument:` line and +/// the `%%EndDocument` one), as the file has them: on `%_` lines (`hidden`) without the `%_` that +/// starts each line, then without a line end the data adds before `%%EndDocument` after the file's +/// own last one. A single line end at the end is the file's own. The line end added is `sep`, the +/// one the data ends its `%%BeginDocument:` line with, when the bytes end with it; otherwise the +/// last line end they end with. An LF `sep` after a CR isn't taken apart from it when the file's +/// first line ends with CRLF: that CRLF is one line end of the file's. +pub(super) fn included_document(doc: &[u8], hidden: bool, sep: Option<&[u8]>) -> Vec { + let mut out = if hidden { unhidden(doc) } else { doc.to_vec() }; + let eol = |b: &[u8]| b.ends_with(b"\r") || b.ends_with(b"\n"); + let first_eol = out.iter().position(|&b| b == b'\r' || b == b'\n').and_then(|i| out.get(i..i + 2)); + let crlf_file = first_eol == Some(b"\r\n") && out.ends_with(b"\r\n"); + let added = sep + .filter(|s| out.ends_with(s) && !(crlf_file && *s == b"\n")) + .or_else(|| [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| out.ends_with(e))) + .map(|e| out.len() - e.len()); + if let Some(n) = added.filter(|&n| out.get(..n).is_some_and(eol)) { + out.truncate(n); + } + out +} + +/// The bounding box an EPS file's comments give (`%%HiResBoundingBox` when it has one), in its +/// own space; `None` without one, or when it is empty or out of range. +fn eps_box(eps: &[u8]) -> Option { + let [x0, y0, x1, y1] = crate::import::bounding_box(eps)?; + Some(Rect::new(x0, y0, x1, y1)).filter(|r| sane(*r) && r.width() > 0.0 && r.height() > 0.0) +} + +/// Does `eps` have a native document's begin comment line, without reading that document? +fn native_eps(eps: &[u8]) -> bool { + eps.split(|b| *b == b'\r' || *b == b'\n') + .any(|line| line.strip_prefix(crate::BEGIN_DATA.as_bytes()).is_some_and(|name| name.trim_ascii() == crate::NATIVE.as_bytes())) +} + +/// Does the file name at the end of `path` (`/` or `\` separators) end in `.ai` or `.ait`, any case? +fn ai_named(path: &str) -> bool { + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + name.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("ai") || ext.eq_ignore_ascii_case("ait")) +} + +/// `doc` without the `%_` that starts each of its lines. +fn unhidden(doc: &[u8]) -> Vec { + let mut out = Vec::with_capacity(doc.len()); + let mut line_start = true; + let mut i = 0; + while let Some(&b) = doc.get(i) { + if line_start && doc.get(i..i + 2) == Some(b"%_") { + i += 2; + line_start = false; + continue; + } + out.push(b); + line_start = b == b'\r' || b == b'\n'; + i += 1; + } + out +} + /// A placed file's path relative to the document's folder (`/` separators): its relative `folder` /// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the /// document's own folder). `None` when the folder is absolute or holds control characters, or @@ -1155,3 +1378,36 @@ pub(crate) fn join_and(items: &[&str]) -> String { [rest @ .., last] => format!("{} and {last}", rest.join(", ")), } } + +#[cfg(test)] +mod tests { + use super::{ReadingEps, readable_eps}; + + /// Check results keep their warnings and failures, respect depth, and expire with the outer check. + #[test] + fn included_eps_checks_keep_the_depth_limit_and_expire() { + let eps = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor 0 0 60 60 rectfill nosuchoperator\n%%EOF\n"; + { + let _outer = ReadingEps::enter().unwrap(); + let warnings = readable_eps(eps).unwrap(); + assert!(!warnings.is_empty(), "a partly read file still passes, with warnings"); + let reads = crate::included_eps_reads(); + assert_eq!(readable_eps(eps).unwrap(), warnings); + assert_eq!(crate::included_eps_reads(), reads, "the repeated check did not parse again"); + let limits: Vec<_> = std::iter::from_fn(ReadingEps::enter).collect(); + assert!(!limits.is_empty()); + assert!(readable_eps(eps).unwrap().is_empty(), "past the depth limit, warnings are not read"); + drop(limits); + assert_eq!(readable_eps(eps).unwrap(), warnings, "the deeper check did not replace the cached warnings"); + let broken = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + assert!(readable_eps(broken).is_none()); + let reads = crate::included_eps_reads(); + assert!(readable_eps(broken).is_none()); + assert_eq!(crate::included_eps_reads(), reads, "a repeated failed check did not parse again"); + } + let _outer = ReadingEps::enter().unwrap(); + let reads = crate::included_eps_reads(); + assert!(readable_eps(eps).is_some()); + assert!(crate::included_eps_reads() > reads, "the outer check's results were discarded"); + } +} diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 8492cca6f0..e63e670b7f 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1441,6 +1441,7 @@ impl<'a> Reader<'a> { placeholders: self.placeholders, placed_elsewhere: self.placed_elsewhere, placed_pages: self.placed_pages, + placed_eps: self.placed_eps, envelopes_drawn: self.envelopes_drawn, warped_type: super::super::envelope::WarpedType { looks: self.warped_type, diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index a155d9f505..27eb8a8576 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -312,6 +312,9 @@ pub(super) struct Place { pub(super) folder: Option, /// The operand stack's height at `%AI28_BeginPlacedRelativePath`, until its end. pub(super) folder_at: Option, + /// The file's bytes, when the data includes them between `%%BeginDocument:` and + /// `%%EndDocument` (at most [`MAX_PLACED_DOCUMENT`]). + pub(super) document: Option>, /// Its `` ` `` was read. pub(super) ticked: bool, /// It began on a `%_` line, in a hidden object or on a layer that doesn't show. @@ -361,8 +364,26 @@ pub struct PlacedPage { pub size: (f64, f64), } +/// An included EPS whose linked preview becomes a placed document after variable binding. +#[derive(Debug)] +pub struct PlacedEps { + /// The linked image. + pub id: NodeId, + /// The document that replaces the image unless an image variable binds it. + pub placed: vectorcraft_doc::PlacedDocument, + /// The EPS bytes stored under the placed document's key only when it replaces the image. + pub blob: vectorcraft_doc::ImageBlob, +} + +/// The largest placed file kept from the bytes the data includes (the largest file File › Place +/// reads). +pub(super) const MAX_PLACED_DOCUMENT: usize = 256 << 20; + +/// The type a placed EPS file's bytes are stored with. +pub(super) const EPS_MIME: &str = "application/postscript"; + /// What the open result says of placed files: they show the preview the file keeps of them. -pub(super) const LINKED_PREVIEWS: &str = +pub(crate) const LINKED_PREVIEWS: &str = "linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel"; /// What the open result says of linked images the data keeps no pixels of (`XF`): they show a diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 242d433b7b..b4d56c9e08 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -12,7 +12,9 @@ use super::*; /// [`super::read`] as an EPS reads it. fn read(data: &[u8]) -> Result { - super::read(data, true) + let mut r = super::read(data, true)?; + super::super::native::placed_documents(&mut r.doc, &[], &r.placed_eps); + Ok(r) } /// Editing data: header comments (crop marks 0 0 200 100), then `body`. @@ -3495,6 +3497,178 @@ fn a_placed_file_keeps_its_folder_relative_to_the_document() { assert_eq!(relative_of(&cut), None); } +/// An EPS file of `w` × `h` points filled red, its lines ended by `eol`. +fn red_eps(w: u32, h: u32, eol: &str) -> Vec { + format!("%!PS-Adobe-3.0 EPSF-3.0{eol}%%BoundingBox: 0 0 {w} {h}{eol}%%EndComments{eol}1 0 0 setrgbcolor{eol}0 0 {w} {h} rectfill{eol}%%EOF{eol}") + .into_bytes() +} + +/// `data` with the first `from` in it replaced by `to`. +fn splice(data: &[u8], from: &[u8], to: &[u8]) -> Vec { + let at = data.windows(from.len()).position(|w| w == from).unwrap(); + [&data[..at], to, &data[at + from.len()..]].concat() +} + +/// [`placed`]'s file with the placed file `/old/place/src/shape.eps` in the box 0 0 80 50, in the +/// folder `src/`, without a preview, and `doc` included between `%%BeginDocument:` and +/// `%%EndDocument` in place of `%%IncludeFile:` (`%%FileType: 0`). +fn placed_eps_file(doc: &[u8]) -> Vec { + let data = placed(true, "[5 0 0 -5 0 200]", "/old/place/src/shape.eps", None, ""); + let data = splice(&data, b"10 20 14 22 4 4 0", b"0 0 80 50 4 4 0"); + let data = splice(&data, b"\r()\r", b"\r(src/)\r"); + let data = splice(&data, b"%%FileType: 1", b"%%FileType: 0"); + let included = [&b"%%BeginDocument: /old/place/src/shape.eps\r"[..], doc, b"\r%%EndDocument\r"].concat(); + splice(&data, b"%%IncludeFile:/old/place/src/shape.eps\r", &included) +} + +/// The one placed document of `data`, with the blob its key names. +fn one_placed(data: &[u8]) -> (Node, vectorcraft_doc::PlacedDocument, vectorcraft_doc::ImageBlob, Structure) { + let r = read(data).unwrap(); + let a = art(&r.doc); + let [n] = &a[..] else { panic!("one object: {a:?}") }; + let NodeKind::PlacedDocument(p) = &n.kind else { panic!("a placed document: {:?}", n.kind) }; + let blob = r.doc.images[&p.key].clone(); + ((**n).clone(), (**p).clone(), blob, r) +} + +#[test] +fn a_placed_eps_file_whose_bytes_the_data_includes_is_a_placed_document_of_them() { + let eps = red_eps(80, 50, "\n"); + let (_, p, blob, r) = one_placed(&placed_eps_file(&eps)); + assert_eq!(*blob.bytes, eps, "the file's own bytes, without the line end the data adds"); + assert_eq!((blob.mime.as_str(), blob.proxy.is_none()), ("application/postscript", true)); + assert_eq!((p.link.path.as_str(), p.link.relative.as_deref()), ("/old/place/src/shape.eps", Some("src/shape.eps"))); + assert_eq!((p.link.page, p.link.size, p.link.hash.clone()), (Some(1), Some(eps.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&eps)))); + assert_eq!((p.width, p.height, p.bounding, p.page_box), (80.0, 50.0, false, vectorcraft_doc::PageBox::Crop)); + assert!(r.unread.is_empty() && r.hidden_unread.is_empty() && r.unread_elsewhere.is_empty(), "{:?}", r.unread); + assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{:?}", r.warnings); + // The matrix takes the file's own space (y up) into art space; the box's top left corner is the + // file's (0, 50). + let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]); + for (corner, file) in [((0.0, 0.0), (0.0, 50.0)), ((80.0, 50.0), (80.0, 0.0)), ((80.0, 0.0), (80.0, 50.0))] { + let (got, want) = (p.xf * Point::from(corner), r.to_doc * m * Point::from(file)); + assert!((got - want).hypot() < 1e-9, "{corner:?}: {got:?} {want:?}"); + } +} + +#[test] +fn a_placed_eps_file_with_included_bytes_and_a_preview_keeps_only_the_bytes() { + let eps = red_eps(80, 50, "\n"); + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let section = + [&b"%AI17_Begin_Content_if_version_gt:24 5\r%AI26_BeginPlacedObjectPreview\r"[..], &preview, b"\r%AI26_EndPlacedObjectPreview\r"].concat(); + let data = splice(&placed_eps_file(&eps), b"%AI17_Begin_Content_if_version_gt:24 5\r", §ion); + // The placed document has no preview, so a save keeps its bytes. + let (_, _, blob, _) = one_placed(&data); + assert_eq!((&*blob.bytes, blob.proxy.is_none()), (&eps, true)); + // The same bytes placed twice share the blob. + let one = placed_eps_file(&eps); + let (from, to) = (|d: &[u8], w: &[u8]| d.windows(w.len()).position(|x| x == w).unwrap(), b"%AI5_EndPlace\r"); + let first = &one[from(&one, b"%AI5_BeginPlace")..from(&one, to) + to.len()]; + let twice = splice(&data, b"%AI5_BeginPlace", &[first, b"%AI5_BeginPlace"].concat()); + let r = read(&twice).unwrap(); + let a = art(&r.doc); + let keys: Vec<_> = a.iter().filter_map(|n| if let NodeKind::PlacedDocument(p) = &n.kind { Some(p.key.clone()) } else { None }).collect(); + assert!(keys.len() == 2 && keys[0] == keys[1], "{keys:?}"); + assert!(r.doc.images[&keys[0]].proxy.is_none()); +} + +#[test] +fn a_placed_eps_files_box_is_its_high_resolution_bounding_box() { + let eps = splice(&red_eps(80, 50, "\n"), b"%%EndComments", b"%%HiResBoundingBox: 0.5 0.5 79.5 49.5\n%%EndComments"); + let (_, p, _, r) = one_placed(&placed_eps_file(&eps)); + assert_eq!((p.width, p.height), (79.0, 49.0)); + // The box's top left corner is the file's (0.5, 49.5), where the matrix puts it. + let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]); + let (got, want) = (p.xf * Point::ZERO, r.to_doc * m * Point::new(0.5, 49.5)); + assert!((got - want).hypot() < 1e-9, "{got:?} {want:?}"); +} + +#[test] +fn a_placed_eps_files_box_with_its_corners_reversed_leaves_it_unread() { + let data = splice(&placed_eps_file(&red_eps(80, 50, "\n")), b"0 0 80 50 4 4 0", b"80 50 0 0 4 4 0"); + let r = read(&data).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc)); +} + +#[test] +fn an_included_eps_files_own_last_line_end_is_kept() { + // The data's line end after the file's own is taken off; a single one is the file's. + let (lf, crlf) = ("%!PS\n%%BoundingBox: 0 0 80 50\n%%EOF\n", "%!PS\r\n%%BoundingBox: 0 0 80 50\r\n%%EOF\r\n"); + for (eps, written) in [(lf, format!("{lf}\r")), (lf, lf.to_string()), (crlf, format!("{crlf}\r\n"))] { + let data = splice(&placed_eps_file(b"%!@@"), b"%!@@\r%%EndDocument", format!("{written}%%EndDocument").as_bytes()); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), eps, "{written:?}"); + } + // The line end added is the one the `%%BeginDocument:` line ends with: an LF after a file whose + // lines end with CR isn't read as a CRLF of the file's. + let data = + splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", b"shape.eps\n%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r\n%%EndDocument"); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), "%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r"); + // A file whose lines end with CRLF, included as it is after an LF: its last CRLF is its own. + let data = splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", format!("shape.eps\n{crlf}%%EndDocument").as_bytes()); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), crlf); +} + +#[test] +fn a_placed_eps_file_on_commented_lines_keeps_its_bytes() { + let eps = red_eps(80, 50, "\r"); + let hidden = hide_placed(&placed_eps_file(&eps)); + let (_, _, blob, _) = one_placed(&hidden); + assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the `%_` that starts each line taken off"); + // The line end added before `%%EndDocument` on a `%_` line of its own. + let (_, _, blob, _) = one_placed(&splice(&hidden, b"%%EOF\r\r%_%%EndDocument", b"%%EOF\r%_\r%_%%EndDocument")); + assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the added line end taken off"); +} + +#[test] +fn an_included_postscript_file_named_as_an_ai_file_stays_unread() { + // Read through its name with the artboard its header gives, not the box the placed one shows. + for name in ["shape.ai", "SHAPE.AIT"] { + let mut data = placed_eps_file(&red_eps(80, 50, "\n")); + while data.windows(9).any(|w| w == b"shape.eps") { + data = splice(&data, b"shape.eps", name.as_bytes()); + } + let r = read(&data).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{name}: {:?}", art(&r.doc)); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{name}: {:?}", r.unread); + } +} + +#[test] +fn included_eps_with_a_native_document_leaves_the_placed_file_unread() { + // Even unreadable native data leaves the file unread: the loader can read an artboard + // larger than the EPS bounding box, which would shrink and offset the art when placed. + for eol in ["\n", "\r", "\r\n"] { + let section = format!("%VectorCraft_BeginData: native \t{eol}%unreadable native data{eol}%VectorCraft_EndData{eol}%%EOF"); + let eps = splice(&red_eps(80, 50, eol), b"%%EOF", section.as_bytes()); + let r = read(&placed_eps_file(&eps)).unwrap(); + assert!( + !art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), + "included EPS with a native document must stay on the fallback path" + ); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread); + } +} + +#[test] +fn included_bytes_that_arent_an_eps_file_leave_the_placed_file_unread() { + // A DCS file, which the placed document reader doesn't read (File › Place makes it a linked + // image), stays unread too. + let dcs = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%PlateFile: (Black) EPS Local pic.K\n%%EndComments\n%%EOF\n"; + // An EPS file without a bounding box, whose art is read on a page of another size, stays unread. + let boxless = b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n1 0 0 setrgbcolor\n0 0 80 50 rectfill\n%%EOF\n"; + // An EPS file whose program doesn't read draws nothing, so it stays unread too. + let broken = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 80 50\n%%EndComments\n0 0 80 50 nosuchoperator\n%%EOF\n"; + for bytes in [&b"hello\rworld"[..], dcs, boxless, broken] { + let r = read(&placed_eps_file(bytes)).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc)); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread); + } +} + #[test] fn hidden_placed_file_ended_by_comment_stays_hidden() { let mut data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", None, "")); @@ -3588,6 +3762,7 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> { NodeKind::Group { .. } => "group", NodeKind::Path { .. } => "path", NodeKind::Image(_) => "image", + NodeKind::PlacedDocument(_) => "placed", _ => "other", }) .collect() @@ -3596,13 +3771,16 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> { #[test] fn version7_placed_file_included_whole_is_read() { // The included document's operators, a `~`, a nested document and counted data in it aren't - // the editing data's. - let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor frobnicate ~\n\ + // the editing data's (the file defines them, so its program reads). + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n/frobnicate {} def /~ {} def\n1 0 0 setrgbcolor frobnicate ~\n\ %%BeginDocument: inner.eps\n~\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n"; let body = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n"); let r = placed_read7(true, &body).unwrap(); - assert_eq!(art_kinds(&r.doc), ["path"]); - assert_unread(&r, "placed files"); + // A placed document of the file's bytes. + assert_eq!(art_kinds(&r.doc), ["placed"]); + let NodeKind::PlacedDocument(p) = &art(&r.doc)[0].kind else { panic!() }; + assert_eq!(r.doc.images[&p.key].bytes.as_slice(), eps.as_bytes()); + assert!(r.unread.is_empty(), "{:?}", r.unread); // One that doesn't end leaves the layer without its end. let cut = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}~\n"); assert!(placed_read7(true, &cut).is_err()); diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index dad13c569f..df97114506 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -50,6 +50,8 @@ mod slots; #[cfg(test)] pub(crate) use build::READ_AFRESH; #[cfg(test)] +pub(super) use build::placed_documents; +#[cfg(test)] use build::{Frame, MADE, prune_unseen}; pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols}; #[cfg(test)] diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 1ef5706e68..d5d7dbc1c8 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -334,6 +334,7 @@ pub(super) fn build_weighing( placeholders, placed_elsewhere, placed_pages, + placed_eps, envelopes_drawn, styles_read, text_paints, @@ -644,33 +645,50 @@ pub(super) fn build_weighing( } doc.limit_depth_noting(&mut notes); bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); - placed_documents(&mut doc, &placed_pages); + if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) { + notes.push(ai::LINKED_PREVIEWS.to_string()); + } if small.is_some() { scale_read_document(&mut doc, unit, styles_read, symbols_own_size); } Ok((doc, notes)) } -/// The linked images of `pages` that are still in `doc`, opacity-mask art included, as placed -/// documents of their page and box, over the same place, each showing the same preview until its -/// file is read. An image bound to an image variable stays a linked image, the object an image -/// variable binds. -fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage]) { - if pages.is_empty() { - return; +/// The linked images of `pages` and included `eps` still in `doc`, opacity-mask art included, as placed +/// documents of their page and box. PDF pages keep their previews, and EPS files keep their included +/// bytes. An image bound to an image variable stays a linked image, the object an image variable binds. +/// Returns whether an included EPS file stays a linked image that way, showing its preview. +pub(in crate::import) fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage], eps: &[ai::PlacedEps]) -> bool { + if pages.is_empty() && eps.is_empty() { + return false; } let vars = &doc.variables; let image_bound = |id: &NodeId| { vars.bindings.get(id).is_some_and(|names| names.iter().any(|v| vars.variable(v).is_some_and(|v| v.kind == VariableKind::Image))) }; let pages: std::collections::HashMap = pages.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, *p)).collect(); + let previews = eps.iter().any(|p| image_bound(&p.id)); + let eps: std::collections::HashMap = eps.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, p)).collect(); for layer in &mut doc.layers { - to_placed_documents(Arc::make_mut(layer), &pages); + to_placed_documents(Arc::make_mut(layer), &pages, &eps, &mut doc.images); } + previews } /// [`placed_documents`] in `n` and everything in it. -fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap) { +fn to_placed_documents( + n: &mut Node, + pages: &std::collections::HashMap, + eps: &std::collections::HashMap, + images: &mut std::collections::BTreeMap, +) { + if let Some(eps) = eps.get(&n.id) + && let NodeKind::Image(im) = &n.kind + && im.link.is_some() + { + images.entry(eps.placed.key.clone()).or_insert_with(|| eps.blob.clone()); + n.kind = NodeKind::PlacedDocument(Box::new(eps.placed.clone())); + } // A box too small to take the image's pixels to (its transform not finite) keeps the linked image. if let Some(page) = pages.get(&n.id) && let NodeKind::Image(im) = &n.kind @@ -694,10 +712,10 @@ fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap>], doc: &Document, placed: &[(N } /// Where the placed files that show in `nodes` are: the linked images the editing data's reader -/// makes of them. +/// makes of them, and the placed documents it makes of the EPS files whose bytes it includes. fn placed_files(nodes: &[Arc], out: &mut Vec) { for n in nodes.iter().filter(|n| n.visible) { match &n.kind { NodeKind::Image(im) if im.link.is_some() => out.extend(n.visual_bounds()), + NodeKind::PlacedDocument(_) => out.extend(n.visual_bounds()), _ => { if let Some(c) = n.children() { placed_files(c, out); diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index 4cae36ac52..2cbcde3551 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -56,6 +56,19 @@ fn tree(nodes: &[Arc]) -> String { nodes.iter().map(one).collect::>().join(" ") } +/// Placed EPS files drawn as the app draws them: the art of the file read as it opens, in its +/// bounding box (the engine registers the app's own loader). +fn draw_placed_eps() { + fn load(_: &vectorcraft_doc::PlacedDocument, bytes: &[u8]) -> Option<(vectorcraft_doc::Document, Node, Rect)> { + let mut doc = import(bytes).ok()?.document; + let frame = doc.artboards.first()?.rect; + let layers = std::mem::take(&mut doc.layers); + let children = layers.iter().flat_map(|l| l.children().map(|c| c.to_vec()).unwrap_or_default()).collect(); + Some((doc, Node::new(vectorcraft_doc::NodeId(0), NodeKind::Group { children, clip: false }), frame)) + } + vectorcraft_doc::placed_document::set_loader(load); +} + fn read(header: &str, ugroup: &str, body: &str) -> (String, Vec) { let r = import(&ai(header, ugroup, body)).unwrap(); (tree(r.document.layers[0].children().unwrap()), r.warnings) @@ -424,9 +437,10 @@ fn a_postscript_ai_with_a_template_box_and_no_art_size_opens_on_a_letter_artboar } /// A placed EPS in the legacy format (version 7 specification §16, no `%AI5_BeginPlace`), its file -/// included whole: the layers come in, the placed file as the art the page draws in its box. +/// included whole: the layers come in, the placed file as a placed document of its bytes in its box. #[test] fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() { + draw_placed_eps(); // `` ` `` takes the file's user space into the page's (`concat`); `~` restores it. let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\ /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; @@ -440,14 +454,35 @@ fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() { let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); assert_eq!(names, ["Back"], "{:?}", r.warnings); let art = r.document.layers[0].children().unwrap(); - assert_eq!(tree(art), "p g[p]", "{:?}", r.warnings); + let NodeKind::PlacedDocument(p) = &art[1].kind else { panic!("{}: {:?}", tree(art), r.warnings) }; + assert_eq!(r.document.images[&p.key].bytes.as_slice(), eps.as_bytes(), "the file's bytes"); + assert_eq!(p.link.path, "art.eps"); // The file's box, moved by the matrix: 20 40 60 70 on the page, y up. let bounds = art[1].geometric_bounds().unwrap(); assert!( (bounds.x0 - 20.0).abs() < 0.01 && (bounds.y0 - 30.0).abs() < 0.01 && (bounds.x1 - 60.0).abs() < 0.01 && (bounds.y1 - 60.0).abs() < 0.01, "{bounds:?}" ); - assert!(r.warnings.iter().any(|w| w.contains("placed files")), "{:?}", r.warnings); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// A legacy file whose placed EPS file, included whole, has type: the page's type is the placed +/// file's, so the layers come in with it as a placed document. +#[test] +fn a_legacy_file_with_a_placed_eps_with_type_comes_in_through_its_layers() { + draw_placed_eps(); + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\ + /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\ + /Helvetica findfont 12 scalefont setfont 15 30 moveto (Hi) show\n%%EOF\n"; + let placed = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n"); + let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{} {placed}LB\n%AI5_EndLayer--\n", tri(10)); + let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog")); + let r = import(file.as_bytes()).unwrap(); + let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Back"], "{:?}", r.warnings); + let art = r.document.layers[0].children().unwrap(); + assert!(matches!(art[1].kind, NodeKind::PlacedDocument(_)), "{}: {:?}", tree(art), r.warnings); } /// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 0d69d248e5..e55d2fe4da 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8358,6 +8358,119 @@ fn a_placed_pdf_page_bound_to_an_image_variable_stays_a_linked_image() { assert_eq!(d.variables.objects_of("v_file"), [n.id], "{notes:?}"); } +/// An included EPS keeps its linked preview and binding when an image variable binds it. +#[test] +fn a_placed_eps_with_a_preview_preserves_its_image_variable_binding() { + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_node}; + let declared = vec![xml_node( + 1, + "variable", + XmlValue::Str(""), + &[("trait", XmlValue::Str("fileref")), ("varName", XmlValue::Unicode("v_file")), ("docRef", XmlValue::Raw("/XMLUIDREF : (eps) ;"))], + &[], + )]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n"; + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\ + %%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n\ + %AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n~\n%AI5_EndPlace\n\ + %_/ArtDictionary :\n%_/XMLUID : (eps) ; (AI10_ArtUID) ,\n%_;\n%_\n", + "\x7f\0\0\0".repeat(4) + ); + let art = layer("Jig", true, &place); + let (bound, notes) = crate::ai_alone(&private(&native(&(library + &art)))).unwrap(); + let n = &bound.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) }; + assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps"); + assert_eq!((im.width, im.height), (2, 2)); + assert_eq!(bound.images[&im.key].mime, "image/png"); + assert!(bound.images.values().all(|b| b.mime != "application/postscript")); + assert_eq!(bound.variables.objects_of("v_file"), [n.id], "{notes:?}"); + assert!(!notes.iter().any(|n| n.contains("variable bindings")), "{notes:?}"); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "the preview it shows is noted: {notes:?}"); + let (unbound, notes) = crate::ai_alone(&private(&native(&art))).unwrap(); + assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "it draws its bytes: {notes:?}"); + let converted = &unbound.layers[0].children().unwrap()[0]; + assert_eq!(converted.id, n.id); + let NodeKind::PlacedDocument(p) = &converted.kind else { panic!("{:?} {notes:?}", converted.kind) }; + assert_eq!(&*unbound.images[&p.key].bytes, eps.as_bytes()); + assert!(unbound.images[&p.key].proxy.is_none()); +} + +/// What reading an included EPS file warns of, such as art left out, is in the open result. +#[test] +fn a_placed_eps_read_in_part_warns_of_what_it_leaves_out() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 30 30 rectfill\n0 0 60 60 nosuchoperator\n%%EOF\n"; + let own = crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).unwrap().warnings; + assert!(!own.is_empty(), "the file read alone warns"); + for place in [placed_eps_with_preview(eps), placed_eps_with_preview(eps).replace(&placed_eps_preview(), "")] { + let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap(); + let n = &d.layers[0].children().unwrap()[0]; + assert!(matches!(n.kind, NodeKind::PlacedDocument(_)), "{:?} {notes:?}", n.kind); + for w in &own { + assert!(notes.contains(&format!("a placed EPS file: {w}")), "{w}: {notes:?}"); + } + } +} + +/// An unreadable included EPS keeps the preview that the linked image can show. +#[test] +fn a_placed_eps_with_an_unreadable_program_keeps_its_preview() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + assert!(crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).is_err()); + let place = placed_eps_with_preview(eps); + let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap(); + let n = &d.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) }; + assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps"); + assert_eq!((im.width, im.height), (2, 2)); + let preview = &d.images[&im.key]; + assert_eq!(preview.mime, "image/png"); + assert_eq!(preview.proxy.as_deref(), Some(&*preview.bytes)); + assert!(d.images.values().all(|b| b.mime != "application/postscript")); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); +} + +/// A pattern's included EPS keeps its bytes without waiting for image variable binding. +#[test] +fn a_placed_eps_with_a_preview_in_a_pattern_keeps_its_bytes() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n"; + let place = placed_eps_with_preview(eps); + let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{place}E\n%AI3_EndPattern\n"); + let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap(); + let art = &d.pattern("Pic").unwrap().art; + assert_eq!(art.len(), 1, "{art:?} {notes:?}"); + let NodeKind::PlacedDocument(p) = &art[0].kind else { panic!("{art:?} {notes:?}") }; + assert_eq!(&*d.images[&p.key].bytes, eps.as_bytes()); + assert_eq!(d.images[&p.key].mime, "application/postscript"); + assert!(d.images[&p.key].proxy.is_none()); + assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); + + // One whose bytes can't be read keeps its preview there too. + let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 nosuchoperator\n%%EOF\n"; + let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{}E\n%AI3_EndPattern\n", placed_eps_with_preview(broken)); + let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap(); + let art = &d.pattern("Pic").unwrap().art; + assert!(matches!(&art[..], [n] if matches!(&n.kind, NodeKind::Image(im) if im.link.is_some())), "{art:?} {notes:?}"); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); +} + +/// A placed EPS file at `/files/shape.eps` whose bytes `eps` the data includes, with a 2 × 2 preview. +fn placed_eps_with_preview(eps: &str) -> String { + format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\ + %%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n{}~\n%AI5_EndPlace\n", + placed_eps_preview() + ) +} + +/// The 2 × 2 preview of [`placed_eps_with_preview`]. +fn placed_eps_preview() -> String { + format!("%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n", "\x7f\0\0\0".repeat(4)) +} + #[test] fn a_small_placed_file_goes_where_it_draws_closer_to_the_page() { // A 2 × 2 placed file (a small logo on a large page) whose box corner the matrix takes to diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 6f5ff3d7a2..1abfd0210e 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -61,6 +61,18 @@ pub use print::{PrintFonts, PrintJob, PrintPage, print}; use vectorcraft_doc::Document; use vectorcraft_geom::{Point, Rect}; +#[cfg(any(test, feature = "work-count"))] +std::thread_local! { + /// Included EPS files parsed by open checks on this thread. + pub(crate) static INCLUDED_EPS_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Included EPS files parsed by open checks on this thread, for tests that count work instead of timing it. +#[cfg(any(test, feature = "work-count"))] +pub fn included_eps_reads() -> usize { + INCLUDED_EPS_READS.with(std::cell::Cell::get) +} + /// The PostScript language level the file needs. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] pub enum Level { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8f9868203d..bc7a0f541a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2436,6 +2436,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). + A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). In a `.ai` or EPS opened from its editing data, and in a legacy `.ai`, each anchor is smooth or a corner as the case of the segment operator ending on it says (`l`, `c`, `v`, `y` smooth; `L`, `C`, `V`, `Y` corner), and a closed path's first anchor takes the case of the segment back to it; points and handles stay where they are. Paths, compound paths, clipping paths, guide paths, area type frames and type-on-a-path paths all keep it (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/legacy_ai/tests.rs`). In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From 789fbb69943ed5300b6e2b596a6a2b23ce95ffdb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:26:44 -0800 Subject: [PATCH 32/42] Tests: run the profile-assigning status bar and Assign rows tests in their own process Assigning a profile to the front document changes the process's active color settings (`cms::active`). The status bar readout test assigned ProPhoto RGB, and the Separations Preview Assign rows test assigned other RGB and CMYK profiles, in the shared test process. A test that converted a color while either profile was active got that profile's values: under plain `cargo test`, `an_artboard_shows_its_background_color_live` read sRGB red as #b3461a, its ProPhoto RGB value. Both tests now start with `testing::in_own_process`, as the crate's other tests that assign profiles or change Color Settings do, and that helper's doc names these cases. --- crates/ui-egui/src/chrome/tests.rs | 4 ++++ crates/ui-egui/src/panels/separations.rs | 4 ++++ crates/ui-egui/src/testing.rs | 7 +++++-- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 9dbf91b4e7..0caf6ca592 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -772,6 +772,10 @@ fn current_tool_names_the_selection_tool_cmd_lends() { /// color profile. #[test] fn the_status_bar_info_field_shows_the_chosen_readout() { + // Assigning a profile to the front document changes the process's active color settings. + if !crate::testing::in_own_process("chrome::tests::the_status_bar_info_field_shows_the_chosen_readout") { + return; + } let mut bar = status_readout_app(); let texts = status_readout_frame(&mut bar); assert!(texts.iter().any(|t| t.text == "Selection"), "Current Tool by default: {texts:?}"); diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 53961fb0ab..96d558186a 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -546,6 +546,10 @@ mod tests { /// model's profile stays as it was. #[test] fn assign_rows_follow_the_document_color_mode() { + // Assigning a profile to the front document changes the process's active color settings. + if !crate::testing::in_own_process("panels::separations::tests::assign_rows_follow_the_document_color_mode") { + return; + } let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({})).unwrap(); for (mode, key, kind, other) in [("rgb", "rgb", ProfileKind::Rgb, "cmyk"), ("cmyk", "cmyk", ProfileKind::Cmyk, "rgb")] { diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index 1af93e507d..3650c423f8 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -94,8 +94,11 @@ pub(crate) fn custom_dictionary() -> std::sync::MutexGuard<'static, ()> { /// Runs the test `name` (its path in the crate, such as `canvas::tests::a_test`) alone in a child test process, for a /// test that loads or removes a color profile. The loaded profiles are the whole process's, and the canvas's frame key /// holds their generation ([`vectorcraft_color::cms::profiles_generation`]), so a profile loaded in this process while -/// another test renders changes that test's keys. In the child it returns `true`, and the test goes on. Here it waits -/// for the child, fails when the child's test fails, and returns `false`. +/// another test renders changes that test's keys. A test that assigns a profile to its front document, or changes +/// Color Settings, also runs here: the active color settings ([`vectorcraft_color::cms::active`]) are the whole +/// process's too, and another test converting a color while they are changed gets that profile's values. In the child +/// it returns `true`, and the test goes on. Here it waits for the child, fails when the child's test fails, and returns +/// `false`. pub(crate) fn in_own_process(name: &str) -> bool { const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS"; if std::env::var_os(CHILD).is_some_and(|v| v == name) { From bc8934569df87d0c2abbae648bc381a29941611c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:39:31 -0800 Subject: [PATCH 33/42] Batch: Escape in the Play, Destination and File Name lists keeps the earlier choice The Batch dialog's lists wrote the row the arrow keys highlighted into the dialog's fields. Escape closed the list but kept that row, and OK then ran the batch with it. The lists now bind to the fields, so Escape restores the earlier choice and only a committed choice applies, as New Action and Action Options do since #9730. --- crates/ui-egui/src/dialogs/action_batch.rs | 43 ++++++++++++++++++++-- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 4b2b79a02d..6e29fc182f 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -307,9 +307,7 @@ impl ActionDialog for BatchDialog { /// A row that picks one of `entries` for `value`. fn select_row(ui: &mut Ui, name: &str, value: &mut T, entries: &[Entry]) { Field::new(label(name)).show(ui, |ui, _| { - if let Some(picked) = Select::new(label(name), Bind::given(*value), entries).show(ui).value().copied() { - *value = picked; - } + Select::new(label(name), Bind::bound(value), entries).show(ui); }); } @@ -417,10 +415,13 @@ impl StackDialog for BatchDialog { #[cfg(test)] mod tests { use craft::automation::actions::{Action, ActionStep}; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; use vectorcraft_engine::Session; use super::*; use crate::dialogs::actions::pump; + use crate::tests::panel_harness::Panel; /// An app with one set holding `steps` as the action "Draw", and a window to show dialogs in. fn app_with(steps: Vec) -> VectorcraftApp { @@ -498,6 +499,42 @@ mod tests { assert!(!app.session.replaying()); } + #[test] + fn canceled_choices_keep_the_batch_source_destination_and_file_name() { + let mut app = app_with(vec![ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))]); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("dataset.new", json!({"name": "a"})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + open(&mut panel.app(), 0, 0).unwrap(); + set_fields(&panel.app(), &[("source", json!("datasets"))]); + panel.frame(); + let fields = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().fields().clone()); + let is_open = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.is_open::()); + let original = fields(&panel); + for (name, key) in [("Play", Key::ArrowUp), ("Destination", Key::ArrowUp), ("File Name", Key::ArrowDown)] { + panel.click_role(name, Role::COMBO_BOX); + panel.key(key, Modifiers::NONE); + assert_ne!(fields(&panel), original, "the popup previews {name}"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel), "Escape closes only the {name} popup"); + assert_eq!(fields(&panel), original, "Escape restores {name}"); + } + panel.click_role("Destination", Role::COMBO_BOX); + panel.key(Key::Home, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + let chosen = fields(&panel); + assert_eq!((chosen.source, chosen.destination), (BatchSource::DataSets, BatchDestination::None)); + panel.click("OK"); + panel.frame(); + panel.frame(); + assert!(!is_open(&panel)); + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 1); + assert!(!app.session.replaying()); + } + #[test] fn data_set_naming_params_follow_dialog_choice() { let mut fields = BatchFields::default(); From 7d5794d0e4f88c72893605c90dabc2e2dbe80b29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:29:20 -0800 Subject: [PATCH 34/42] .ai import: envelopes and warped art spend a difference budget on each page Live envelopes, warped type and warped images were held to one shared difference budget measured only on the first artboard. A file whose PDF part shows a later artboard, a page cropped to the art, or more than one artboard could then take more difference on that page than the page check allows, and open from its PDF part instead of its layers. Each page the art may be compared with (every artboard, and the art's bounding box when it is not one of them) now has its own half share of the page check's allowance. An envelope on a later artboard that draws away from its drawn art over that artboard's page keeps its drawn art, where before it opened live. Art on no such page is not held to a page. Repeated pages are held once, the page list is worked out once per change of artboards, and an import makes at most 1,024 comparisons with pages; art that needs more keeps its drawn art. --- crates/eps/src/import/ai/envelope.rs | 119 ++++++++++++++------ crates/eps/src/import/ai/read.rs | 7 ++ crates/eps/src/import/ai/read/containers.rs | 6 +- crates/eps/src/import/ai/read/document.rs | 41 +++++-- crates/eps/src/import/ai/read/ops.rs | 11 +- crates/eps/src/import/ai/tests.rs | 101 +++++++++++++++-- 6 files changed, 228 insertions(+), 57 deletions(-) diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index d9a14a0239..6ff37bec92 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -59,6 +59,9 @@ pub(crate) fn drawn_note(typed: bool) -> &'static str { pub(super) const MAX_PENDING: usize = 64; /// The most envelopes and warped text objects one import draws to check; more keep their drawn art. pub(crate) const MAX_CHECKED: usize = 256; +/// The most comparisons with pages those checks make in one import, one for each page an object +/// is on ([`drawn_alike`]); an object that needs more keeps its drawn art. +pub(crate) const MAX_PAGE_COMPARISONS: usize = 4 * MAX_CHECKED; /// The most strokes with dashes aligned to corners one import draws to check against their drawn /// looks (apart from [`MAX_CHECKED`]); more keep their drawn looks. pub(crate) const MAX_DASH_CHECKS: usize = 256; @@ -664,13 +667,31 @@ fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Opt } /// The differences from their drawn art that the live envelopes and warped type of one import may -/// add up to, as shares of the page drawn as the page check draws it: half of what that check allows -/// ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), so they never make the file open from its PDF part -/// instead. +/// add up to on each page the art may be compared with, as shares of that page drawn as the page +/// check draws it: half of what that check allows ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), +/// so they never make the file open from its PDF part instead. Each page has its own share. #[derive(Debug, Default)] pub(crate) struct Spent { - pub(super) any: f64, - pub(super) solid: f64, + /// Each page with the shares of it spent so far: of pixels that differ at all, and of those + /// whose neighbors all differ too. + pub(super) pages: Vec<(Rect, f64, f64)>, + /// How many comparisons with pages have been made ([`MAX_PAGE_COMPARISONS`]). + pub(super) compared: usize, +} + +impl Spent { + /// The shares of `page` spent so far. + pub(super) fn on(&self, page: Rect) -> (f64, f64) { + self.pages.iter().find(|(p, ..)| *p == page).map_or((0.0, 0.0), |&(_, any, solid)| (any, solid)) + } + + /// Set the shares of `page` spent so far. + fn set(&mut self, page: Rect, any: f64, solid: f64) { + match self.pages.iter_mut().find(|(p, ..)| *p == page) { + Some(spent) => *spent = (page, any, solid), + None => self.pages.push((page, any, solid)), + } + } } /// A text object read with a Warp. @@ -738,7 +759,8 @@ pub struct WarpedType { pub(super) envelopes: Vec, pub(super) checks: usize, pub(super) spent: Spent, - pub(super) page: Option, + /// The pages the art may be compared with, each with its own share of the budget ([`Spent`]). + pub(super) pages: Vec, /// [`super::Structure::type_clips`]: type in an envelope's contents clips its clipping group too. pub(super) type_clips: HashMap, /// The envelopes of type that may open live in layers built without a page, by their place @@ -884,7 +906,7 @@ impl WarpedType { let (id, layer) = (doc.alloc_id(), doc.alloc_id()); let mut plain = art.clone(); (plain.visible, plain.opacity) = (true, 1.0); - let page = self.page.filter(|_| shown.contains(&drawn)); + let pages: Vec = if shown.contains(&drawn) { self.pages.clone() } else { vec![] }; let mut alike = None; // In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again // moved onto that art ([`moved_onto`]), after every other way. @@ -917,7 +939,7 @@ impl WarpedType { let shared = Shared { patterns: &doc.patterns, images: &doc.images }; let mut live_one = envelope.clone(); (live_one.visible, live_one.opacity) = (true, 1.0); - if drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) { + if drawn_alike(&live_one, &plain, layer, &shared, &pages, &mut self.spent) { alike = Some(envelope); break; } @@ -942,7 +964,8 @@ impl WarpedType { /// budget has no check left for) with that look: `made` gives the text object a slot became. A /// frame in `threaded` stays type, since the frames of a thread share one story. A replaced /// object's box goes back into the comparisons with the page (out of `restyled`), and only what - /// `doc` shows counts against the page's share of the budget. Returns how many were replaced. + /// `doc` shows counts against the share of the budget of each page it is on. Returns how many + /// were replaced. pub(crate) fn settle( self, doc: &mut Document, @@ -950,7 +973,7 @@ impl WarpedType { threaded: &BTreeSet, restyled: &mut Vec, ) -> usize { - let Self { looks, mut checks, mut spent, page, .. } = self; + let Self { looks, mut checks, mut spent, pages, .. } = self; let mut shown_ids = BTreeSet::new(); doc.layers.iter().for_each(|l| collect_shown(l, &mut shown_ids)); let mut replaced = 0; @@ -965,7 +988,8 @@ impl WarpedType { let (mut shown, mut plain) = (text.clone(), look.clone()); (shown.visible, shown.opacity) = (true, 1.0); (plain.visible, plain.opacity) = (true, 1.0); - alike = warped_alike(&shown, &plain, layer, &shared, page.filter(|_| shown_ids.contains(&id)), &mut spent); + let on: &[Rect] = if shown_ids.contains(&id) { &pages } else { &[] }; + alike = warped_alike(&shown, &plain, layer, &shared, on, &mut spent); } if alike { continue; @@ -1032,23 +1056,24 @@ pub(super) fn warps(appearance: &Appearance) -> bool { } /// Do `live` and `drawn` draw alike? Either neither has any paint ([`paints`]), or few of the -/// pixels either inks differ and fewer still where a whole patch differs, and, on `page` (when the -/// file has one), they differ little enough that with the differences in `spent` the page check -/// still takes the layers' art (it is added to `spent` when they do). Both are drawn on `layer`, a -/// layer id no other node has. -pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { - alike_within(live, drawn, live.visual_bounds(), layer, shared, page, spent) +/// pixels either inks differ and fewer still where a whole patch differs, and, on each of `pages` +/// they are on (the pages the art may be compared with), they differ little enough that with the +/// differences `spent` holds for that page the page check still takes the layers' art (they are +/// added to `spent` when they do on every one). Both are drawn on `layer`, a layer id no other node +/// has. +pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { + alike_within(live, drawn, live.visual_bounds(), layer, shared, pages, spent) } /// [`drawn_alike`] for type under a Warp, compared over all that its effects draw, which can reach /// past its own box. -pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { +pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { let reach = vectorcraft_render::effect_bounds(&alone(live, layer, shared).symbol_boxes(), live); - alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, page, spent) + alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, pages, spent) } /// [`drawn_alike`], with `live` measured as `reach`. -fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { +fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { // Neither has any paint (type with no fill and no stroke, its drawn art the outlines unpainted): // both draw nothing, so they draw alike and add nothing to what the page check sees. Their // shapes aren't compared. Art that paints, however faintly, is compared as before. @@ -1069,21 +1094,31 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, s if share(solid) > MAX_SOLID || share(any) > MAX_ANY { return false; } - let Some(page) = page.filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) else { return true }; - // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along the - // page's longer side). - let on_page = region.intersect(page); - let scale = compare_scale(page); - if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 { - return true; + let mut added = vec![]; + for &page in pages.iter().filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) { + // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along + // the page's longer side). + let on_page = region.intersect(page); + let scale = compare_scale(page); + if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 { + continue; + } + if spent.compared >= MAX_PAGE_COMPARISONS { + return false; + } + spent.compared += 1; + let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false }; + let pixels = (page.width() * scale * page.height() * scale).max(1.0); + let (was_any, was_solid) = spent.on(page); + let (any, solid) = (was_any + any as f64 / pixels, was_solid + solid as f64 / pixels); + if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 { + return false; + } + added.push((page, any, solid)); } - let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false }; - let pixels = (page.width() * scale * page.height() * scale).max(1.0); - let (any, solid) = (spent.any + any as f64 / pixels, spent.solid + solid as f64 / pixels); - if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 { - return false; + for (page, any, solid) in added { + spent.set(page, any, solid); } - *spent = Spent { any, solid }; true } @@ -1161,7 +1196,7 @@ mod tests { #[test] fn art_with_no_paint_draws_alike_and_faint_art_is_still_compared() { let shared = Shared { patterns: &[], images: &BTreeMap::new() }; - let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, None, &mut Spent::default()); + let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, &[], &mut Spent::default()); let (none, other_none) = (square_node(1, None), square_node(2, None)); assert!(alike(&none, &other_none)); let (faint, other_faint) = (square_node(1, Some(0.02)), square_node(2, Some(0.02))); @@ -1169,6 +1204,22 @@ mod tests { assert!(!alike(&none, &square_node(2, Some(1.0)))); } + /// Each page an object is on takes one of the import's comparisons with pages. With none left, + /// art on a page keeps its drawn art, and art on no page needs none. + #[test] + fn comparisons_with_pages_stop_at_their_limit() { + let shared = Shared { patterns: &[], images: &BTreeMap::new() }; + let (live, drawn) = (square_node(1, Some(1.0)), square_node(2, Some(1.0))); + let (page, other) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 60.0, 60.0)); + let mut spent = Spent { compared: MAX_PAGE_COMPARISONS - 2, ..Default::default() }; + assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[page, other], &mut spent)); + assert_eq!(spent.compared, MAX_PAGE_COMPARISONS); + assert!(!drawn_alike(&live, &drawn, NodeId(999), &shared, &[page], &mut spent)); + let off = Rect::new(500.0, 500.0, 600.0, 600.0); + assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[off], &mut spent)); + assert_eq!(spent.compared, MAX_PAGE_COMPARISONS); + } + /// "AVA" at 40 points, at (10, 60). fn type_node(id: u64, style: CharStyle) -> Node { Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "AVA", CharStyle { size: 40.0, ..style })))) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 66cdb82adc..3bb571df07 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -472,6 +472,10 @@ struct BrushesKept { bending: HashMap, } +/// What the pages the art may be compared with are worked out from: the move into the document, +/// the number of artboards, the first artboard and the art's bounding box. +type PageSources = (Option, usize, Option, Option); + struct Reader<'a> { lex: Lexer<'a>, stack: Vec, @@ -604,6 +608,8 @@ struct Reader<'a> { envelope_checks: usize, /// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]). envelope_spent: super::envelope::Spent, + /// [`Self::pages_in_doc`] as last worked out, with what it was worked out from. + page_cache: Option<(PageSources, Arc<[Rect]>)>, /// How many more strokes with dashes aligned to corners this import may draw to check /// ([`super::MAX_DASH_CHECKS`]). dash_checks: usize, @@ -877,6 +883,7 @@ impl<'a> Reader<'a> { envelopes: Vec::new(), envelope_checks: super::envelope::MAX_CHECKED, envelope_spent: super::envelope::Spent::default(), + page_cache: None, dash_checks: super::MAX_DASH_CHECKS, defs_only: false, warped_type: Vec::new(), diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 2a14ce1c24..ad97b7b47b 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -917,6 +917,7 @@ impl<'a> Reader<'a> { } let Some(p) = self.envelopes.pop() else { return }; let scale = self.space_scale(); + let pages = self.pages_in_doc(); let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); let Some(drawn) = drawn else { self.warn(crate::import::ai::envelope::drawn_note(p.typed)); @@ -959,8 +960,7 @@ impl<'a> Reader<'a> { (shown.visible, shown.opacity) = (true, 1.0); let mut plain = drawn.clone(); (plain.visible, plain.opacity) = (true, 1.0); - let page = self.page_in_doc(); - let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent); + let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent); // In Edit Contents, a grid that draws the contents elsewhere than the drawn art is checked // again moved onto that art. if !alike @@ -969,7 +969,7 @@ impl<'a> Reader<'a> { { self.envelope_checks -= 1; (envelope.kind, shown.kind) = (kind.clone(), kind); - alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent); + alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent); } if !alike { self.warn(crate::import::ai::envelope::DRAWN); diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 8492cca6f0..544c6725cc 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -55,6 +55,22 @@ impl AiArtboard { } } +/// The pages the art may be compared with in the document's space, art space being moved there by +/// `to_doc` (none before the art starts): each of `artboards` (else `first`, the first artboard), +/// then `art_box`, the art's bounding box. A page that is an earlier one to half a point is left out. +fn pages_of(to_doc: Option, artboards: &[AiArtboard], first: Option, art_box: Option) -> Vec { + let Some(to_doc) = to_doc else { return vec![] }; + let boards: Vec = if artboards.is_empty() { first.into_iter().collect() } else { artboards.iter().map(|b| b.rect).collect() }; + let mut pages: Vec = vec![]; + for page in boards.into_iter().chain(art_box).map(|r| to_doc.transform_rect_bbox(r)) { + let same = |p: &Rect| [p.x0 - page.x0, p.y0 - page.y0, p.x1 - page.x1, p.y1 - page.y1].iter().all(|d| d.abs() <= 0.5); + if !pages.iter().any(same) { + pages.push(page); + } + } + pages +} + /// The number of entry `key` in `o` when it is written as one finite number of the type `ty` /// (`/Int`, `/Real`, `/Bool`; a whole number unless `/Real`), else `None`. fn typed(o: &Obj, key: &str, ty: &str) -> Option { @@ -923,10 +939,21 @@ impl<'a> Reader<'a> { self.artboards.first().map(|b| b.rect).or(self.cropmarks).or_else(|| self.sized_board()) } - /// The page the art is compared with in the document's space, once the art has started. - pub(super) fn page_in_doc(&self) -> Option { - let board = self.first_board().or_else(|| self.bbox_board())?; - Some(self.to_doc?.transform_rect_bbox(board)) + /// Every page the art may be compared with, in the document's space, once the art has started: + /// each artboard (else the first artboard [`Self::first_board`] gives), since a page of a file's + /// PDF part can show any of them, and the art's bounding box ([`Self::bbox_board`]), which a page + /// cropped to the art and the page of the legacy format show ([`pages_of`]). Worked out again + /// only when the artboards, the art's box or the move into the document have changed. + pub(super) fn pages_in_doc(&mut self) -> Arc<[Rect]> { + let sources = (self.to_doc, self.artboards.len(), self.first_board(), self.bbox_board()); + if let Some((from, pages)) = &self.page_cache + && *from == sources + { + return pages.clone(); + } + let pages: Arc<[Rect]> = pages_of(sources.0, &self.artboards, sources.2, sources.3).into(); + self.page_cache = Some((sources, pages.clone())); + pages } /// The page of a file that says nothing of its artboard (the legacy format as other apps write @@ -1239,8 +1266,8 @@ impl<'a> Reader<'a> { } let to_doc = self.ensure_space(); let artboard = self.first_board(); - // Before the artboards are taken below: the page is the first artboard's. - let page = self.page_in_doc(); + // Before the artboards are taken below: the pages are the artboards' and the art's box. + let pages = self.pages_in_doc(); self.check_symbols(); self.order_symbols(); drop_commented_copies(&mut self.doc.layers, &self.hidden_ids); @@ -1447,7 +1474,7 @@ impl<'a> Reader<'a> { envelopes: self.typed_envelopes, checks: self.envelope_checks, spent: self.envelope_spent, - page, + pages: pages.to_vec(), alone: None, type_clips: self.type_clips, }, diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index fcdffd4580..362425ec72 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -787,7 +787,7 @@ impl<'a> Reader<'a> { } let space = self.space(); self.note_brushes_kept(); - let page = self.page_in_doc(); + let pages = self.pages_in_doc(); let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else { @@ -873,7 +873,8 @@ impl<'a> Reader<'a> { let layer = self.doc.alloc_id(); let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; let shown = !hidden && object.visible && look.visible; - look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + let on: &[Rect] = if shown { &pages } else { &[] }; + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, on, &mut self.envelope_spent) }; alike.then_some(ap) } @@ -885,7 +886,7 @@ impl<'a> Reader<'a> { let layer = self.doc.alloc_id(); let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; let mut spent = crate::import::ai::envelope::Spent::default(); - look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, None, &mut spent) + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, &[], &mut spent) }; alike.then_some(ap) } @@ -1314,7 +1315,7 @@ fn look_alike( hidden: bool, layer: NodeId, shared: &crate::import::ai::envelope::Shared<'_>, - page: Option, + pages: &[Rect], spent: &mut crate::import::ai::envelope::Spent, ) -> bool { let mut live = object.clone(); @@ -1329,7 +1330,7 @@ fn look_alike( for n in [&mut live, &mut plain] { (n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal); } - crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent) + crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, pages, spent) } /// Does `appearance` stroke with dashes aligned to corners and path ends? diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 242d433b7b..9ea967b927 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -9395,24 +9395,35 @@ fn warped_type_gets_what_the_envelopes_left_of_the_budget() { let exact = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)))); let beside = format!("{RED}{}f\n", rect_path(40.5, 20.0, 160.5, 80.0)); let shifted = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &beside))); + let page = Rect::new(0.0, 0.0, 200.0, 100.0); for r in [&exact, &shifted] { assert_eq!(r.warped_type.checks, super::envelope::MAX_CHECKED - 1); - assert!(r.warped_type.page.is_some()); + assert_eq!(r.warped_type.pages, [page]); } live_envelope(&art(&shifted.doc)[0]); - assert!(shifted.warped_type.spent.any > exact.warped_type.spent.any); + assert!(shifted.warped_type.spent.on(page).0 > exact.warped_type.spent.on(page).0); } -/// In a file with an artboard list, warped type is held to the first artboard, not to the crop marks. +/// In a file with an artboard list, warped type is held to every artboard, not to the crop marks. #[test] -fn warped_type_is_held_to_the_first_artboard() { +fn warped_type_is_held_to_every_artboard() { let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ %_/Dictionary :\n%_0 200 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_300 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ %_/Dictionary :\n%_400 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_600 -150 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_; ,\n\ %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; let r = read_ok(&format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0))))); assert_eq!(r.doc.artboards[0].rect, Rect::new(0.0, 0.0, 300.0, 200.0)); - assert_eq!(r.warped_type.page, Some(Rect::new(0.0, 0.0, 300.0, 200.0))); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 300.0, 200.0), Rect::new(400.0, 200.0, 600.0, 350.0)]); +} + +/// Artboards that are an earlier one to half a point, and an art box that is one of them, add no +/// page of their own. +#[test] +fn pages_that_repeat_an_artboard_are_held_once() { + let boards = boards_at(&[[0.0, 0.0, 200.0, 100.0], [0.2, 0.0, 200.0, 100.3], [0.0, 0.0, 200.0, 100.0], [300.0, 0.0, 400.0, 100.0]]); + let data = format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0)))); + let r = read(stream_with_header("%%HiResBoundingBox: 300 0 400 100.4\n", &data).as_bytes()).unwrap(); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 200.0, 100.0), Rect::new(300.0, 0.0, 400.0, 100.0)]); } /// Type whose Warp is hidden draws no warp, so it stays type even with no check left. @@ -9454,17 +9465,39 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { w.look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10 - i as u64), vec![Arc::new(w.look.clone()), mark.clone()]); } let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; - let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); + let page = Rect::new(0.0, 60.0, 60.0, 100.0); let settle = |w: &super::envelope::WarpedLook, spent| { - let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page, ..Default::default() }; + let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, pages: vec![page], ..Default::default() }; warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) }; - let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; + let spent = || super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() }; assert_eq!(settle(&looks[1], Default::default()), 0); assert_eq!(settle(&looks[1], spent()), 1); assert_eq!(settle(&looks[0], spent()), 0); } +/// Each page the art may be compared with has its own share of the budget: warped type on the +/// second page spends that page's share, whatever is left of the first page's. +#[test] +fn warped_type_on_a_later_page_spends_that_pages_share_of_the_budget() { + use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE}; + let (doc, mut looks) = warped_type_doc(2); + // The second object shows. Its look draws a little more than it. + let mark = read_ok(&layer(&format!("{RED}{}f\n", rect_path(2.0, 2.0, 2.6, 2.6)))); + let mark = art(&mark.doc)[0].clone(); + let w = looks.remove(1); + let look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10), vec![Arc::new(w.look.clone()), mark]); + let (first, second) = (Rect::new(200.0, 0.0, 260.0, 40.0), Rect::new(0.0, 60.0, 60.0, 100.0)); + let settle = |spent| { + let looks = vec![super::envelope::WarpedLook { slot: w.slot, look: look.clone(), left_out: None }]; + let warped = super::envelope::WarpedType { looks, checks: 1, spent, pages: vec![first, second], ..Default::default() }; + warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) + }; + let full = |page| super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() }; + assert_eq!(settle(full(first)), 0); + assert_eq!(settle(full(second)), 1); +} + /// An envelope that comes out close to its drawn art, but with more of the page differing than the /// page check can take from the live envelopes (its drawn art 2 pt to the side on a 200 × 100 /// page), keeps the drawn art, so the file still opens from its layers. @@ -9479,6 +9512,58 @@ fn an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it() { assert_eq!(r.warnings, [super::envelope::DRAWN]); } +/// The document data of artboards in art space, each `[x0, y0, x1, y1]`. +fn boards_at(boards: &[[f64; 4]]) -> String { + let boards: String = boards + .iter() + .map(|[x0, y0, x1, y1]| { + format!("%_/Dictionary :\n%_{x0} {y1} /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{x1} {y0} /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n") + }) + .collect(); + format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n") +} + +/// The envelope of [`an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it`] on the +/// second artboard, the first a strip along the top that it doesn't reach: a page of the second +/// artboard can be compared with the layers, so it is held to that page and keeps its drawn art. +/// One that draws as its drawn art opens live there. +#[test] +fn an_envelope_on_a_later_artboard_that_differs_over_its_page_keeps_its_drawn_art() { + let boards = boards_at(&[[0.0, 98.0, 20.0, 100.0], [0.0, 0.0, 200.0, 100.0]]); + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted); + let r = read_ok(&format!("{boards}{}", layer(&body))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]); + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)); + let r = read_ok(&format!("{boards}{}", layer(&body))); + live_envelope(&art(&r.doc)[0]); +} + +/// The same envelope on no artboard, inside the art's bounding box: a page cropped to the art +/// shows it, so it is held to that page too. +#[test] +fn an_envelope_off_the_artboards_that_differs_over_the_arts_box_keeps_its_drawn_art() { + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted); + let data = format!("{}{}", boards_at(&[[0.0, 98.0, 20.0, 100.0]]), layer(&body)); + let r = read(stream_with_header("%%HiResBoundingBox: 0 0 200 100\n", &data).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]); +} + /// An envelope whose drawn art holds an object the reader can't read keeps that drawn art, which /// the page's art replaces. #[test] From 06d977439b420b9876cf650c56afdd592c1aea23 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:43:17 -0800 Subject: [PATCH 35/42] Tests: ui-egui tests that change the proof view hold the default proof view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit View › Proof Colors, Overprint Preview and Separations Preview are one view for the whole process, and the canvas draws through it. Canvas tests hold `testing::DefaultProofView` to keep it fixed while they compare frames, and `testing.rs` asks every test that sets the view to hold it too. Three tests changed it without holding it: - `panels::actions::tests_edits::every_listed_menu_item_runs_from_the_menu_what_its_step_holds` and `shortcut_editor::tests::listed_commands_run_from_a_key_without_a_missing_param` run every listed command, the View menu's proof commands included. - `dialogs::new_document::tests::new_document_choice_enter_commits_before_create` creates a document with Preview Mode set to Overprint, which turns on Overprint Preview and leaves it on. When one of them ran between two frames of a canvas test in the same test process, the render options of the next frame no longer matched the frame shown. An edit then rendered the whole frame instead of drawing its part, and `canvas::tests::without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render` failed with "rendered whole about STILL_SECS after the view stopped: 1 frames". Turning Overprint Preview on between two of its frames gives that failure every time. --- crates/ui-egui/src/dialogs/new_document.rs | 2 ++ crates/ui-egui/src/panels/actions/tests_edits.rs | 2 ++ crates/ui-egui/src/shortcut_editor.rs | 2 ++ 3 files changed, 6 insertions(+) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index bf048d3e28..8ec5e10ba1 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -907,6 +907,8 @@ mod tests { #[test] fn new_document_choice_enter_commits_before_create() { + // Preview Mode's last choice, Overprint, turns on the whole process's Overprint Preview. + let _view = crate::testing::DefaultProofView::new(); let mut panel = actual_preset_dialog(); panel.click("Advanced Options"); for (label, key) in [ diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index d83e306f05..1fe2f13711 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -925,6 +925,8 @@ fn insert_menu_item_refuses_what_no_menu_item_runs_and_changes_nothing() { /// artboard to both. #[test] fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() { + // The View menu's proof items change the whole process's proof view. + let _view = crate::testing::DefaultProofView::new(); for item in crate::menus::insertable_items(false, &crate::menus::Listed::default()) { let (mut app, _) = app_with_three_moves(); app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": item.command, "params": item.params})).unwrap(); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a96f77c18a..3c8c5cc986 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -2437,6 +2437,8 @@ mod tests { #[test] fn listed_commands_run_from_a_key_without_a_missing_param() { use vectorcraft_testkit::fixtures::Fixture; + // The View menu's proof commands change the whole process's proof view. + let _view = crate::testing::DefaultProofView::new(); // These need a state the fixtures lack: text being edited, a pattern being edited, an // object linked to a graphic style, a plug-ins folder. let context = ["text.insertInline", "pattern.options", "graphicStyle.redefine", "plugin.reload"]; From d19a3305a46b4cb6b3258d30d36d9487359ff098 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:10:58 -0800 Subject: [PATCH 36/42] EPS import: complexity tests count the work done instead of timing it Four EPS import tests asserted elapsed time (5 s, 20 s, a 20 s receive timeout, and 1,000 copies against 5 times one copy). A busy test runner could fail them, and a slower run that was still bounded could pass them. Each now reads a test-only counter on its own thread: - `]` without its `[`: the operand stack slots that `[` and `]` look at. 200,000 brackets look at no more than 4 slots each. - The outline check: the point-to-segment distances it works out. A look drawn 5,000 times works out no more than `MAX_OUTLINE_PAIRS`. - Objects on a path: the paths and objects the records measure. A thousand copies of a record measure as many as one copy. - File fonts: the glyphs `fits` compares. A string of 250,000 of one character makes fewer comparisons than it has glyphs. Outside tests the counters do nothing. --- crates/eps/src/import/ai/read.rs | 4 ++ crates/eps/src/import/ai/read/on_path.rs | 16 ++++++++ crates/eps/src/import/ai/read/ops.rs | 52 +++++++++++++++++++++--- crates/eps/src/import/ai/tests.rs | 32 +++++++-------- crates/eps/src/import/file_fonts.rs | 27 ++++++++---- 5 files changed, 100 insertions(+), 31 deletions(-) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 66cdb82adc..cf7c5e1159 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -155,6 +155,10 @@ pub use document::{ }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; +#[cfg(test)] +pub(crate) use on_path::on_path_measured; +#[cfg(test)] +pub(crate) use ops::array_slots; pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs index 1e33e09a1b..682739c27d 100644 --- a/crates/eps/src/import/ai/read/on_path.rs +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -123,6 +123,18 @@ impl Reader<'_> { } } +#[cfg(test)] +thread_local! { + /// How many paths and objects the records on this thread have measured. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`MEASURED`] of this thread. +#[cfg(test)] +pub(crate) fn on_path_measured() -> u64 { + MEASURED.get() +} + /// Give each group that a record of `found` names exactly its [`ObjectsOnPath`] record. pub(super) fn apply(doc: &mut Document, found: &OnPath) { if found.records.is_empty() { @@ -174,11 +186,15 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap if !tried.insert(g.id) { return None; } + #[cfg(test)] + MEASURED.set(MEASURED.get() + 1); attachable_path(children.iter().find(|c| c.id == path)?)?; let mut members = Vec::with_capacity(placed.len()); for (id, place, angle) in placed { // The frame the object is drawn in: turned by its angle (the document's y points down) // about the center of its bounds. + #[cfg(test)] + MEASURED.set(MEASURED.get() + 1); let center = doc.node_at(place)?.geometric_bounds()?.center(); members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index fcdffd4580..1bf190817c 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -9,6 +9,29 @@ use super::{ use vectorcraft_doc::{ArrowAlign, Arrowhead}; use vectorcraft_geom::PathData; +#[cfg(test)] +thread_local! { + /// The operand stack slots that `[` and `]` have looked at on this thread, to find the open + /// `[` or to take an array's items: their work. + static ARRAY_SLOTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The point-to-segment distances [`draws_look_outline`] has worked out on this thread. + static OUTLINE_PAIRS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`ARRAY_SLOTS`] of this thread. +#[cfg(test)] +pub(crate) fn array_slots() -> u64 { + ARRAY_SLOTS.get() +} + +/// Count `slots` that `[` or `]` looked at in [`ARRAY_SLOTS`]; nothing outside tests. +fn array_slots_looked_at(slots: usize) { + #[cfg(test)] + ARRAY_SLOTS.set(ARRAY_SLOTS.get().saturating_add(u64::try_from(slots).unwrap_or(u64::MAX))); + #[cfg(not(test))] + let _ = slots; +} + impl<'a> Reader<'a> { // ---- operators ------------------------------------------------------------------------- @@ -16,11 +39,13 @@ impl<'a> Reader<'a> { // The innermost `[` still on the stack (the stack is cut back by operators). let mut at = self.stack.len(); while let Some(m) = self.marks.pop() { + array_slots_looked_at(1); if matches!(self.stack.get(m), Some(V::Mark)) { at = m; break; } } + array_slots_looked_at(self.stack.len() - at); let items: Vec = self.stack.split_off(at).into_iter().skip(1).collect(); self.push(V::Arr(items)) } @@ -172,6 +197,7 @@ impl<'a> Reader<'a> { "[" => { // Drop marks that operators have taken off, so `marks` is the open nesting. while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) { + array_slots_looked_at(1); self.marks.pop(); } // Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack. @@ -1635,7 +1661,13 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo /// projection onto it) is taken from `budget`: `false` once that runs out. fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool { use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; - let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT); + let close = |p: kurbo::Point| { + b.iter().any(|t| { + #[cfg(test)] + OUTLINE_PAIRS.set(OUTLINE_PAIRS.get() + 1); + t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT + }) + }; for s in a { let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil(); let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 }; @@ -2019,7 +2051,8 @@ mod tests { /// The outline check works from one budget for the object: a look of the outline drawn twice /// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn - /// look instead of comparing every copy. + /// look instead of comparing every copy, having worked out no more distances than the budget + /// holds. #[test] fn the_outline_check_has_one_budget_for_the_object() { let zig = vectorcraft_doc::Effect { @@ -2035,10 +2068,17 @@ mod tests { let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect(); Node::group(NodeId(2), drawn) }; - assert!(draws_look_outline(&object, &appearance, &look(2))); - let started = std::time::Instant::now(); - assert!(!draws_look_outline(&object, &appearance, &look(5_000))); - assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + // Whether the object draws `look`, and how many distances the check worked out. + let check = |look: &Node| { + let before = OUTLINE_PAIRS.get(); + let drawn = draws_look_outline(&object, &appearance, look); + (drawn, OUTLINE_PAIRS.get() - before) + }; + let (drawn, two) = check(&look(2)); + assert!(drawn); + let (drawn, many) = check(&look(5_000)); + assert!(many <= u64::try_from(MAX_OUTLINE_PAIRS).unwrap(), "5,000 copies: {many} distances; 2 copies: {two}"); + assert!(!drawn); } /// The outline check reshapes the object as it is drawn, its effects working from its bounds diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 242d433b7b..57d402f1f4 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -6440,13 +6440,16 @@ fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() { } } +/// A `]` without its `[` looks at a few operand stack slots, not at every slot below it: hundreds +/// of thousands of them look at no more than four slots each. #[test] fn closing_brackets_without_their_opening_dont_rescan_the_stack() { let n = 200_000; let body = format!("{}\n{}\n", "1 ".repeat(n), "] ".repeat(n)); - let started = std::time::Instant::now(); + let before = read::array_slots(); let _ = read(stream(&layer(&body)).as_bytes()); - assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed()); + let slots = read::array_slots() - before; + assert!(slots <= 4 * u64::try_from(n).unwrap(), "{n} brackets looked at {slots} slots"); } #[test] @@ -10833,9 +10836,9 @@ fn an_objects_on_path_record_that_doesnt_fit_leaves_a_plain_group() { } /// The path and objects of a group are measured once however many records name it: a thousand -/// copies of a record open about as fast as one copy followed by 999 records whose path id is -/// missing, when the group opens live, when its long path has no length, and when its first object -/// is a group of many paths and its last object has no bounds. +/// copies of a record measure as many paths and objects as one copy followed by 999 records whose +/// path id is missing, when the group opens live, when its long path has no length, and when its +/// first object is a group of many paths and its last object has no bounds. #[test] fn repeated_objects_on_path_records_dont_measure_the_objects_again() { use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record}; @@ -10860,23 +10863,18 @@ fn repeated_objects_on_path_records_dont_measure_the_objects_again() { let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000"); let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]); let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]); - let time = |data: &str| { - let started = std::time::Instant::now(); + let measure = |data: &str| { + let before = read::on_path_measured(); let doc = read_ok(&format!("{data}{}", layer(&group))).doc; - let elapsed = started.elapsed(); + let measured = read::on_path_measured() - before; let g = art(&doc)[0].clone(); assert_eq!(g.children().unwrap().len(), n, "{why}"); assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}"); - elapsed + measured }; - // The fastest of three runs each, taken in turn, so that other tests running at the same - // time weigh on both. - let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX); - for _ in 0..3 { - fastest_one = fastest_one.min(time(&one)); - fastest_many = fastest_many.min(time(&many)); - } - assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}"); + let (measured_one, measured_many) = (measure(&one), measure(&many)); + assert!(measured_one > 0, "{why}"); + assert_eq!(measured_many, measured_one, "{why}: 1000 copies measured {measured_many} times, one copy {measured_one}"); } } diff --git a/crates/eps/src/import/file_fonts.rs b/crates/eps/src/import/file_fonts.rs index 83e51bb7ee..de6f044cd3 100644 --- a/crates/eps/src/import/file_fonts.rs +++ b/crates/eps/src/import/file_fonts.rs @@ -38,6 +38,12 @@ struct Gathered { chars: HashMap, } +#[cfg(test)] +thread_local! { + /// How many glyphs [`FileFontGlyphs::fits`] has compared with another glyph on this thread. + static COMPARED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + impl FileFontGlyphs { /// The font of `family` and `style` (made with `info` the first time): its index. pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize { @@ -59,6 +65,10 @@ impl FileFontGlyphs { let mut new: HashMap = HashMap::new(); for g in glyphs { let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied()); + #[cfg(test)] + if kept.is_some() { + COMPARED.set(COMPARED.get() + 1); + } match kept { Some(k) if k.outline != g.outline || k.advance != g.advance => return false, Some(_) => {} @@ -178,15 +188,16 @@ mod tests { } /// A long string of one character compares each glyph with that character's once, not with - /// every one before it: a quarter of a million of them fit at once. + /// every one before it: a quarter of a million of them fit at once, with fewer comparisons + /// than glyphs. #[test] fn a_long_string_of_one_character_fits_in_linear_time() { - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let mut g = FileFontGlyphs::default(); - let f = g.font("F", "Regular", FileFontInfo::default); - tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok(); - }); - assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true)); + let n = 250_000; + let mut g = FileFontGlyphs::default(); + let f = g.font("F", "Regular", FileFontInfo::default); + let before = COMPARED.get(); + assert!(g.fits(f, &vec![glyph('A'); n])); + let compared = COMPARED.get() - before; + assert!(compared < u64::try_from(n).unwrap(), "{n} glyphs: {compared} comparisons"); } } From 53aa1a148c05698565dfdacd35871514ad90af91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:04:57 -0800 Subject: [PATCH 37/42] Command Palette: leave out commands with no menu item that need a value A command with no menu path whose params name a required field (Close Path needs an `id`, Knife needs `points`) was still listed, and a pick of it always failed with an error such as "missing id". The rule that leaves out commands needing a value now applies to these commands as well as to menu commands, so 232 more engine commands are left out (562 in all, up from 330). Rename Artboards and the Remove Asset, Rename Asset and Set 3D Format commands stay listed: a pick of each opens the Rename dialog or the Asset Export panel. --- crates/ui-egui/src/palette.rs | 38 +++++++++------------------ crates/ui-egui/src/shortcut_editor.rs | 7 ++--- 2 files changed, 17 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 40699f7804..aad5a37d1f 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -44,7 +44,8 @@ const WRAPPED: &[(&str, &str)] = &[ /// every preference, Forget Import Matches forgets every saved match, Begin Undo Group and End /// Undo Group begin and end a group, the six Save … Preset commands save a new preset (Save /// Gradient Preset the selection's gradient), Delete Gradient Preset deletes the saved preset the -/// selection's gradient matches, the three Asset Export commands open the Asset Export panel (#4864), New +/// selection's gradient matches, the six Asset Export commands open the Asset Export panel (#4864), +/// Rename Artboards opens the Rename dialog for the selected artboards, New /// Symbol makes a symbol of the selection, Gradient Vector gives the selection the default /// gradient, Define Perspective Grid makes the document's grid, Select Slice deselects the /// slices, and Find Next goes on from the last Find and Replace search or opens its dialog, as @@ -65,8 +66,12 @@ const PICK_RUNS: &[&str] = &[ "gradient.presets.save", "gradient.presets.delete", "assets.export", + "assets.remove", + "assets.rename", "assets.export3D", + "assets.set3DFormat", "assets.settings.set", + "artboard.rename", "symbol.new", "paint.setGradientGeom", "perspective.grid.set", @@ -80,23 +85,11 @@ const PANEL_PATH: &str = "Window › Show Panel"; /// The menu path ([`context`]) a result takes when another result has its name: (id, English /// path), for commands that no item of the menu bar runs and whose id names no parent command. const CONTEXTS: &[(&str, &str)] = &[ - ("addon.pen.close", "Pen"), - ("addon.pen.reshape", "Pen"), - ("addon.pen.togglePoint", "Pen"), - ("charStyle.setAttrs", "Character Styles"), ("file.exportInBackground", "Export"), ("file.openInBackground", "Open"), ("imageTrace.hideRuns", "Image Trace"), ("links.reveal", "Links"), - ("livePaint.fill", "Live Paint"), - ("object.blend.spine.convertAnchor", "Blend"), - ("paraStyle.setAttrs", "Paragraph Styles"), - ("path.close", "Path"), - ("path.convertAnchor", "Path"), - ("path.knife", "Path"), - ("path.reshapeSegment", "Path"), ("plugin.hideRuns", "Plug-ins"), - ("text.editRange", "Text"), ("ui.layersPanelOptions", "Layers"), ("ui.navigatorPanelOptions", "Navigator"), ]; @@ -1563,15 +1556,8 @@ mod tests { ("ui.paraStyleOptions.resetPanel", "Paragraph Style Options › Reset Panel"), ("window.swatchLibrary.other", "Window › Swatch Libraries › Other Library…"), ("window.brushLibrary.other", "Window › Brush Libraries › Other Library…"), - ("tool:knife", "Tools › Knife"), - ("path.knife", "Path › Knife"), - ("addon.pen.close", "Pen › Close Path"), - ("path.close", "Path › Close Path"), ("type.fitHeadline", "Type › Fit Headline (type.fitHeadline)"), ("text.fitHeadline", "Type › Fit Headline (text.fitHeadline)"), - ("shape.ellipse", "Ellipse (shape.ellipse)"), - ("addon.shapes.ellipse", "Ellipse (addon.shapes.ellipse)"), - ("perspective.editText", "Object › Perspective › Edit Text"), ("ui.action.play", "Play Action (ui.action.play)"), ("ui.action.playAt", "Play Action (ui.action.playAt)"), ("ui.batchDialog", "Batch…"), @@ -1690,7 +1676,8 @@ mod tests { /// Of the engine commands the palette listed before, it leaves out only the ones /// [`crate::shortcut_editor::needs_a_value`] marks: queries with no default key and no item of - /// the menu bar, and commands that need a value no menu item gives. A pick of each one it leaves + /// the menu bar, and commands that need a value no menu item gives, with a menu path of their own + /// or without one. A pick of each one it leaves /// out (with no document, one object selected or several) changes neither the document, its /// selection, history and layer state, nor the interface. Every [`PICK_RUNS`] query is still /// listed. @@ -1706,7 +1693,8 @@ mod tests { let listed: std::collections::HashSet = items().into_iter().map(|(_, id)| id).collect(); let dropped: Vec<&vectorcraft_engine::CommandSpec> = before.iter().copied().filter(|c| !listed.contains(c.id)).collect(); let ids: Vec<&str> = dropped.iter().map(|c| c.id).collect(); - for id in ["document.json", "brush.unused", "symbol.unused", "transparency.set"] { + // Close Path, Set Handle and Knife have no menu path, and each needs an `id`. + for id in ["document.json", "brush.unused", "symbol.unused", "transparency.set", "path.close", "path.setHandle", "path.knife"] { assert!(ids.contains(&id), "{id} is left out: {ids:?}"); } // What a pick can change: the document with its selection, history, revision and layer @@ -1733,8 +1721,8 @@ mod tests { look(&app) != before }) }; - // `layer.setProps {}` records an undo step that changes nothing. - let changed: Vec<&str> = ids.iter().copied().filter(|id| *id != "layer.setProps" && acts(id)).collect(); + // `layer.setProps {}` and `path.moveAnchors {}` record an undo step that changes nothing. + let changed: Vec<&str> = ids.iter().copied().filter(|id| !["layer.setProps", "path.moveAnchors"].contains(id) && acts(id)).collect(); assert!(changed.is_empty(), "a pick of these does something: {changed:?}"); for c in &dropped { assert!(c.shortcut.is_none() && crate::shortcut_editor::menu_bar_path(c.id).is_none(), "{}", c.id); @@ -1767,7 +1755,7 @@ mod tests { for id in PICK_RUNS.iter().filter(|id| !session_only.contains(id)) { assert!(acts(id), "a pick of {id} does something"); } - for id in PICK_RUNS.iter().chain(&["object.group", "select.key", "view.preciseCursors", "path.close"]) { + for id in PICK_RUNS.iter().chain(&["object.group", "select.key", "view.preciseCursors"]) { assert!(listed.contains(*id), "{id} stays"); } } diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a96f77c18a..50ce83bf84 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -798,8 +798,9 @@ pub(crate) fn menu_target(id: &str) -> Option<(String, Value)> { /// Is `key` a command with no default shortcut that a key press can't run: no item of the menu /// bar runs it without params or with one set of params ([`menu_target`]), it opens no dialog when /// run without them (as the Variables panel's commands do), and it is a query, whose answer a key -/// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a menu command whose params -/// doc names a field a call must give (File › Document Setup › Units, `{units}`)? +/// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a command whose params doc +/// names a field a call must give, with a menu path (File › Document Setup › Units, `{units}`) or +/// without one (Close Path, `{id}`)? pub(crate) fn needs_a_value(key: &str) -> bool { static KEYS: OnceLock> = OnceLock::new(); KEYS.get_or_init(|| { @@ -809,7 +810,7 @@ pub(crate) fn needs_a_value(key: &str) -> bool { c.shortcut.is_none() && !a_menu_bar_item_runs(c.id, c.params) && !crate::dialogs::variables::opens(c.id) - && (!c.journal || NEEDS_A_PARAM.contains(&c.id) || (!c.menu.is_empty() && names_a_required_field(c.params))) + && (!c.journal || NEEDS_A_PARAM.contains(&c.id) || names_a_required_field(c.params)) }) .map(|c| c.id) .collect() From 3315bc4bfd6f2aac706a7e9a61398d12524acaab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:10:15 -0800 Subject: [PATCH 38/42] Docs: limit the Preview-off exception to layers that are not templates A template layer stays in Preview whatever its Preview flag is, so only a layer that is not a template and has Preview off draws placed files by the Outline rules in Preview mode. --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index bceff53d7b..b356fa923b 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -558,7 +558,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | | Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: while the artboards show, the canvas outside the artboards is white in every interface brightness and Canvas Color, and the artboards keep their paper and edges and draw no shadows. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | | Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | -| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | +| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer that is not a template and whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | From 27104129d0ae9f83e8a4be5eb62d7d6fa7d55ae9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:10:33 -0800 Subject: [PATCH 39/42] Docs: list the placed EPS files the .ai reader leaves as before The progress line now names the cases where a placed EPS file whose bytes the editing data includes stays as on main: DCS bytes, no bounding box of its own, a VectorCraft document, bytes that don't read as EPS, an `.ai` or `.ait` file name, and a previewed file that an image variable binds. --- 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 bc7a0f541a..df6433d0ed 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2436,7 +2436,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). - A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). + A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified. The placed file stays as before when its bytes are a DCS file, have no bounding box of their own, carry a VectorCraft document, don't read as an EPS file, or belong to a file named `.ai` or `.ait`, and a placed EPS file with a preview that an image variable binds stays the linked image showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). In a `.ai` or EPS opened from its editing data, and in a legacy `.ai`, each anchor is smooth or a corner as the case of the segment operator ending on it says (`l`, `c`, `v`, `y` smooth; `L`, `C`, `V`, `Y` corner), and a closed path's first anchor takes the case of the segment back to it; points and handles stay where they are. Paths, compound paths, clipping paths, guide paths, area type frames and type-on-a-path paths all keep it (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/legacy_ai/tests.rs`). In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From ebf50139e7f4d888f5a4fc75a63bce8e2c293247 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:18:35 -0800 Subject: [PATCH 40/42] Properties: a live rectangle's Corner menu sets a kind only when it is chosen The Corner menus of a live rectangle's properties (one for all four corners while Corner Radius is linked, one per corner otherwise) read the select's current value, so a kind highlighted with the arrow keys in the open list ran object.setLiveShape at once and recorded an undo step, and Escape left the highlighted kind on the rectangle. The menus now read only the committed pick, as the Corner menu of Direct-Selected corners does since #9728. The rows are shared by the Transform panel, the Properties panel's Transform section and the Contextual Task Bar. --- crates/ui-egui/src/panels.rs | 5 +- crates/ui-egui/src/panels/transform/tests.rs | 66 ++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 52649d6400..7e18b51179 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -167,9 +167,10 @@ fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { } /// A select of the corner kinds named `name`, showing `current` (blank for None), as wide as its -/// widest kind, so it fits beside a corner's radius field. Returns the kind picked. +/// widest kind, so it fits beside a corner's radius field. Returns the kind chosen, not one only +/// highlighted in the open list. fn corner_select(ui: &mut Ui, name: &'static str, current: Option, entries: &[Entry]) -> Option { - Select::new(name, Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), entries).sizing(Sizing::Content).show(ui).value().copied() + Select::new(name, Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), entries).sizing(Sizing::Content).show(ui).events.committed().copied() } /// Set `kind` on corner `corner` (every corner for None) of each selected live rectangle diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index bfad19d09b..a5f37234e1 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -158,6 +158,72 @@ fn a_rectangle_shows_linked_and_unlinked_corner_types() { assert!(!p.shows("Corner") && p.shows("Top Left Corner") && p.shows("Bottom Left Corner")); } +/// Checks a live rectangle's Corner menu `menu` drawn by `draw`, with Corner Radius linked +/// (`single`) or not: a kind highlighted in the open menu leaves the rectangle as it is, Escape +/// closes the menu with the kind and the undo history unchanged, and Enter sets the highlighted +/// kind, on the corners `changed` marks, as one undo step. +fn check_corner_kind_menu(draw: fn(&mut VectorcraftApp, &mut Ui), single: bool, menu: &str, changed: [bool; 4]) { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + use vectorcraft_doc::{LiveCorners, NodeId}; + use vectorcraft_geom::shapes::CornerKind; + let mut app = new_app(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 120, "height": 80, "radius": 10})).unwrap()["id"].as_u64().unwrap(); + set_pref(&mut app, "singleCornerRadius", single); + let mut p = Panel::new(app, draw); + let kinds = |p: &Panel| { + let app = p.app(); + let corners = LiveCorners::of(app.session.active().unwrap().doc.node(NodeId(id)).unwrap()).unwrap(); + [0, 1, 2, 3].map(|k| corners.kind(k)) + }; + let original = p.app().session.active().unwrap().doc.clone(); + assert_eq!(kinds(&p), [CornerKind::ALL[0]; 4]); + let undo = undo_depth(&p.app()); + + p.click_role(menu, Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + assert!(p.app().session.active().unwrap().doc == original, "{menu}: highlighting a kind leaves the rectangle as it was"); + p.key(Key::Escape, Modifiers::NONE); + assert!(p.shows(menu), "{menu}: the panel still shows the menu after Escape"); + assert!(p.app().session.active().unwrap().doc == original, "{menu}: Escape leaves the rectangle as it was"); + assert_eq!(undo_depth(&p.app()), undo, "{menu}: Escape records no undo step"); + + p.click_role(menu, Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + p.key(Key::Enter, Modifiers::NONE); + let expected = changed.map(|c| if c { CornerKind::ALL[1] } else { CornerKind::ALL[0] }); + assert_eq!(kinds(&p), expected, "{menu}: Enter sets the highlighted kind"); + assert_eq!(undo_depth(&p.app()), undo + 1, "{menu}: the kind is one undo step"); +} + +/// The Transform panel's Corner menu for all four corners of a live rectangle applies only the +/// kind chosen. +#[test] +fn transform_panel_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(show, true, "Corner", [true; 4]); +} + +/// The Transform panel's Corner menu for one corner of a live rectangle applies only the kind +/// chosen. +#[test] +fn transform_panel_single_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(show, false, "Top Right Corner", [false, true, false, false]); +} + +/// The Properties panel's Corner menu for all four corners of a live rectangle applies only the +/// kind chosen. +#[test] +fn properties_panel_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(crate::panels::properties::transform_section, true, "Corner", [true; 4]); +} + +/// The Properties panel's Corner menu for one corner of a live rectangle applies only the kind +/// chosen. +#[test] +fn properties_panel_single_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(crate::panels::properties::transform_section, false, "Top Right Corner", [false, true, false, false]); +} + /// The four corner labels of an unlinked Corner Radius, in the Transform panel and in the /// Properties panel, start at one edge of their column whatever their widths, and the radius /// fields after them line up. From 3d33094d3924abfa1772620daee097e034592d18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:39:57 -0800 Subject: [PATCH 41/42] Direct Selection: hover marks the anchor a press takes across selected groups The selected paths a hover tries were listed group by group in selection order, while a press tries them topmost first across the document. With two selected groups whose anchors fall within reach, hover marked the back group's anchor and a press took the front one. The list is now sorted in paint order, topmost first, with a Shaper Group's original shapes included. --- crates/tools/src/direct.rs | 22 +++++++++++++++++----- crates/tools/src/direct/tests.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 02eb4e2202..4ee67bde6c 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -641,15 +641,14 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { } /// The editable paths of the selected objects and inside them (a selected group's members), with -/// their control bounds: each selected object's paths topmost first, in selection order. The list -/// is made once per document state and selection; a hover measures only the paths whose bounds it -/// is near. +/// their control bounds, topmost first across the whole document: the order [`hit_anchor`] tries +/// them in. The list is made once per document state and selection; a hover measures only the +/// paths whose bounds it is near. fn selected_part_boxes(cx: &ToolContext) -> std::sync::Arc<[(NodeId, vectorcraft_geom::Rect)]> { crate::select::selected_part_boxes(cx, || { let editable = cx.doc.editable(); let mut v = vec![]; for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { - let from = v.len(); walk_pickable_from(root, &mut |n| { if editable(n.id) && let Some(b) = editable_path(n).and_then(|pd| pd.control_bounds()) @@ -657,8 +656,21 @@ fn selected_part_boxes(cx: &ToolContext) -> std::sync::Arc<[(NodeId, vectorcraft v.push((n.id, b)); } }); - v[from..].reverse(); } + // The paint order of every node, a Shaper Group's original shapes included (isolation can + // select them); the topmost path comes first. + fn walk_all(n: &Node, order: &mut std::collections::HashMap) { + let i = order.len(); + order.insert(n.id, i); + for c in n.children().into_iter().flatten() { + walk_all(c, order); + } + } + let mut order = std::collections::HashMap::new(); + for l in &cx.doc.layers { + walk_all(l, &mut order); + } + v.sort_by_key(|(id, _)| std::cmp::Reverse(order.get(id).copied())); v.into() }) } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index b4689642fd..ee1d88778f 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -3074,3 +3074,31 @@ fn select_behind_is_measured_once_for_a_point() { assert!(crate::select::selects_behind_at(&c, at)); assert_eq!(MEASURED_PARTS.get() - before, 1, "measured for the first ask only"); } + +/// With two selected groups whose anchors sit on the same point, the highlighted anchor is the one +/// a press takes: the front group's, whatever order the groups were selected in. +#[test] +fn the_highlighted_anchor_of_two_selected_groups_is_the_one_a_press_takes() { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (back_path, back, front_path, front) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = |id, x| { + std::sync::Arc::new(vectorcraft_doc::Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(x, x, x + 100.0, x + 100.0)), + vectorcraft_doc::Appearance::default_art(), + )) + }; + d.insert(Some(l), 0, vectorcraft_doc::Node::group(back, vec![path(back_path, 100.0)])).unwrap(); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::group(front, vec![path(front_path, 100.0)])).unwrap(); + let p = paint(); + let corner = Point::new(100.0, 100.0); + for order in [[back, front], [front, back]] { + let mut s = Selection::default(); + s.set(order); + let c = cx(&d, &s, &p); + let pressed = hit_anchor(&c, corner, c.point_tol()).map(|(id, ..)| id); + assert_eq!(pressed, Some(front_path), "a press takes the front anchor (selected {order:?})"); + assert_eq!(hovered_anchor(&c, corner), Some((front_path, corner)), "the front anchor is highlighted (selected {order:?})"); + } +} From 1caf734c0f534c25bd1f68e44ca05538de8f7c86 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:42:17 -0800 Subject: [PATCH 42/42] Docs: state the 256 MiB limit on included placed EPS bytes --- 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 df6433d0ed..16f9c83d42 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2436,7 +2436,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). - A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified. The placed file stays as before when its bytes are a DCS file, have no bounding box of their own, carry a VectorCraft document, don't read as an EPS file, or belong to a file named `.ai` or `.ait`, and a placed EPS file with a preview that an image variable binds stays the linked image showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). + A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified. The placed file stays as before when its bytes are larger than 256 MiB, are a DCS file, have no bounding box of their own, carry a VectorCraft document, don't read as an EPS file, or belong to a file named `.ai` or `.ait`, and a placed EPS file with a preview that an image variable binds stays the linked image showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). In a `.ai` or EPS opened from its editing data, and in a legacy `.ai`, each anchor is smooth or a corner as the case of the segment operator ending on it says (`l`, `c`, `v`, `y` smooth; `L`, `C`, `V`, `Y` corner), and a closed path's first anchor takes the case of the segment back to it; points and handles stay where they are. Paths, compound paths, clipping paths, guide paths, area type frames and type-on-a-path paths all keep it (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/legacy_ai/tests.rs`). In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`).