From 959332840ce5f3aae7e1472236b8e34f43f337bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:27:12 -0800 Subject: [PATCH 01/68] 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/68] 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/68] 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/68] 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/68] 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 2400aa7712cd7be374ef957fdd4b6caa470293ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:51:26 -0800 Subject: [PATCH 06/68] Scripts: reflect describes an object's properties and methods Every object now has a read-only reflect property. Each read gives a new frozen reflection with the class name, the properties and methods as entries (name, type, dataType, defaultValue, min, max, isCollection, arguments), and find(name). - app, its documents, page items, layers, DocumentPreset and each class constructor are described from the host class registry: the installed members give the names and access, and the new HostClass.info gives the types, bounds, defaults and method arguments dom.rs declares beside each member. Members that are not available yet are left out. A class that names a member twice or describes a member it does not have is refused. - Any other object is described by its own properties without running a getter; a JavaScript function's parameters are its arguments. - An object with more than 10,000 members and arguments throws a RangeError. - script.check counts reflection as a language feature, not host-only. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 312 +++++++++++++---- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/builtins/extensions.rs | 7 +- crates/js/src/host_classes.rs | 139 +++++++- crates/js/src/host_tests.rs | 2 +- crates/js/src/lib.rs | 6 +- crates/js/src/realm.rs | 4 +- crates/js/src/reflect.rs | 331 ++++++++++++++++++ crates/js/src/reflect_tests.rs | 242 +++++++++++++ crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/tests.rs | 7 + docs/mcp.md | 20 +- docs/target-app-parity.md | 1 + 13 files changed, 995 insertions(+), 80 deletions(-) create mode 100644 crates/js/src/reflect.rs create mode 100644 crates/js/src/reflect_tests.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bce4edad74..6fda66efe1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -25,7 +25,12 @@ //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. -//! - Members the help pages list that are not here yet throw an error that says so. +//! - Members the help pages list that are not here yet throw an error that says so, and `reflect` +//! leaves them out. +//! - `reflect` on an object or a class gives each member's type from the declaration that installs +//! the member ([`classes`]): a class name, `boolean`, `number`, `string`, `Array` for a list of +//! numbers, the enumeration's name for an enumerated value, and `*` where the value can be of +//! more than one type. use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -33,7 +38,9 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_geom::{Point, Rect}; -use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; +use vectorcraft_js::{ + ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts, +}; use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; @@ -151,9 +158,23 @@ fn method(link: &Link, f: Member) -> HostMember { HostMember::Method(function(link, f)) } +/// A member of a class with what `reflect` tells of it. +type Described = (String, HostMember, MemberInfo); + +/// A property's or a method's result's type for `reflect`. +fn typed(data_type: &str) -> MemberInfo { + MemberInfo { data_type: data_type.into(), ..MemberInfo::default() } +} + +/// A method's result's type and its arguments' names and types, for `reflect`. +fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { + let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect(); + MemberInfo { arguments, ..typed(data_type) } +} + /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document or page item `this` is still there. -fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { +fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -170,7 +191,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM } Err(HostError::Error(message.clone())) }); - (name.to_string(), HostMember::Property { get: f.clone(), set: f }) + (name.to_string(), HostMember::Property { get: f.clone(), set: f }, MemberInfo { unavailable: true, ..MemberInfo::default() }) } fn text(s: impl Into) -> Data { @@ -1765,12 +1786,30 @@ fn typename_of(name: &'static str) -> HostMember { HostMember::Get(Rc::new(move |_| Ok(text(name)))) } -fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option) -> HostClass { - HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None } +fn class(name: &str, parent: Option<&str>, members: Vec, index: Option) -> HostClass { + let info = members.iter().map(|(n, _, i)| (n.clone(), i.clone())).collect(); + let members = members.into_iter().map(|(n, m, _)| (n, m)).collect(); + HostClass { name: name.into(), parent: parent.map(Into::into), members, info, index, construct: None } } -fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> { - items.into_iter().map(|(n, m)| (n.to_string(), m)).collect() +fn named(items: Vec<(&str, HostMember, MemberInfo)>) -> Vec { + items.into_iter().map(|(n, m, i)| (n.to_string(), m, i)).collect() +} + +/// The type of a `DocumentPreset` field's value. +fn preset_type(field: &str) -> &'static str { + match field { + "artboardLayout" => "DocumentArtboardLayout", + "colorMode" => "DocumentColorSpace", + "documentBleedLink" => "boolean", + "documentBleedOffsetRect" => "Array", + "previewMode" => "DocumentPreviewMode", + "rasterResolution" => "DocumentRasterResolution", + "title" => "string", + "transparencyGrid" => "DocumentTransparencyGrid", + "units" => "RulerUnits", + _ => "number", + } } /// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings. @@ -1807,14 +1846,20 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))]) +} + +/// The classes of the object model, each member with the type `reflect` gives for it. +fn classes(link: &Link) -> Vec { let l = link; + let placement = [("relativeObject", "*"), ("insertionLocation", "ElementPlacement")]; let mut application = named(vec![ - ("typename", typename_of("Application")), - ("documents", get(l, app_documents)), - ("activeDocument", property(l, app_active, app_set_active)), - ("selection", get(l, app_selection)), - ("coordinateSystem", property(l, app_coords, app_set_coords)), - ("getIsFileOpen", method(l, app_is_open)), + ("typename", typename_of("Application"), typed("string")), + ("documents", get(l, app_documents), MemberInfo { collection: true, ..typed("Documents") }), + ("activeDocument", property(l, app_active, app_set_active), typed("Document")), + ("selection", get(l, app_selection), typed("*")), + ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), + ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), ]); application.push(later(l, "Application", "beep")); let preset = { @@ -1824,9 +1869,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), h.charge_call(64)?; new_preset(&h) }); - let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))]; - members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); - HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"), typed("string"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k))))); + HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) } }; let mut classes = vec![ class("Application", None, application, None), @@ -1835,29 +1880,52 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "Documents", None, named(vec![ - ("typename", typename_of("Documents")), - ("length", get(l, docs_length)), - ("parent", get(l, app_ref)), - ("index", method(l, docs_index)), - ("getByName", method(l, docs_by_name)), - ("add", method(l, docs_add)), - ("addDocument", method(l, docs_add_document)), + ("typename", typename_of("Documents"), typed("string")), + ("length", get(l, docs_length), typed("number")), + ("parent", get(l, app_ref), typed("Application")), + ("index", method(l, docs_index), returns("Document", &[("itemKey", "*")])), + ("getByName", method(l, docs_by_name), returns("Document", &[("name", "string")])), + ( + "add", + method(l, docs_add), + returns( + "Document", + &[ + ("colorSpace", "DocumentColorSpace"), + ("width", "number"), + ("height", "number"), + ("numArtBoards", "number"), + ("artboardLayout", "DocumentArtboardLayout"), + ("artboardSpacing", "number"), + ("artboardRowsOrCols", "number"), + ], + ), + ), + ( + "addDocument", + method(l, docs_add_document), + returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]), + ), ]), Some(function(l, docs_at)), ), ]; let mut document = named(vec![ - ("typename", get(l, doc_typename)), - ("parent", get(l, doc_parent)), - ("name", get(l, doc_name)), - ("width", get(l, doc_width)), - ("height", get(l, doc_height)), - ("rulerUnits", get(l, doc_units)), - ("documentColorSpace", get(l, doc_color_space)), - ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), - ("convertCoordinate", method(l, doc_convert)), - ("pageItems", get(l, doc_page_items)), - ("selection", property(l, doc_selection, doc_set_selection)), + ("typename", get(l, doc_typename), typed("string")), + ("parent", get(l, doc_parent), typed("Application")), + ("name", get(l, doc_name), typed("string")), + ("width", get(l, doc_width), typed("number")), + ("height", get(l, doc_height), typed("number")), + ("rulerUnits", get(l, doc_units), typed("RulerUnits")), + ("documentColorSpace", get(l, doc_color_space), typed("DocumentColorSpace")), + ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin), typed("Array")), + ( + "convertCoordinate", + method(l, doc_convert), + returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]), + ), + ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), + ("selection", property(l, doc_selection, doc_set_selection), typed("*")), ]); document.extend( ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] @@ -1869,38 +1937,44 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "PageItems", None, named(vec![ - ("typename", get(l, items_typename)), - ("length", get(l, items_length)), - ("parent", get(l, items_parent)), - ("index", method(l, items_index)), - ("getByName", method(l, items_by_name)), - ("removeAll", method(l, items_remove_all)), + ("typename", get(l, items_typename), typed("string")), + ("length", get(l, items_length), typed("number")), + ("parent", get(l, items_parent), typed("Document")), + ("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])), + ("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])), + ("removeAll", method(l, items_remove_all), returns("undefined", &[])), ]), Some(function(l, items_at)), )); let mut page_item = named(vec![ - ("typename", get(l, item_typename)), - ("parent", get(l, item_parent)), - ("name", property(l, item_name, item_set_name)), - ("note", property(l, item_note, item_set_note)), - ("hidden", property(l, item_hidden, item_set_hidden)), - ("locked", property(l, item_locked, item_set_locked)), - ("selected", property(l, item_selected, item_set_selected)), - ("opacity", property(l, item_opacity, item_set_opacity)), - ("position", property(l, item_position, item_set_position)), - ("left", property(l, item_left, item_set_left)), - ("top", property(l, item_top, item_set_top)), - ("width", property(l, item_width, item_set_width)), - ("height", property(l, item_height, item_set_height)), - ("geometricBounds", get(l, item_geometric)), - ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), - ("editable", get(l, item_editable)), - ("zOrderPosition", get(l, item_z_order_position)), - ("duplicate", method(l, item_duplicate)), - ("move", method(l, item_move)), - ("remove", method(l, item_remove)), - ("zOrder", method(l, item_z_order)), + ("typename", get(l, item_typename), typed("string")), + ("parent", get(l, item_parent), typed("*")), + ("name", property(l, item_name, item_set_name), typed("string")), + ("note", property(l, item_note, item_set_note), typed("string")), + ("hidden", property(l, item_hidden, item_set_hidden), typed("boolean")), + ("locked", property(l, item_locked, item_set_locked), typed("boolean")), + ("selected", property(l, item_selected, item_set_selected), typed("boolean")), + ("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }), + ("position", property(l, item_position, item_set_position), typed("Array")), + ("left", property(l, item_left, item_set_left), typed("number")), + ("top", property(l, item_top, item_set_top), typed("number")), + ("width", property(l, item_width, item_set_width), typed("number")), + ("height", property(l, item_height, item_set_height), typed("number")), + ("geometricBounds", get(l, item_geometric), typed("Array")), + ("visibleBounds", get(l, item_visible), typed("Array")), + ("controlBounds", get(l, item_visible), typed("Array")), + ("editable", get(l, item_editable), typed("boolean")), + ("zOrderPosition", get(l, item_z_order_position), typed("number")), + ("duplicate", method(l, item_duplicate), returns("PageItem", &placement)), + ("move", method(l, item_move), { + let mut info = returns("PageItem", &placement); + if let Some(at) = info.arguments.get_mut(1) { + at.default = Some(text("ElementPlacement.PLACEATBEGINNING")); + } + info + }), + ("remove", method(l, item_remove), returns("undefined", &[])), + ("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ]); page_item.extend( [ @@ -1928,8 +2002,13 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ); classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); - classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); - realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) + classes.push(class( + "Layer", + None, + named(vec![("typename", get(l, layer_typename), typed("string")), ("name", get(l, layer_name), typed("string"))]), + None, + )); + classes } #[cfg(test)] @@ -1944,4 +2023,107 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + + /// A script function that writes a reflection as one line, in the form [`expected_line`] gives. + const LINE: &str = "function line(r) {\ + function args(a) { var s = []; for (var i = 0; i < a.length; i++) s.push([a[i].name, a[i].type, a[i].dataType, a[i].defaultValue].join('=')); return s.join(','); }\ + function list(a) { var s = []; for (var i = 0; i < a.length; i++) { var e = a[i];\ + s.push([e.name, e.type, e.dataType, e.isCollection, e.min, e.max, e.defaultValue, args(e.arguments)].join(':')); } return s.join(' '); }\ + return r.name + '|' + list(r.properties) + '|' + list(r.methods); }"; + + fn shown(d: Option<&Data>) -> String { + match d { + None | Some(Data::Undefined) => String::new(), + Some(Data::String(s)) => s.clone(), + Some(Data::Number(n)) => n.to_string(), + Some(other) => panic!("no form for {other:?}"), + } + } + + /// The line [`LINE`] should write for `class`: its parents' members, then its own, a member it + /// declares again in its parent's place, without the members that are not available. + fn expected_line(classes: &[HostClass], class: &HostClass) -> String { + let mut chain = vec![class]; + while let Some(p) = chain.last().and_then(|c| c.parent.as_ref()) { + chain.push(classes.iter().find(|c| &c.name == p).unwrap_or_else(|| panic!("no class {p}"))); + } + let mut members: Vec<(String, &'static str, MemberInfo)> = Vec::new(); + for c in chain.iter().rev() { + for (name, member) in &c.members { + let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i.clone()).unwrap_or_default(); + let kind = match member { + HostMember::Get(_) => "readonly", + HostMember::Property { .. } => "readwrite", + HostMember::Method(_) => "method", + }; + match members.iter_mut().find(|(n, ..)| n == name) { + Some(slot) => *slot = (name.clone(), kind, info), + None => members.push((name.clone(), kind, info)), + } + } + } + members.retain(|(.., i)| !i.unavailable); + let one = |(name, kind, i): &(String, &str, MemberInfo)| { + let args: Vec = + i.arguments.iter().map(|a| format!("{}=parameter={}={}", a.name, a.data_type, shown(a.default.as_ref()))).collect(); + let number = |n: Option| n.map(|n| n.to_string()).unwrap_or_default(); + format!( + "{name}:{kind}:{}:{}:{}:{}:{}:{}", + i.data_type, + i.collection, + number(i.min), + number(i.max), + shown(i.default.as_ref()), + args.join(",") + ) + }; + let properties: Vec = members.iter().filter(|m| m.1 != "method").map(one).collect(); + let methods: Vec = members.iter().filter(|m| m.1 == "method").map(one).collect(); + format!("{}|{}|{}", class.name, properties.join(" "), methods.join(" ")) + } + + fn logged(s: &mut Session, source: &str) -> Vec { + let r = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().unwrap_or_else(|| panic!("{r}")).iter().map(|v| v.as_str().unwrap_or_default().to_string()).collect() + } + + #[test] + fn reflect_of_every_class_equals_its_declaration() { + let link = Link::default(); + let classes = classes(&link); + // Every member that is available declares its type, so `reflect` never answers `unknown`. + for c in &classes { + for (name, _) in &c.members { + let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i); + assert!(info.is_some_and(|i| i.unavailable || !i.data_type.is_empty()), "{}.{name} declares no type", c.name); + } + } + let mut s = Session::new(); + let logs: Vec = classes.iter().map(|c| format!("vc.log(line({}.reflect));", c.name)).collect(); + let script = format!("{LINE} {}", logs.join(" ")); + let got = logged(&mut s, &script); + let want: Vec = classes.iter().map(|c| expected_line(&classes, c)).collect(); + assert_eq!(got, want); + assert!(want.iter().any(|w| w.contains("insertionLocation=parameter=ElementPlacement=ElementPlacement.PLACEATBEGINNING"))); + } + + #[test] + fn reflect_of_an_object_equals_its_class_and_calls_no_member() { + let link = Link::default(); + let classes = classes(&link); + let want = |name: &str| expected_line(&classes, classes.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no class {name}"))); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap_or_else(|e| panic!("{e}")); + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap_or_else(|e| panic!("{e}")); + let script = format!( + "{LINE} var d = app.activeDocument, p = d.pageItems[0]; vc.log(line(app.reflect)); vc.log(line(app.documents.reflect));\ + vc.log(line(d.reflect)); vc.log(line(d.pageItems.reflect)); vc.log(line(p.reflect)); vc.log(line(new DocumentPreset().reflect));\ + p.remove(); vc.log(line(p.reflect)); vc.log(String(p.reflect.find('opacity').max));" + ); + let got = logged(&mut s, &script); + let path = want("PathItem"); + let expected = + [want("Application"), want("Documents"), want("Document"), want("PageItems"), path.clone(), want("DocumentPreset"), path, "100".into()]; + assert_eq!(got, expected); + } } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..4b3b95e517 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -45,7 +45,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), - ("Object.prototype.", "toSource"), + ("Object.prototype.", "reflect toSource"), ("localize.", "length"), ("toSource.", "length"), ( diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 94ee226d57..68eca8d657 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -1,6 +1,6 @@ //! The script extensions a host adds with [`crate::Realm::add_script_extensions`]: the global -//! `localize`, the global `toSource` and `Object.prototype.toSource`, and the getters behind -//! [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of +//! `localize`, the global `toSource` and `Object.prototype.toSource`, `Object.prototype.reflect` +//! ([`crate::reflect`]), and the getters behind [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of //! [`Localization`]. //! //! `toSource` writes primitives, arrays and plain objects as the text of a JavaScript expression @@ -96,7 +96,8 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { method(interp, global, "localize", localize, 1)?; method(interp, global, "toSource", to_source, 1)?; let object_proto = interp.intrinsics.object_proto; - method(interp, object_proto, "toSource", to_source_method, 0) + method(interp, object_proto, "toSource", to_source_method, 0)?; + crate::reflect::install(interp) } /// The text of the localization object `id` for the current locale: the string value of the first diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..2af2fc130f 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -17,6 +17,11 @@ //! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each //! array index `i` with it, called with `this` and the index, and `i in object` is true when it //! gives a value other than `undefined`; other names are looked up as usual. +//! +//! A script's `reflect` ([`crate::reflect`]) describes an object of a host class, and the class's +//! constructor, from the members installed here and their [`HostClass::info`], so what a script is +//! told always matches what the class has. A class that names a member twice, or describes a member +//! it does not have, is refused. use std::rc::Rc; @@ -40,6 +45,39 @@ pub enum HostMember { Method(HostFunction), } +/// What a script's `reflect` tells of a member of a host class ([`HostClass::info`]). The member's +/// name and whether it is read-only, read-write or a method come from the [`HostMember`] itself. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MemberInfo { + /// The type of the member's value, or of a method's result: `boolean`, `number`, `string`, a + /// class name, `*` for any type, `null` or `undefined`. Empty reads as `unknown`. + pub data_type: String, + pub description: Option, + pub help: Option, + /// The value an omitted value means. + pub default: Option, + pub min: Option, + pub max: Option, + /// The value, or a method's result, is a collection. + pub collection: bool, + /// A method's arguments, in order. + pub arguments: Vec, + /// The member is installed but throws when used: `reflect` leaves it out. + pub unavailable: bool, +} + +/// What a script's `reflect` tells of an argument of a host class's method ([`MemberInfo::arguments`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ArgInfo { + pub name: String, + /// As [`MemberInfo::data_type`]. + pub data_type: String, + pub description: Option, + pub default: Option, + pub min: Option, + pub max: Option, +} + /// A class [`crate::Realm::define_host_classes`] adds. #[derive(Clone)] pub struct HostClass { @@ -48,6 +86,9 @@ pub struct HostClass { /// class's prototype inherits from. pub parent: Option, pub members: Vec<(String, HostMember)>, + /// What `reflect` tells of the members, each under the name of one of `members`. A member + /// without an entry has the type `unknown` and nothing else. + pub info: Vec<(String, MemberInfo)>, /// What `object[i]` gives for an array index `i`. pub index: Option, /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. @@ -72,6 +113,26 @@ pub(crate) struct Entry { /// The class without a parent this class descends from (itself for such a class), as an index /// into the realm's classes. family: u32, + /// The parent class, as an index into the realm's classes. + parent: Option, + /// The class's own members as `reflect` lists them. + members: Rc<[Reflected]>, +} + +/// How a script may use a member of a host class. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Access { + ReadOnly, + ReadWrite, + Method, +} + +/// A member of a host class as `reflect` lists it. +#[derive(Clone, Debug)] +pub(crate) struct Reflected { + pub(crate) name: Rc, + pub(crate) access: Access, + pub(crate) info: MemberInfo, } impl Entry { @@ -168,6 +229,41 @@ impl Interp { self.host_classes.iter().any(|e| e.ctor == id) } + /// The name of the host class of `id`, when it is an object of a host class. + pub(crate) fn host_class_name(&self, id: ObjId) -> JsResult>> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + Ok(self.host_classes.get(h.class as usize).map(|e| e.name.clone())) + } + + /// The name and members of the host class of `id`, an object of the class or its constructor: + /// the members of its parents first, then its own, a member a class declares again in the place + /// of its parent's. Members marked [`MemberInfo::unavailable`] are left out. `None` when `id` is + /// neither. + pub(crate) fn host_class_members(&self, id: ObjId) -> JsResult, Vec)>> { + let class = match &self.object(id)?.class { + Class::Host(h) => Some(h.class as usize), + _ => self.host_classes.iter().position(|e| e.ctor == id), + }; + let Some(class) = class else { return Ok(None) }; + let Some(entry) = self.host_classes.get(class) else { return Err(Abrupt::Internal("host class out of range".into())) }; + let mut chain = vec![entry]; + while let Some(p) = chain.last().and_then(|e| e.parent) { + let Some(parent) = self.host_classes.get(p as usize) else { return Err(Abrupt::Internal("host class out of range".into())) }; + chain.push(parent); + } + let mut out: Vec = Vec::new(); + for e in chain.iter().rev() { + for m in e.members.iter() { + match out.iter_mut().find(|r| r.name == m.name) { + Some(slot) => *slot = m.clone(), + None => out.push(m.clone()), + } + } + } + out.retain(|m| !m.info.unavailable); + Ok(Some((entry.name.clone(), out))) + } + /// The indexer of the host class of `id`, when it is an object of a host class that has one. pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult> { let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; @@ -223,24 +319,57 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); } let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); - let (parent, family) = match &class.parent { - None => (i.intrinsics.object_proto, own), - Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { - Some(e) => (e.proto, e.family), + let (parent, family, parent_index) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((n, e)) => (e.proto, e.family, Some(u32::try_from(n).unwrap_or(u32::MAX))), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; + let members = match reflected_members(&class) { + Ok(m) => m, + Err(message) => return Err(i.throw(ErrorType::Type, &message)), + }; let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); let mark = i.temp_roots.len(); i.temp_roots.push(Value::Object(proto)); let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family, parent: parent_index, members }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } +/// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the +/// error's message when a member is named twice, or an entry names no member or is given twice. +fn reflected_members(class: &HostClass) -> Result, String> { + let mut out: Vec = Vec::with_capacity(class.members.len()); + for (name, member) in &class.members { + if out.iter().any(|r| *r.name == **name) { + return Err(format!("the host class {} names the member {name} twice", class.name)); + } + let access = match member { + HostMember::Get(_) => Access::ReadOnly, + HostMember::Property { .. } => Access::ReadWrite, + HostMember::Method(_) => Access::Method, + }; + out.push(Reflected { name: name.as_str().into(), access, info: MemberInfo::default() }); + } + let mut seen: Vec<&str> = Vec::with_capacity(class.info.len()); + for (name, info) in &class.info { + if seen.contains(&name.as_str()) { + return Err(format!("the host class {} describes the member {name} twice", class.name)); + } + seen.push(name); + let Some(slot) = out.iter_mut().find(|r| *r.name == **name) else { + return Err(format!("the host class {} describes {name}, which is not one of its members", class.name)); + }; + slot.info = info.clone(); + } + Ok(out.into()) +} + /// Puts the members of `class` on `proto` and makes its constructor. → the constructor. fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult { let path = &class.name; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..040361d460 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -644,7 +644,7 @@ fn with_thing(r: &mut Realm, make: Option) { let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }); let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number))); let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))]; - let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make }; + let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: make }; r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..8d61712e36 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -65,6 +65,7 @@ mod number; mod number_builtins; mod parser; mod realm; +mod reflect; mod regexp; mod regexp_builtins; mod regexp_vm; @@ -82,10 +83,11 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; -pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; +pub use host_classes::{ArgInfo, HOST_REF_KEY, HostClass, HostMember, MemberInfo, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; +pub use reflect::MAX_REFLECTED_MEMBERS; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -211,6 +213,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod reflect_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index f1ca6b570d..745c2b9364 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -539,7 +539,9 @@ impl Realm { /// Adds the script extensions: the global `localize(object, ...values)`, which gives a /// localization object's text for the locale of [`Realm::localization`], the global /// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text, - /// and the localized `Object.prototype.toString` while [`crate::Localization::enabled`]. + /// `Object.prototype.reflect`, which describes an object's properties and methods (a host + /// class's from its [`crate::HostClass`]), and the localized `Object.prototype.toString` while + /// [`crate::Localization::enabled`]. pub fn add_script_extensions(&mut self) -> Result<(), RunError> { match crate::builtins::extensions::install(&mut self.interp) { Ok(()) => Ok(()), diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs new file mode 100644 index 0000000000..a84c221d3a --- /dev/null +++ b/crates/js/src/reflect.rs @@ -0,0 +1,331 @@ +//! The script extension `reflect` ([`crate::Realm::add_script_extensions`]): a read-only property +//! of `Object.prototype` that gives, on each read, a new reflection object describing the object it +//! is read on. +//! +//! A reflection object has `name` (the object's class), `description` and `help` (`undefined`), +//! `properties` and `methods` (arrays of ReflectionInfo objects), and `find(name)`, which gives the +//! ReflectionInfo of the property or method with that name, or `null`. A ReflectionInfo has `name` +//! (a string, or a number for an array index), `description`, `help`, `type` (`readonly`, +//! `readwrite`, `method`, or `parameter` for a method's argument), `dataType`, `defaultValue`, +//! `min`, `max`, `isCollection` and `arguments` (an array of ReflectionInfo objects, empty for a +//! property). Each entry of `properties`, `methods` and `arguments` is also under its name when +//! that name is not an array index or `length`. +//! +//! An object of a host class and the class's constructor are described by the class's members +//! ([`crate::HostClass::members`] and [`crate::HostClass::info`]), its parents' included. Any other +//! object is described by its own properties: a property whose value is a function is a method, +//! with the parameter names of a function written in JavaScript as its arguments; a data property +//! is read-write when it is writable and gives the type of its value; an accessor is read-write +//! when it has a setter and its type is `unknown`. A string, number or boolean is described by its +//! prototype's own properties. No getter or other script code runs. +//! +//! Every object made is frozen, so a script cannot change one; `reflect` itself has no setter. +//! Each member described takes fuel, and an object with more than [`MAX_REFLECTED_MEMBERS`] +//! members and arguments throws a `RangeError`. + +use crate::builtins::native; +use crate::heap::{Class, ENUMERABLE, Func, Key, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, WRITABLE, key}; +use crate::host::Data; +use crate::host_classes::{Access, Reflected}; +use crate::interp::{ErrorType, Interp, JsResult}; +use crate::value::{Str, Value, array_index, index_key, number_to_str}; + +/// The most members and arguments `reflect` describes for one object. +pub const MAX_REFLECTED_MEMBERS: usize = 10_000; + +/// The properties of a ReflectionInfo object. +const INFO_PROPS: usize = 10; + +/// A member or argument as a ReflectionInfo object describes it. +struct Info { + name: Value, + kind: &'static str, + data_type: String, + description: Option, + help: Option, + default: Option, + min: Option, + max: Option, + collection: bool, + arguments: Vec, +} + +impl Info { + fn new(name: Value, kind: &'static str, data_type: &str) -> Self { + Self { + name, + kind, + data_type: data_type.to_string(), + description: None, + help: None, + default: None, + min: None, + max: None, + collection: false, + arguments: Vec::new(), + } + } +} + +/// The type a [`crate::MemberInfo`] gives, `unknown` when it gives none. +fn declared(data_type: &str) -> &str { + if data_type.is_empty() { "unknown" } else { data_type } +} + +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let get = native(interp, "reflect", reflect, 0, NativeKind::Plain, false)?; + let object_proto = interp.intrinsics.object_proto; + interp.define(object_proto, key("reflect"), Prop::Accessor { get: Some(get), set: None, flags: 0 }) +} + +/// Counts one more member or argument against [`MAX_REFLECTED_MEMBERS`], with a unit of fuel. +fn count(interp: &mut Interp, total: &mut usize) -> JsResult<()> { + interp.use_fuel()?; + *total += 1; + if *total > MAX_REFLECTED_MEMBERS { + return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members"))); + } + Ok(()) +} + +/// The getter of `Object.prototype.reflect`. +fn reflect(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (id, primitive) = match &this { + Value::Undefined | Value::Null => return Err(interp.type_error("reflect needs an object")), + Value::String(_) => (interp.intrinsics.string_proto, Some("String")), + Value::Number(_) => (interp.intrinsics.number_proto, Some("Number")), + Value::Bool(_) => (interp.intrinsics.boolean_proto, Some("Boolean")), + Value::Object(o) => (*o, None), + }; + let (name, properties, methods) = match interp.host_class_members(id)? { + Some((name, members)) if primitive.is_none() => { + let (properties, methods) = host_infos(interp, &members)?; + (name.to_string(), properties, methods) + } + _ => { + let name = primitive.unwrap_or(interp.object(id)?.class.name()).to_string(); + let (properties, methods) = own_infos(interp, id)?; + (name, properties, methods) + } + }; + interp.rooted(&[this], |i| { + let mark = i.temp_roots.len(); + let r = reflection(i, &name, &properties, &methods); + i.temp_roots.truncate(mark); + r + }) +} + +/// The properties and methods of a host class's `members`. +fn host_infos(interp: &mut Interp, members: &[Reflected]) -> JsResult<(Vec, Vec)> { + let (mut properties, mut methods) = (Vec::new(), Vec::new()); + let mut total = 0; + for m in members { + count(interp, &mut total)?; + let kind = match m.access { + Access::ReadOnly => "readonly", + Access::ReadWrite => "readwrite", + Access::Method => "method", + }; + let mut info = Info::new(Value::str(&m.name), kind, declared(&m.info.data_type)); + info.description = m.info.description.clone(); + info.help = m.info.help.clone(); + info.default = m.info.default.clone(); + info.min = m.info.min; + info.max = m.info.max; + info.collection = m.info.collection; + for a in &m.info.arguments { + count(interp, &mut total)?; + let mut arg = Info::new(Value::str(&a.name), "parameter", declared(&a.data_type)); + arg.description = a.description.clone(); + arg.default = a.default.clone(); + arg.min = a.min; + arg.max = a.max; + info.arguments.push(arg); + } + if m.access == Access::Method { methods.push(info) } else { properties.push(info) } + } + Ok((properties, methods)) +} + +/// The properties and methods of the own properties of `id`. No getter runs. +fn own_infos(interp: &mut Interp, id: ObjId) -> JsResult<(Vec, Vec)> { + let o = interp.object(id)?; + let extra = match &o.class { + Class::String(s) => s.len().saturating_add(1), + Class::Array { .. } => 1, + _ => 0, + }; + // Checked before the names are listed, so a huge object costs no more than a small one. + if o.props.len().saturating_add(extra) > MAX_REFLECTED_MEMBERS { + return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members"))); + } + let keys = interp.own_keys(id)?; + let (mut properties, mut methods) = (Vec::new(), Vec::new()); + let mut total = 0; + for k in keys { + count(interp, &mut total)?; + let Some(prop) = interp.get_own_property(id, &k)? else { continue }; + let name = member_name(&k); + match prop { + Prop::Data { value, .. } if interp.is_callable(&value) => { + let mut info = Info::new(name, "method", "unknown"); + if let Some(params) = parameters(interp, &value)? { + for p in params { + count(interp, &mut total)?; + info.arguments.push(Info::new(Value::String(Str::from_rc(p)), "parameter", "*")); + } + } + methods.push(info); + } + Prop::Data { value, flags } => { + let kind = if flags & WRITABLE != 0 { "readwrite" } else { "readonly" }; + let data_type = value_type(interp, &value)?; + properties.push(Info::new(name, kind, &data_type)); + } + Prop::Accessor { set, .. } => properties.push(Info::new(name, if set.is_some() { "readwrite" } else { "readonly" }, "unknown")), + } + } + Ok((properties, methods)) +} + +/// A property name as a ReflectionInfo's `name`: a number for an array index. +fn member_name(k: &Key) -> Value { + match array_index(k) { + Some(i) => Value::Number(f64::from(i)), + None => Value::String(Str::from_rc(k.clone())), + } +} + +/// The parameter names of the function `f` when it is written in JavaScript. +fn parameters(interp: &Interp, f: &Value) -> JsResult>> { + let Some(id) = f.as_object() else { return Ok(None) }; + Ok(match &interp.object(id)?.class { + Class::Function(Func::Closure { code, .. }) => Some(code.params.clone()), + _ => None, + }) +} + +/// The `dataType` of a data property holding `v`. +fn value_type(interp: &Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => "undefined".into(), + Value::Null => "null".into(), + Value::Bool(_) => "boolean".into(), + Value::Number(_) => "number".into(), + Value::String(_) => "string".into(), + Value::Object(o) => match interp.host_class_name(*o)? { + Some(name) => name.to_string(), + None => interp.object(*o)?.class.name().into(), + }, + }) +} + +/// The reflection object. Every object it makes is kept in `interp.temp_roots`. +fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[Info]) -> JsResult { + let properties = info_array(interp, properties)?; + let methods = info_array(interp, methods)?; + interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?; + let find = native(interp, "find", find, 1, NativeKind::Plain, false)?; + interp.temp_roots.push(Value::Object(find)); + let r = interp.new_object(); + interp.temp_roots.push(Value::Object(r)); + for (k, v) in [ + ("name", Value::str(name)), + ("description", Value::Undefined), + ("help", Value::Undefined), + ("properties", Value::Object(properties)), + ("methods", Value::Object(methods)), + ] { + interp.define(r, key(k), Prop::Data { value: v, flags: ENUMERABLE })?; + } + interp.define(r, key("find"), Prop::Data { value: Value::Object(find), flags: 0 })?; + interp.object_mut(r)?.extensible = false; + Ok(Value::Object(r)) +} + +/// A frozen array of ReflectionInfo objects for `infos`, each also under its name when that name +/// is not an array index or `length`. +fn info_array(interp: &mut Interp, infos: &[Info]) -> JsResult { + interp.reserve_heap(OBJECT_BYTES.saturating_add(infos.len().saturating_mul(2 * PROP_BYTES)))?; + let proto = interp.intrinsics.array_proto; + let a = interp.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: false }, Some(proto))); + interp.temp_roots.push(Value::Object(a)); + for (n, info) in infos.iter().enumerate() { + let o = info_object(interp, info)?; + interp.define(a, index_key(u32::try_from(n).unwrap_or(u32::MAX)), Prop::Data { value: Value::Object(o), flags: ENUMERABLE })?; + } + for (n, info) in infos.iter().enumerate() { + let Value::String(s) = &info.name else { continue }; + let k = s.flat(); + if array_index(&k).is_some() || *k == *key("length") || interp.object(a)?.props.contains(&k) { + continue; + } + let Some(Prop::Data { value, .. }) = interp.get_own_property(a, &index_key(u32::try_from(n).unwrap_or(u32::MAX)))? else { continue }; + interp.define(a, k, Prop::Data { value, flags: 0 })?; + } + interp.object_mut(a)?.extensible = false; + Ok(a) +} + +/// A frozen ReflectionInfo object for `info`. +fn info_object(interp: &mut Interp, info: &Info) -> JsResult { + let arguments = info_array(interp, &info.arguments)?; + interp.reserve_heap(OBJECT_BYTES + INFO_PROPS * PROP_BYTES)?; + let o = interp.new_object(); + interp.temp_roots.push(Value::Object(o)); + let text = |s: &Option| s.as_deref().map_or(Value::Undefined, Value::str); + let number = |n: Option| n.map_or(Value::Undefined, Value::Number); + let default = match &info.default { + Some(d) => interp.write_data(d.clone(), 0, true)?, + None => Value::Undefined, + }; + let fields = [ + ("name", info.name.clone()), + ("description", text(&info.description)), + ("help", text(&info.help)), + ("type", Value::str(info.kind)), + ("dataType", Value::str(&info.data_type)), + ("defaultValue", default), + ("min", number(info.min)), + ("max", number(info.max)), + ("isCollection", Value::Bool(info.collection)), + ("arguments", Value::Object(arguments)), + ]; + for (k, v) in fields { + interp.define(o, key(k), Prop::Data { value: v, flags: ENUMERABLE })?; + } + interp.object_mut(o)?.extensible = false; + Ok(o) +} + +/// `reflect.find(name)`: the ReflectionInfo of the property, or else the method, named `name` (a +/// string, or a number for an array index), or `null`. +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let wanted = match args.first() { + Some(Value::String(s)) => s.flat(), + Some(Value::Number(n)) => number_to_str(*n).flat(), + _ => return Err(interp.type_error("reflect.find: give the member's name, as a string or a number")), + }; + let not_reflection = "reflect.find must be called on a reflection object"; + let Value::Object(r) = this else { return Err(interp.type_error(not_reflection)) }; + for list in ["properties", "methods"] { + let Some(Prop::Data { value: Value::Object(a), .. }) = interp.get_own_property(r, &key(list))? else { + return Err(interp.type_error(not_reflection)); + }; + let Class::Array { length, .. } = interp.object(a)?.class else { return Err(interp.type_error(not_reflection)) }; + for i in 0..length { + interp.use_fuel()?; + let Some(Prop::Data { value: Value::Object(e), .. }) = interp.get_own_property(a, &index_key(i))? else { continue }; + let name = match interp.get_own_property(e, &key("name"))? { + Some(Prop::Data { value: Value::String(s), .. }) => s.flat(), + Some(Prop::Data { value: Value::Number(n), .. }) => number_to_str(n).flat(), + _ => continue, + }; + if *name == *wanted { + return Ok(Value::Object(e)); + } + } + } + Ok(Value::Null) +} diff --git a/crates/js/src/reflect_tests.rs b/crates/js/src/reflect_tests.rs new file mode 100644 index 0000000000..3e8827cf4f --- /dev/null +++ b/crates/js/src/reflect_tests.rs @@ -0,0 +1,242 @@ +//! `reflect`: the description of an object's properties and methods, from a host class's members +//! or from an object's own properties. + +use std::rc::Rc; + +use super::*; + +fn realm() -> Realm { + let mut r = Realm::new(); + r.add_script_extensions().unwrap(); + r +} + +fn text(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Ok(JsValue::String(s)) => s, + other => panic!("{source}: {other:?}"), + } +} + +fn thrown(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Err(e) if e.kind == RunErrorKind::Thrown => e.message, + other => panic!("{source}: {other:?}"), + } +} + +/// `name:type:dataType` of each entry of a list, joined with spaces. +const LIST: &str = "function list(a) { var s = []; for (var i = 0; i < a.length; i++) s.push(a[i].name + ':' + a[i].type + ':' + a[i].dataType); \ + return s.join(' '); }"; + +#[test] +fn a_script_object_lists_its_own_properties_and_methods_without_running_getters() { + let mut r = realm(); + let setup = "var o = {a: 1, b: 'x', c: null, d: [1], f: function (p, q) {}, get g() { throw new Error('ran'); }, set h(v) {}};\ + Object.defineProperty(o, 'k', {value: true, writable: false});"; + r.run(setup).unwrap(); + r.run(LIST).unwrap(); + assert_eq!(text(&mut r, "o.reflect.name"), "Object"); + assert_eq!( + text(&mut r, "list(o.reflect.properties)"), + "a:readwrite:number b:readwrite:string c:readwrite:null d:readwrite:Array g:readonly:unknown h:readwrite:unknown k:readonly:boolean" + ); + assert_eq!(text(&mut r, "list(o.reflect.methods)"), "f:method:unknown"); + assert_eq!(text(&mut r, "list(o.reflect.methods[0].arguments)"), "p:parameter:* q:parameter:*"); + assert_eq!(text(&mut r, "list(o.reflect.properties[0].arguments) + '|' + o.reflect.description + '|' + o.reflect.help"), "|undefined|undefined"); + // A value replaced by a function becomes a method on the next read; each read is a new snapshot. + assert_eq!( + text(&mut r, "var before = o.reflect; o.a = function () {}; delete o.b; list(before.methods) + '|' + list(o.reflect.methods)"), + "f:method:unknown|a:method:unknown f:method:unknown" + ); + assert_eq!(text(&mut r, "String(o.reflect.find('b'))"), "null"); +} + +#[test] +fn find_and_names_look_up_properties_then_methods() { + let mut r = realm(); + r.run("var o = {width: 2, draw: function () {}};").unwrap(); + assert_eq!(text(&mut r, "o.reflect.find('width').dataType + ' ' + o.reflect.find('draw').type"), "number method"); + assert_eq!(text(&mut r, "String(o.reflect.find('nothing'))"), "null"); + assert_eq!(text(&mut r, "o.reflect.properties.width.name + ' ' + o.reflect.methods.draw.name"), "width draw"); + // Array indexes are numbers, found by number or by their text. + assert_eq!( + text( + &mut r, + "var a = [5, 'x']; a[3] = true; var f = a.reflect.find(1); typeof f.name + ' ' + f.dataType + ' ' + a.reflect.find('3').dataType" + ), + "number string boolean" + ); + assert_eq!(text(&mut r, "[5].reflect.properties.length + ' ' + [5].reflect.find('length').type"), "2 readwrite"); + // A name that is missing or of another type is refused. + assert!(thrown(&mut r, "o.reflect.find();").starts_with("TypeError")); + assert!(thrown(&mut r, "o.reflect.find({});").starts_with("TypeError")); + assert!(thrown(&mut r, "o.reflect.find.call({}, 'width');").starts_with("TypeError")); +} + +#[test] +fn a_reflection_info_has_every_field() { + let mut r = realm(); + let fields = "var i = ({a: 1}).reflect.properties[0]; var k = []; for (var n in i) k.push(n); k.join(' ')"; + assert_eq!(text(&mut r, fields), "name description help type dataType defaultValue min max isCollection arguments"); + let values = + "var i = ({a: 1}).reflect.properties[0]; [i.description, i.help, i.defaultValue, i.min, i.max, i.isCollection, i.arguments.length].join()"; + assert_eq!(text(&mut r, values), ",,,,,false,0"); + assert_eq!(text(&mut r, "var k = []; for (var n in ({}).reflect) k.push(n); k.join(' ')"), "name description help properties methods"); +} + +#[test] +fn functions_primitives_and_built_ins_are_described() { + let mut r = realm(); + r.run(LIST).unwrap(); + assert_eq!( + text(&mut r, "function f(a, b) {} f.reflect.name + ' ' + list(f.reflect.properties)"), + "Function length:readonly:number prototype:readwrite:Object" + ); + assert_eq!(text(&mut r, "Math.reflect.name + ' ' + Math.reflect.find('PI').type + ' ' + Math.reflect.find('max').type"), "Math readonly method"); + assert_eq!(text(&mut r, "'abc'.reflect.name + ' ' + 'abc'.reflect.find('charAt').type"), "String method"); + assert_eq!(text(&mut r, "(5).reflect.name + ' ' + true.reflect.name"), "Number Boolean"); + assert!(thrown(&mut r, "var n = null; n.reflect;").starts_with("TypeError")); + let getter = "Object.getOwnPropertyDescriptor(Object.prototype, 'reflect').get"; + assert!(thrown(&mut r, &format!("{getter}.call(undefined);")).starts_with("TypeError")); + // Neither a getter nor `toString` runs, so a cyclic object is described as it is. + assert_eq!(text(&mut r, "var c = {}; c.self = c; c.toString = function () { throw 1; }; c.reflect.find('self').dataType"), "Object"); +} + +#[test] +fn a_reflection_cannot_be_changed() { + let mut r = realm(); + r.run("var o = {a: 1}; var x = o.reflect;").unwrap(); + // Outside strict mode the writes are ignored. + let tries = "o.reflect = 5; x.name = 'y'; x.properties[0].dataType = 'y'; x.properties[1] = 2; x.extra = 1; delete x.methods;\ + [typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()"; + assert_eq!(text(&mut r, tries), "object,Object,number,1,,object"); + // In strict mode each one throws a TypeError. + for write in ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find"] { + assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}"); + } + assert_eq!( + text(&mut r, "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments)"), + "true true true" + ); +} + +#[test] +fn a_very_wide_object_is_refused() { + let mut r = realm(); + let wide = |n: usize| format!("var w = {{}}; for (var i = 0; i < {n}; i++) w['p' + i] = i;"); + r.run(&wide(MAX_REFLECTED_MEMBERS)).unwrap(); + assert_eq!(text(&mut r, "String(w.reflect.properties.length)"), MAX_REFLECTED_MEMBERS.to_string()); + r.run(&wide(MAX_REFLECTED_MEMBERS + 1)).unwrap(); + assert!(thrown(&mut r, "w.reflect;").starts_with("RangeError")); + // A function with too many parameters is counted with the members. + let params = (0..MAX_REFLECTED_MEMBERS).map(|i| format!("a{i}")).collect::>().join(","); + assert!(thrown(&mut r, &format!("({{f: function ({params}) {{}}}}).reflect;")).starts_with("RangeError")); +} + +fn constant(value: f64) -> HostFunction { + Rc::new(move |_| Ok(Data::Number(value))) +} + +/// `Item` with `size` (read-write, 1 to 10, default 5), `kind` and the method `fit(target, +/// margin?)`; and `Box`, a child that declares `kind` again as a method and adds `cut`, which is +/// not available. +fn classes() -> Vec { + let item = HostClass { + name: "Item".into(), + parent: None, + members: vec![ + ("size".into(), HostMember::Property { get: constant(5.0), set: constant(0.0) }), + ("kind".into(), HostMember::Get(constant(1.0))), + ("fit".into(), HostMember::Method(constant(2.0))), + ], + info: vec![ + ( + "size".into(), + MemberInfo { + data_type: "number".into(), + description: Some("The size.".into()), + help: Some("How large the item is.".into()), + default: Some(Data::Number(5.0)), + min: Some(1.0), + max: Some(10.0), + ..MemberInfo::default() + }, + ), + ( + "fit".into(), + MemberInfo { + data_type: "boolean".into(), + collection: true, + arguments: vec![ + ArgInfo { name: "target".into(), data_type: "Item".into(), ..ArgInfo::default() }, + ArgInfo { + name: "margin".into(), + data_type: "number".into(), + default: Some(Data::Number(0.0)), + min: Some(0.0), + ..ArgInfo::default() + }, + ], + ..MemberInfo::default() + }, + ), + ], + index: None, + construct: None, + }; + let child = HostClass { + name: "Box".into(), + parent: Some("Item".into()), + members: vec![("kind".into(), HostMember::Method(constant(3.0))), ("cut".into(), HostMember::Method(constant(4.0)))], + info: vec![("cut".into(), MemberInfo { unavailable: true, ..MemberInfo::default() })], + index: None, + construct: None, + }; + vec![item, child] +} + +#[test] +fn a_host_class_is_described_by_its_members_and_their_info() { + let mut r = realm(); + r.define_host_classes(classes(), vec![("item".into(), host_ref("Item", &[1.0])), ("box".into(), host_ref("Box", &[2.0]))]).unwrap(); + r.run(LIST).unwrap(); + for target in ["item", "Item"] { + assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Item"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number kind:readonly:unknown"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "fit:method:boolean"); + } + let size = "var s = item.reflect.find('size'); [s.description, s.help, s.defaultValue, s.min, s.max, s.isCollection].join('|')"; + assert_eq!(text(&mut r, size), "The size.|How large the item is.|5|1|10|false"); + let fit = "var f = item.reflect.find('fit'); f.isCollection + ' ' + list(f.arguments) + ' ' + f.arguments.margin.defaultValue + ' ' + f.arguments[1].min"; + assert_eq!(text(&mut r, fit), "true target:parameter:Item margin:parameter:number 0 0"); + // The child lists its parent's members first, its own declaration of one in its place, and + // leaves out the member that is not available. + for target in ["box", "Box"] { + assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Box"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "kind:method:unknown fit:method:boolean"); + assert_eq!(text(&mut r, &format!("String({target}.reflect.find('cut'))")), "null"); + } + // No member's function ran: a data property of the class's type names it. + assert_eq!(text(&mut r, "({b: box}).reflect.find('b').dataType"), "Box"); +} + +#[test] +fn info_for_a_member_a_class_does_not_have_is_refused() { + for (info, message) in [ + (vec![("nothing".to_string(), MemberInfo::default())], "not one of its members"), + (vec![("size".to_string(), MemberInfo::default()), ("size".to_string(), MemberInfo::default())], "twice"), + ] { + let mut r = realm(); + let mut class = classes().remove(0); + class.info = info; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains(message), "{}", e.message); + } + let mut r = realm(); + let mut class = classes().remove(0); + class.members.push(("size".into(), HostMember::Get(constant(1.0)))); + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains("names the member size twice"), "{}", e.message); +} diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..1e61b47bf5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -174,7 +174,7 @@ features! { Notify "notify" Language, OperatorOverloading "operatorOverloading" HostOnly, Preferences "preferences" Language, - Reflection "reflection" HostOnly, + Reflection "reflection" Language, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, ScriptuiPalette "scriptui.palette" HostOnly, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..ac75fb0256 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -212,6 +212,13 @@ fn directives_are_read_at_the_start_of_a_line_in_both_forms() { assert_eq!(r.needs, [Need::Language], "VectorCraft runs #targetengine"); } +#[test] +fn reflection_needs_only_the_language() { + let r = report("var p = obj.reflect.properties;\nvar m = $.reflect.find('write');\n"); + assert_eq!(feature(&r, "reflection").map(|f| f.lines.clone()), Some(vec![1, 2])); + assert_eq!(r.needs, [Need::Language], "VectorCraft runs reflect"); +} + #[test] fn a_byte_order_mark_and_every_line_break_are_read() { // U+2028 ends line 2. diff --git a/docs/mcp.md b/docs/mcp.md index 51cd09fdbb..eff8b953f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2540,9 +2540,9 @@ top-level `import` or `export`, such as a React `.jsx` file), `notText` (a NUL b control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, the reply holds these lists: - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects - and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's + and directives, such as `$`, `alert`, `UnitValue`, `reflect`, `#target` and `#targetengine`), `dom` (the reference app's document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: - palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions + palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, actions and `selectTool`). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and @@ -2794,6 +2794,22 @@ itself throws a `TypeError`. So does a property that is not writable or not conf would make each of them writable, configurable and extensible again (VectorCraft's own rule). A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 characters throws a `RangeError`. +`value.reflect` describes an object, as the reflection interface page lays out +(https://extendscript.docsforadobe.dev/extendscript-tools-features/extendscript-reflection-interface/). Each read +gives a new frozen object with `name` (the class), `description` and `help` (`undefined`), `properties` and +`methods` (arrays of entries), and `find(name)`, which gives the entry of the property, or else the method, with that +name, or `null`; a name that is not a string or a number throws a `TypeError`. Each entry has `name` (a number for an +array index), `description`, `help`, `type` (`readonly`, `readwrite`, `method`, or `parameter` for an argument), +`dataType`, `defaultValue`, `min`, `max`, `isCollection` and `arguments`; an entry is also under its name in its array +when that name is not an array index or `length`. `app`, its documents, page items and layers, `DocumentPreset` and +each class's constructor list the members of their class and its parents, with the types, bounds, defaults and method +arguments the object model declares for them (VectorCraft's own values); members that are not available yet are left +out. Any other object lists its own properties: a function value is a method, with a JavaScript function's parameter +names as its arguments, a data property gives the type of its value, and an accessor gives `unknown`. A string, number +or boolean lists its prototype's own properties. No getter runs. `reflect` has no setter, and nothing in a reflection +can be changed: a write is ignored, or throws a `TypeError` in strict mode. An object with more than 10,000 members +and arguments throws a `RangeError`. + The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A run that changes no document adds no undo step. The journal records each command the run finished, as it records commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..762fde881d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,6 +1029,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. + - Scripts: every object has a read-only `reflect` property (https://extendscript.docsforadobe.dev/extendscript-tools-features/extendscript-reflection-interface/) that gives its class name, its properties and methods with their types, access, bounds, defaults and method arguments, and `find(name)`. `app`, its documents and page items and their classes are described from the declarations that install their members, and any other object from its own properties, without running a getter. `script.check` no longer counts it as host-only. `crates/js/src/reflect_tests.rs`, `crates/engine/src/script/dom.rs`. - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`). - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. From 9e6c315689cbb59d9ae67a6cba04385fb3e34e1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:36:43 -0800 Subject: [PATCH 07/68] Scripts: selection, controlBounds, Revert and preset limits in the object model - Document.selection = undefined throws a TypeError and keeps the selection; null and [] still clear it. The assignment finds the locked artboards once and drops repeated objects with a set. - PageItem.controlBounds is the visible bounds widened to take in the direction points of every path in the object. - A page item or layer handle carries the document's revert count, so an object read before file.revert throws Stale page item. - Restoring a selection gives a path with only segments selected no anchors of its own before its segments are added back. - A failed object-model call and a vc.run result that cannot reach the script put back the growth they were charged. - DocumentPreset values count against the run's heap by what they hold now; an assignment past it throws a RangeError. - A host class member named constructor is refused, and reflect's find function is frozen. - file.new keeps the stored columns while rows are set, so a change of spacing alone no longer changes the grid a later layout uses. - command_value passes the id and params through without copying them. - Tests: the getIsFileOpen test passes its paths as JSON strings, and the locked removeAll test checks both objects from inside the script. --- crates/engine/src/cmd/newdoc.rs | 5 +- crates/engine/src/script/dom.rs | 139 ++++++++++++++++++------- crates/engine/src/script/mod.rs | 29 ++++-- crates/engine/src/tests/script_dom.rs | 143 ++++++++++++++++++++++++-- crates/js/src/host_classes.rs | 4 + crates/js/src/reflect.rs | 1 + crates/js/src/reflect_tests.rs | 20 +++- docs/mcp.md | 14 +-- 8 files changed, 295 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index fb26b13c68..0a5ed93ba3 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -394,9 +394,8 @@ impl DocSettings { if (o.contains_key("columns") && !o.contains_key("rows")) || self.layout != ArtboardLayout::GridByColumn { self.rows = 0; } - if self.grid_rows().is_some() { - self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); - } + // While rows are set, `grid_columns` gives the columns they make; the stored columns stay as + // they were given, and are the ones a later layout without rows uses. Ok(()) } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 6fda66efe1..0753cc5263 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -6,9 +6,10 @@ //! describe them. //! //! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the -//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the -//! document and the object up again. An object that was deleted, a document that was closed and an -//! object from an earlier run of a named engine throw an error on every member. Every change runs +//! document's [`crate::DocState::uid`] and, for art and layers, the document's +//! [`crate::DocState::reverts`] and the object's id, and every read looks the document and the +//! object up again. An object that was deleted, a document that was closed, an object from before +//! File › Revert and an object from an earlier run of a named engine throw an error on every member. Every change runs //! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each //! changed document; a change that changes nothing runs no command. A change to a document that is //! not the active one makes it active for the command and makes the other one active again after. @@ -24,7 +25,9 @@ //! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object -//! must be one of that document's that can be selected, or nothing changes. +//! must be one of that document's that can be selected, or nothing changes. `undefined` throws. +//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path +//! in the object. //! - Members the help pages list that are not here yet throw an error that says so, and `reflect` //! leaves them out. //! - `reflect` on an object or a class gives each member's type from the declaration that installs @@ -33,6 +36,7 @@ //! more than one type. use std::cell::{Cell, RefCell}; +use std::collections::HashSet; use std::rc::Rc; use std::sync::Arc; @@ -93,16 +97,24 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's /// page items, kept while that document is unchanged, whether a call's own savepoint -/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made, with the size +/// of the values they hold now and the most they may hold: the run's heap. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, presets: RefCell>>, + preset_bytes: Cell, + preset_limit: u64, } impl State { + /// The state of a run whose heap is `heap_bytes`. + pub(super) fn new(heap_bytes: usize) -> Self { + Self { preset_limit: heap_bytes as u64, ..Self::default() } + } + /// Whether a call's own savepoint is open: its commands take none of their own. pub(super) fn saving(&self) -> bool { self.saving.get() @@ -111,20 +123,25 @@ impl State { /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every /// document, the selection and the undo histories are as they were before it, with no undo step -/// and no change to the document's saved state. +/// and no change to the document's saved state, and the growth its commands were charged is not +/// counted. fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { if h.dom.saving.get() { return f(h); } let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); + let mark = h.growth_mark(); h.dom.saving.set(true); let r = f(h); h.dom.saving.set(false); let mut s = h.session.borrow_mut(); if r.is_ok() { save.keep(&mut s); - } else if !save.restore(&mut s) { - return Err(HostError::Abort(HISTORY_LOST.to_string())); + } else { + h.put_growth_back(mark); + if !save.restore(&mut s) { + return Err(HostError::Abort(HISTORY_LOST.to_string())); + } } r } @@ -304,11 +321,17 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result bool { + whole(reverts) != Some(with_doc(h, doc, |_, st| st.reverts)) +} + /// The page item `d` names, which must still be in its document. fn item_of(h: &Host, d: &Data) -> std::result::Result { let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc(h, *run, *uid).filter(|doc| !reverted_since(h, *doc, *reverts)).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; @@ -346,8 +369,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { - Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), - None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + Some(t) => host_ref(t, &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), }, None => Data::Null, } @@ -509,6 +532,8 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - .map(|i| { let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + // A path with only segments selected gets them back below, with no anchors. + None if before.segments.contains_key(i) => Vec::new(), None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), }; json!({"id": i.0, "anchors": anchors}) @@ -963,17 +988,30 @@ fn new_preset(h: &Host) -> Answer { return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); } let item = |k: &str, v: Data| (k.to_string(), v); - presets.push(vec![ + let fields = vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ]); + ]; + hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| data_size(v)).sum())?; + presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } +/// Counts that the run's presets now hold `added` bytes of values in place of `replaced`, and +/// refuses when they would hold more than the run's heap. +fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result<(), HostError> { + let total = h.dom.preset_bytes.get().saturating_sub(replaced).saturating_add(added); + if total > h.dom.preset_limit { + return Err(HostError::Range(format!("the DocumentPreset settings would hold more than {} bytes", h.dom.preset_limit))); + } + h.dom.preset_bytes.set(total); + Ok(()) +} + /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; @@ -1026,8 +1064,12 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; - match fields.iter_mut().find(|(k, _)| k == key) { - Some((_, v)) => *v = value, + // The values the presets hold now count against the run's heap: a value assigned again + // replaces the one before it. + let at = fields.iter().position(|(k, _)| k == key); + hold_preset_bytes(&h, at.map_or(0, |n| data_size(&fields[n].1)), data_size(&value))?; + match at { + Some(n) => fields[n].1 = value, None => fields.push((key.to_string(), value)), } Ok(Data::Undefined) @@ -1157,28 +1199,33 @@ fn selection_of(h: &Host, uid: u64) -> Answer { } /// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or -/// `[]`. Every one must be an object of that document that can be selected. +/// `[]`. Every one must be an object of that document that can be selected. `undefined`, such as +/// an index past the end of `pageItems`, is refused and clears nothing. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), + Data::Undefined => return Err(HostError::Type("a selection is a page item, a list of them, null or []".into())), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], }; - let mut ids: Vec = Vec::with_capacity(list.len()); - for d in list { - let item = item_of(h, d)?; - let ok = item.doc.uid == doc.uid - && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); - if !ok { - let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); - return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + // The locked artboards are found once for the whole list, and repeated objects are kept once. + with_doc(h, doc, |_, st| { + let locks = st.doc.locked_artboards(); + let mut seen: HashSet = HashSet::with_capacity(list.len()); + let mut ids: Vec = Vec::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, item.id) { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if seen.insert(item.id) { + ids.push(item.id); + } } - if !ids.contains(&item.id) { - ids.push(item.id); - } - } - Ok(ids) + Ok(ids) + }) } fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { @@ -1440,6 +1487,25 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in +/// the object. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, true)?; + let r = with_doc(h, item.doc, |_, st| { + let mut r = r; + if let Some(n) = st.doc.node(item.id) { + n.walk(&mut |c| { + if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) { + r = r.union(handles); + } + }); + } + r + }); + Ok(f.bounds(h.dom.coords.get(), r)) +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1611,13 +1677,13 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { + let Some(&[run, uid, reverts, high, low]) = handle.as_deref() else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let doc = find_doc(h, run, uid).filter(|doc| !reverted_since(h, *doc, reverts)).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } @@ -1771,8 +1837,11 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { fn layer_name(h: &Host, a: &[Data]) -> Answer { let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + if reverted_since(h, doc, *reverts) { + return Err(HostError::Error(STALE_ITEM.into())); + } let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) } @@ -1962,7 +2031,7 @@ fn classes(link: &Link) -> Vec { ("height", property(l, item_height, item_set_height), typed("number")), ("geometricBounds", get(l, item_geometric), typed("Array")), ("visibleBounds", get(l, item_visible), typed("Array")), - ("controlBounds", get(l, item_visible), typed("Array")), + ("controlBounds", get(l, item_control), typed("Array")), ("editable", get(l, item_editable), typed("boolean")), ("zOrderPosition", get(l, item_z_order_position), typed("number")), ("duplicate", method(l, item_duplicate), returns("PageItem", &placement)), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..8e79b7bdda 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1076,6 +1076,20 @@ impl Host { self.pause.set(true); Ok(()) } + + /// The growth [`Host::charge_growth`] has counted, and whether the run waits for an answer about + /// it, for [`Host::put_growth_back`]. + fn growth_mark(&self) -> (u64, u64, bool) { + (self.objects.get(), self.bytes_kept.get(), self.waiting.get()) + } + + /// Puts back the growth counted after [`Host::growth_mark`] gave `mark`: the commands that added + /// it were put back. + fn put_growth_back(&self, (objects, bytes, waiting): (u64, u64, bool)) { + self.objects.set(objects); + self.bytes_kept.set(bytes); + self.waiting.set(waiting); + } } /// A run in progress. @@ -1309,16 +1323,14 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> { - let id = id.to_string(); - let params = params.clone(); let session = host.session.clone(); let started = clock(); let r = { let mut s = session.borrow_mut(); - step(&mut s, host, &id, ¶ms) + step(&mut s, host, id, params) }; // Only commands that exist are timed, so the table holds at most one row per command. - if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { + if let (Some(started), Some(spec)) = (started, crate::find_command(id)) { let nanos = started.elapsed().as_nanos(); let mut times = host.commands.borrow_mut(); let row = times.entry(spec.id).or_insert((0, 0, 0)); @@ -1331,13 +1343,18 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())), Err(e) => return Err(HostError::Error(e.to_string())), }; + let mark = host.growth_mark(); let crossed = host.charge_growth(objects, added).and_then(|()| { let data = to_data(&value, &result_limits(), 0, &mut (0, 0)) .map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?; host.charge_call(data_size(&data))?; Ok(data) }); - // A command whose result does not reach the script is put back, like one that failed. + // A command whose result does not reach the script is put back, like one that failed, and so is + // the growth it was charged. + if crossed.is_err() { + host.put_growth_back(mark); + } if let Some(save) = save { let mut s = session.borrow_mut(); if crossed.is_ok() { @@ -2064,7 +2081,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - dom: dom::State::default(), + dom: dom::State::new(heap_bytes), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..d0cb4e7ecd 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -229,6 +229,41 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert!(e.contains("Cannot select"), "{e}"); } +/// An index past the end of `pageItems` gives `undefined`, which does not clear the selection; +/// `null` and `[]` do. +#[test] +fn assigning_undefined_to_the_selection_throws_and_keeps_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let caught = "var d = app.activeDocument, m = '';\ + try { d.selection = d.pageItems[99]; } catch (e) { m = e.name; }\ + vc.log(m); vc.log(d.selection.length);"; + assert_eq!(log(&mut s, caught), vec![json!("TypeError"), json!(1)]); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + for clear in ["null", "[]"] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + log(&mut s, &format!("app.activeDocument.selection = {clear};")); + assert!(s.active().unwrap().selection.objects.is_empty(), "{clear}"); + } +} + +/// `controlBounds` takes in a direction point that lies past the curve; `visibleBounds` does not. +#[test] +fn control_bounds_take_in_direction_points_past_the_curve() { + let (mut s, _, _) = doc(); + s.execute("path.create", &json!({"anchors": [{"x": 200, "y": 0, "out": [200, -100]}, {"x": 300, "y": 0, "in": [300, -100]}]})).unwrap(); + let out = log( + &mut s, + "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var p = app.activeDocument.pageItems;\ + vc.log(p[2].controlBounds); vc.log(p[2].visibleBounds); vc.log(p[0].controlBounds); vc.log(p[0].visibleBounds);", + ); + let top = |v: &Value| v[1].as_f64().unwrap(); + assert!((top(&out[0]) + 100.0).abs() < 1e-9, "{out:?}"); + assert!(top(&out[1]) > -90.0, "{out:?}"); + // A rectangle's direction points lie on its edges. + assert_eq!(out[2], out[3]); +} + #[test] fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); @@ -364,6 +399,17 @@ fn a_copy_that_cannot_be_placed_is_deleted() { assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); // The refused copy leaves no undo step and does not change the document's step. assert_eq!((undo_steps(&s), s.active().unwrap().history.step()), (steps, step)); + // Nor does it count toward the run's growth allowance: many refused copies stay within one + // that a few kept copies would pass. + crate::script::TEST_GROWTH.with(|g| g.set(Some(5))); + let r = run( + &mut s, + "var p = app.activeDocument.pageItems, n = p.length, g = p[0], t = p[n - 1], refused = 0;\ + for (var k = 0; k < 20; k++) { try { t.duplicate(g, ElementPlacement.INSIDE); } catch (e) { refused++; } }\ + vc.log(refused);", + ); + crate::script::TEST_GROWTH.with(|g| g.set(None)); + assert_eq!(r.unwrap()["log"], json!([20])); } #[test] @@ -482,6 +528,14 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { let by_row = stored.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}"); } + // A change of spacing alone leaves the stored columns as they are, so leaving the rows later + // gives the same grid with or without it. + let to_row = json!({"artboardLayout": {"layout": "gridByRow"}}); + let plain = stored.clone().with_params(&json!({"artboards": 9}), "file.new").unwrap(); + let spaced = stored.clone().with_params(&json!({"artboards": 9, "artboardLayout": {"spacing": 20}}), "file.new").unwrap(); + assert_eq!((plain.grid_columns(), spaced.grid_columns()), (3, 3)); + let (plain, spaced) = (plain.with_params(&to_row, "file.new").unwrap(), spaced.with_params(&to_row, "file.new").unwrap()); + assert_eq!(plain.grid_columns(), spaced.grid_columns()); let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); assert!(e.contains("rows must be 1 or more"), "{e}"); for layout in ["gridByRow", "row", "column"] { @@ -549,6 +603,26 @@ fn an_edit_keeps_the_order_of_a_mixed_selection() { assert_eq!((sel.objects.clone(), sel.anchors.clone()), (before.objects, before.anchors)); } +/// A path with segments selected and no anchors gets the segments back, not every anchor. +#[test] +fn an_edit_keeps_a_path_with_only_a_segment_selected() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 200.0, 20.0, 20.0); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + s.doc_mut().unwrap().selection.anchors.remove(&b); + let before = s.active().unwrap().selection.clone(); + log(&mut s, "app.activeDocument.pageItems[2].duplicate();"); + let sel = &s.active().unwrap().selection; + assert_eq!((&sel.objects, &sel.segments, sel.anchors.get(&a)), (&before.objects, &before.segments, before.anchors.get(&a))); + // The segment brings back its own two end points, as `select.segments` selects them, and none + // of the path's other anchors: the journaled restore selects none of them first. + assert_eq!(sel.anchors.get(&b).map(|k| k.len()), Some(2), "{sel:?}"); + let restore = s.journal.iter().rev().find(|(id, _)| id == "select.anchorsMany").map(|(_, p)| p.clone()).unwrap(); + let path = restore["items"].as_array().unwrap().iter().find(|i| i["id"] == json!(b.0)).cloned().unwrap(); + assert_eq!(path["anchors"], json!([]), "{restore}"); +} + #[test] fn assigning_the_selection_clears_a_layers_panel_target() { let (mut s, a, _) = doc(); @@ -733,6 +807,28 @@ fn a_document_preset_is_an_instance_of_its_class() { assert_eq!(out, vec![json!(true), json!("DocumentPreset"), json!(612)]); } +/// The values the presets hold count against the run's heap, a value assigned again in place of +/// the one before it. +#[test] +fn document_preset_values_are_bounded_by_the_runs_heap() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = Session::new(); + let big = "var s = 'a'; while (s.length < (1 << 19)) s += s;"; + let again = + format!("#targetengine presets\n{big} var p = new DocumentPreset(); for (var k = 0; k < 40; k++) p.title = s + k; vc.log(p.title.length);"); + assert_eq!(log(&mut s, &again), vec![json!(524_290)]); + let many = format!( + "#targetengine presets\n{big} var m = '';\ + try {{ for (var k = 0; k < 40; k++) {{ var p = new DocumentPreset(); p.title = s; }} }} catch (e) {{ m = e.name + ': ' + e.message; }}\ + vc.log(k < 40); vc.log(m);" + ); + let out = log(&mut s, &many); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!(out[0], json!(true), "{out:?}"); + assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); +} + #[test] fn the_same_document_or_item_is_the_same_object() { let (mut s, a, _) = doc(); @@ -928,20 +1024,52 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +/// File › Revert loads objects with the ids they were saved with: an object or a layer read before +/// the revert does not name the loaded one. +#[test] +fn wrappers_go_stale_after_revert() { + let (mut s, a, _) = doc(); + let dir = std::env::temp_dir().join(format!("vc-dom-revert-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for read in ["i.name", "i.name = 'after'", "app.activeDocument.selection = i", "l.name"] { + let source = format!("var i = app.activeDocument.pageItems[0], l = i.parent; i.name = 'before'; vc.run('file.revert'); {read};"); + let e = failure(&mut s, &source); + assert!(e.contains("Stale page item"), "{read}: {e}"); + } + // Objects read after the revert are the loaded ones. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems; p[0].name = 'before'; vc.run('file.revert');\ + app.activeDocument.pageItems[0].name = 'loaded'; vc.log(app.activeDocument.pageItems.length);", + ); + assert_eq!(out, vec![json!(2)]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().name.as_deref(), Some("loaded")); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); - let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); - assert!(e.contains(&b.0.to_string()), "{e}"); - assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + // The script catches the error and finds both objects still there before the run ends, so the + // run's own rollback cannot hide a deletion. + let caught = "var p = app.activeDocument.pageItems, m = '';\ + try { p.removeAll(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.length);"; + let out = log(&mut s, caught); + assert!(out[0].as_str().unwrap().contains(&b.0.to_string()), "{out:?}"); + assert_eq!(out[1], json!(2)); + assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); // A locked object inside an unlocked group stops it too. s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); - let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); - assert!(e.contains(&g.to_string()), "{e}"); + let out = log(&mut s, caught); + assert!(out[0].as_str().unwrap().contains(&g.to_string()), "{out:?}"); + assert_eq!(out[1], json!(3)); assert!(s.active().unwrap().doc.node(b).is_some()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log(&mut s, "var p = app.activeDocument.pageItems; p.removeAll(); vc.log(p.length);"); @@ -1002,8 +1130,9 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy().to_string(); + let (p, other) = (serde_json::to_string(&p).unwrap(), serde_json::to_string(&format!("{p}.other")).unwrap()); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 2af2fc130f..7380cc574c 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -349,6 +349,10 @@ fn reflected_members(class: &HostClass) -> Result, String> { if out.iter().any(|r| *r.name == **name) { return Err(format!("the host class {} names the member {name} twice", class.name)); } + // The prototype's `constructor` is the class's own constructor. + if name == "constructor" { + return Err(format!("the host class {} names a member constructor, which is the name of its constructor", class.name)); + } let access = match member { HostMember::Get(_) => Access::ReadOnly, HostMember::Property { .. } => Access::ReadWrite, diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index a84c221d3a..0b6b7fffff 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -227,6 +227,7 @@ fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[I let methods = info_array(interp, methods)?; interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?; let find = native(interp, "find", find, 1, NativeKind::Plain, false)?; + interp.object_mut(find)?.extensible = false; interp.temp_roots.push(Value::Object(find)); let r = interp.new_object(); interp.temp_roots.push(Value::Object(r)); diff --git a/crates/js/src/reflect_tests.rs b/crates/js/src/reflect_tests.rs index 3e8827cf4f..e28247e162 100644 --- a/crates/js/src/reflect_tests.rs +++ b/crates/js/src/reflect_tests.rs @@ -112,13 +112,20 @@ fn a_reflection_cannot_be_changed() { [typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()"; assert_eq!(text(&mut r, tries), "object,Object,number,1,,object"); // In strict mode each one throws a TypeError. - for write in ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find"] { + for write in + ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find", "x.find.extra = 1"] + { assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}"); } assert_eq!( - text(&mut r, "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments)"), - "true true true" + text( + &mut r, + "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments) + ' ' + Object.isFrozen(x.find)" + ), + "true true true true" ); + // The frozen `find` still finds. + assert_eq!(text(&mut r, "x.find('a').name"), "a"); } #[test] @@ -239,4 +246,11 @@ fn info_for_a_member_a_class_does_not_have_is_refused() { class.members.push(("size".into(), HostMember::Get(constant(1.0)))); let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); assert!(e.message.contains("names the member size twice"), "{}", e.message); + // `constructor` is the class's own constructor, so no member may take its name. + let mut r = realm(); + let mut class = classes().remove(0); + class.members.push(("constructor".into(), HostMember::Get(constant(1.0)))); + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains("names a member constructor"), "{}", e.message); + assert_eq!(text(&mut r, "typeof Item"), "undefined"); } diff --git a/docs/mcp.md b/docs/mcp.md index eff8b953f8..8219fb3d83 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2631,7 +2631,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset `file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()` (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` - starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and + starts with the defaults that page gives. The values a run's `DocumentPreset` objects hold together may not take + more than the run's heap; an assignment past that throws a `RangeError`, and a value assigned again replaces the + one before it in that count. A preset's `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a @@ -2648,7 +2650,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds, widened to take in the direction points of every path in the object), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same @@ -2670,16 +2672,16 @@ app through the global object `vc`, and writes to the Script Console and runs ot is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active - tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine - kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a + tab as it was. A bad value throws an error and changes nothing. An object that was deleted, that was read before + `file.revert` reloaded its document, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` and delete nothing. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, - a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + a list of at most 10,000, `null` or `[]`; `undefined`, such as an index past the end of `pageItems`, throws a + `TypeError`, and an object that cannot be selected throws `Cannot select`, both with nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, From 99e07b0f6bd5129ffbc46c2b33a86d1e19542272 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:40:07 -0800 Subject: [PATCH 08/68] Scripts: DocumentPreset arrays count each element against the heap The heap limit on DocumentPreset values counted a boolean as 4 bytes, while the host keeps a whole value for each array element, so arrays kept by many presets could hold several times the run's heap. The limit now counts the host's copy: a value for the field and for each element or property, plus the text of its strings and property names. --- crates/engine/src/script/dom.rs | 16 ++++++++++++++-- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 0753cc5263..8054a1b174 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -996,7 +996,7 @@ fn new_preset(h: &Host) -> Answer { item("numArtboards", num(1.0)), item("width", num(612.0)), ]; - hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| data_size(v)).sum())?; + hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?; presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } @@ -1012,6 +1012,18 @@ fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result Ok(()) } +/// The bytes the host's copy of `d` takes: a `Data` for the value and each element or property +/// in it, plus the text of its strings and property names. +fn held_bytes(d: &Data) -> u64 { + let owned = match d { + Data::String(s) => s.len() as u64, + Data::Array(a) => a.iter().map(held_bytes).sum(), + Data::Object(o) => o.iter().map(|(k, v)| (size_of::() + k.len()) as u64 + held_bytes(v)).sum(), + Data::Undefined | Data::Null | Data::Bool(_) | Data::Number(_) => 0, + }; + size_of::() as u64 + owned +} + /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; @@ -1067,7 +1079,7 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { // The values the presets hold now count against the run's heap: a value assigned again // replaces the one before it. let at = fields.iter().position(|(k, _)| k == key); - hold_preset_bytes(&h, at.map_or(0, |n| data_size(&fields[n].1)), data_size(&value))?; + hold_preset_bytes(&h, at.map_or(0, |n| held_bytes(&fields[n].1)), held_bytes(&value))?; match at { Some(n) => fields[n].1 = value, None => fields.push((key.to_string(), value)), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index d0cb4e7ecd..039d5d17e8 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -829,6 +829,24 @@ fn document_preset_values_are_bounded_by_the_runs_heap() { assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); } +/// An array a preset holds counts a whole value for each element, so arrays of booleans kept by +/// many presets stop at the run's heap too. +#[test] +fn document_preset_arrays_count_each_element_they_hold() { + use crate::script::TEST_ENGINE_HEAP; + TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20))); + let mut s = Session::new(); + let out = log( + &mut s, + "#targetengine presets\nvar a = []; for (var i = 0; i < 20000; i++) a.push(true); var m = '';\ + try { for (var k = 0; k < 40; k++) { var p = new DocumentPreset(); p.title = a; } } catch (e) { m = e.name + ': ' + e.message; }\ + vc.log(k < 40); vc.log(m);", + ); + TEST_ENGINE_HEAP.with(|h| h.set(None)); + assert_eq!(out[0], json!(true), "{out:?}"); + assert!(out[1].as_str().unwrap().starts_with("RangeError: the DocumentPreset settings"), "{out:?}"); +} + #[test] fn the_same_document_or_item_is_the_same_object() { let (mut s, a, _) = doc(); From 82e3d6dac34458445d9bf5511a55957a323e2294 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 09:11:54 -0800 Subject: [PATCH 09/68] Plug-ins: the web build checks plug-ins and runs filters in a Web Worker On the web, a plug-in being installed ran its start function and vc_manifest on the page, and a filter ran on the page for its whole budget, so a slow or looping module froze the tab for up to a minute (five for a heavy filter), and Cancel could not stop it. - A second wasm, apps/vectorcraft-plugin-worker, is built by Trunk as a worker (data-type="worker" with data-loader-shim in index.html). The page starts one worker for each check and each run, and terminates it on Cancel, when the document or the plug-in changes, and 5 s past the run's time budget, also while a dialog is open. Each worker's inbox holds its latest progress report and at most 8 other messages. - crates/plugins/src/worker.rs holds the messages and the worker's side. Runs can pause at each vc_call (Plugin::begin_run and resume_run), which the desktop's synchronous calls now use too. - Install Plug-in... and File > Open check a module in a worker first; the page then loads it with Plugin::load_checked, which runs none of its code. - A filter that calls commands sends each call to the page. The session holds the run's undo step open and refuses other edits with "a plug-in is running: cancel it or wait for it to finish" until the run ends; the progress window shows at once with Cancel only. - On the web every filter and plug-in command started from the menus or their dialogs runs in a worker, and the dialogs have no Preview. A plug-in command applies as itself, one undo step named after it. Commands that automation runs directly still run where they are called and return their result. - packaging/web: the worker files carry no hash, so the sample cache rules make only the hashed app files immutable. --- Cargo.lock | 10 + apps/vectorcraft-plugin-worker/Cargo.toml | 20 + apps/vectorcraft-plugin-worker/src/main.rs | 37 ++ apps/vectorcraft-web/Cargo.toml | 2 +- apps/vectorcraft-web/index.html | 2 + apps/vectorcraft-web/src/main.rs | 4 + apps/vectorcraft-web/src/plugin_workers.rs | 72 +++ apps/vectorcraft-web/src/web.rs | 3 + crates/engine/src/cmd/plugin.rs | 207 +++++++- crates/engine/src/cmd/plugin_call.rs | 97 ++-- crates/engine/src/error.rs | 7 + crates/engine/src/lib.rs | 6 + crates/engine/src/session/documents.rs | 2 + crates/engine/src/session/edit.rs | 6 + crates/engine/src/session/execute.rs | 5 + crates/engine/src/tests/plugins.rs | 128 +++++ crates/plugins/src/host.rs | 2 +- crates/plugins/src/lib.rs | 6 +- crates/plugins/src/runtime.rs | 396 ++++++++++---- crates/plugins/src/worker.rs | 533 +++++++++++++++++++ crates/plugins/tests/call.rs | 10 + crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/app/commands.rs | 9 + crates/ui-egui/src/dialogs/plugin.rs | 29 +- crates/ui-egui/src/io.rs | 2 +- crates/ui-egui/src/io/open.rs | 16 +- crates/ui-egui/src/plugin_runs.rs | 566 +++++++++++++++++++-- crates/ui-egui/src/services.rs | 4 + crates/ui-egui/src/tests/plugin_runs.rs | 435 ++++++++++++++++ docs/plugins.md | 32 +- packaging/web/.htaccess | 4 +- packaging/web/README.md | 19 +- packaging/web/_headers | 6 +- xtask/src/layers.rs | 1 + xtask/src/main.rs | 7 +- 35 files changed, 2489 insertions(+), 198 deletions(-) create mode 100644 apps/vectorcraft-plugin-worker/Cargo.toml create mode 100644 apps/vectorcraft-plugin-worker/src/main.rs create mode 100644 apps/vectorcraft-web/src/plugin_workers.rs create mode 100644 crates/plugins/src/worker.rs diff --git a/Cargo.lock b/Cargo.lock index 6a602ed891..55f7f18d34 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7132,6 +7132,16 @@ dependencies = [ "vectorcraft-text", ] +[[package]] +name = "vectorcraft-plugin-worker" +version = "0.24.1" +dependencies = [ + "js-sys", + "vectorcraft-plugins", + "wasm-bindgen", + "web-sys", +] + [[package]] name = "vectorcraft-plugins" version = "0.24.1" diff --git a/apps/vectorcraft-plugin-worker/Cargo.toml b/apps/vectorcraft-plugin-worker/Cargo.toml new file mode 100644 index 0000000000..a2dfc0b944 --- /dev/null +++ b/apps/vectorcraft-plugin-worker/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "vectorcraft-plugin-worker" +description = "The web build's plug-in worker: checks plug-in modules being installed and runs filters off the page" +version.workspace = true +edition.workspace = true +license.workspace = true +publish = false + +[lints] +workspace = true + +[[bin]] +name = "vectorcraft-plugin-worker" +path = "src/main.rs" + +[target.'cfg(target_arch = "wasm32")'.dependencies] +vectorcraft-plugins = { workspace = true } +wasm-bindgen = "0.2" +js-sys = "0.3" +web-sys = { version = "0.3", features = ["DedicatedWorkerGlobalScope", "MessageEvent"] } diff --git a/apps/vectorcraft-plugin-worker/src/main.rs b/apps/vectorcraft-plugin-worker/src/main.rs new file mode 100644 index 0000000000..4699ca2e3f --- /dev/null +++ b/apps/vectorcraft-plugin-worker/src/main.rs @@ -0,0 +1,37 @@ +//! The web build's plug-in worker ([`vectorcraft_plugins::worker`]). Trunk builds it beside the +//! app (`data-type="worker"` in `apps/vectorcraft-web/index.html`), and the page starts one for each +//! module it checks and each filter it runs, through the loader Trunk writes for it +//! (`vectorcraft-plugin-worker_loader.js`). Each message, both ways, is one `Uint8Array`. + +#[cfg(target_arch = "wasm32")] +fn main() { + use std::cell::RefCell; + use std::rc::Rc; + + use wasm_bindgen::JsCast as _; + use wasm_bindgen::prelude::Closure; + use web_sys::{DedicatedWorkerGlobalScope, MessageEvent}; + + let scope: DedicatedWorkerGlobalScope = js_sys::global().unchecked_into(); + let poster = scope.clone(); + let post = Rc::new(move |msg: Vec| { + let bytes = js_sys::Uint8Array::from(msg.as_slice()); + // A message that can't be posted leaves the page waiting, and its time budget ends the run. + let _ = poster.post_message_with_transfer(&bytes, &js_sys::Array::of1(&bytes.buffer())); + }); + let worker = Rc::new(RefCell::new(vectorcraft_plugins::worker::Worker::new(post))); + let handler = Rc::clone(&worker); + let on_message = Closure::::new(move |e: MessageEvent| { + let msg = js_sys::Uint8Array::new(&e.data()).to_vec(); + handler.borrow_mut().handle(&msg); + }); + scope.set_onmessage(Some(on_message.as_ref().unchecked_ref())); + // The handler lives as long as the worker. + on_message.forget(); + worker.borrow().ready(); +} + +#[cfg(not(target_arch = "wasm32"))] +fn main() { + eprintln!("vectorcraft-plugin-worker only runs in the browser, as the web build's plug-in worker"); +} diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 9569d2b3f3..7907ecc476 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -31,4 +31,4 @@ wasm-bindgen = "0.2" serde_json = { workspace = true } wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlInputElement", "KeyboardEvent", "HtmlIFrameElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "ClipboardEvent", "DataTransfer", "File", "FileList", "Url", "Location", "CssStyleDeclaration", "Event", "EventTarget", "MouseEvent", "PointerEvent", "TouchEvent", "AddEventListenerOptions", "DomRect", "DragEvent", "Storage", "Navigator", "RequestInit", "Response", "AbortController", "AbortSignal", "Node", "Worker", "MessageEvent", "ErrorEvent", "Performance"] } diff --git a/apps/vectorcraft-web/index.html b/apps/vectorcraft-web/index.html index 2ccfc271b0..965bd03ebd 100644 --- a/apps/vectorcraft-web/index.html +++ b/apps/vectorcraft-web/index.html @@ -17,6 +17,8 @@ + +