From 959332840ce5f3aae7e1472236b8e34f43f337bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:27:12 -0800 Subject: [PATCH 001/160] 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 12edbb10738153d80f7195f81a90e89025a1ce34 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:09:30 -0800 Subject: [PATCH 002/160] Swatches: a pattern swatch dropped on empty canvas places a copy of its tile art A pattern swatch dragged from the Swatches panel and released where there is no art now runs the new `pattern.placeArt {name, x?, y?}`: one group holding a rectangle of the tile with no fill and no stroke at its back and the tile art in its place in the tile, centered on the drop point, selected, in one undo step. Dropped on art, the swatch fills it as before. `object.pattern.replaceArt` now reads a rectangle with no fill and no stroke at the back of the art (or at the back of one selected group) as the tile and leaves it out of the tile art, so the placed copy, edited and Alt-dragged back onto the swatch, keeps its place in the tile. Without such a rectangle the tile keeps its size and moves as far as the art's bounds moved from the old tile art's, instead of staying where it was. The help page describes this edit cycle and the unpainted bounding rectangle: https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=208 https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=204 Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/brushes.rs | 5 +- crates/engine/src/cmd/patterncmds.rs | 95 +++++++++-- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/pattern.rs | 154 +++++++++++++++++- crates/ui-egui/src/canvas/context.rs | 14 +- crates/ui-egui/src/canvas/tests.rs | 44 +++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/widgets/drag.rs | 6 +- docs/mcp.md | 27 ++- docs/target-app-parity.md | 3 +- 38 files changed, 352 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index fbd4512fa3..ba4277da58 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -38,7 +38,7 @@ mod dynamic; mod symbolism; mod symbols; -pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; +pub(crate) use brushes::{apply_brush, brush_targets, frame_marker, stroke_paint}; use brushes::{ brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_object_options, brush_options, brush_place_art, brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush, diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index b0ab4366d2..afdf7d9f60 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -766,10 +766,11 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0 })) } -/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the +/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and +/// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the /// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its /// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. -fn frame_marker(n: &Node) -> Option { +pub(crate) fn frame_marker(n: &Node) -> Option { let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; let unpainted = n.appearance.effects.is_empty() && n.appearance.items.iter().all(|i| match i { diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index e4b6d810a6..1b5d00de58 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -19,6 +19,7 @@ use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_pai use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect}; +use super::brushsym::frame_marker; use super::edit::{outermost, selected_roots}; use super::pathops::Beside; use super::{ @@ -43,10 +44,19 @@ pub fn specs() -> Vec { "Replace Pattern Art", [], None, - "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", + "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch and options; an unpainted rectangle at the back of the art (or at the back of one selected group, as pattern.placeArt places it) becomes the tile and is left out of the tile art, otherwise the tile keeps its size and moves as far as the art's bounds moved from the old tile art's (with Size Tile to Art on, the tile fits the new art); every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art and tile match the pattern's already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", can_replace_pattern_art, pattern_replace_art ), + cmd!( + "pattern.placeArt", + "Place Pattern Art", + [], + None, + "{name, x?, y?} place a copy of pattern `name`'s tile art, as dragging its swatch from the Swatches panel onto an empty part of the canvas does: one group with an unpainted rectangle of the tile at its back, centered on (x, y) (default: the center of the first artboard) in the layer new art goes into, and selected; object.pattern.replaceArt reads the rectangle back as the tile; the pattern does not change; one undo step; refused while a pattern is edited and for a pattern with no art → {id}", + can_replace_pattern_art, + pattern_place_art + ), cmd!( "object.pattern.edit", "Edit Pattern", @@ -429,41 +439,102 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result Result { const C: &str = "object.pattern.replaceArt"; let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); let roots = roots(s, p, C)?; let d = &s.doc()?.doc; - let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; - if roots.is_empty() { + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + let (src, marked) = tile_and_art(roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect()); + if src.is_empty() { return Err(bad(C, "select the art for the pattern tile")); } - let src: Vec> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect(); if paints_pattern(d, &src, &name) { return Err(bad(C, format!("art painted with `{name}` can't be its tile"))); } + let mut next = def.clone(); + next.tile = match (marked, vectorcraft_doc::live::nodes_bounds(&def.art), vectorcraft_doc::live::nodes_bounds(&src)) { + (Some(tile), ..) => tile, + (None, Some(was), Some(now)) => def.tile + (now.origin() - was.origin()), + (None, ..) => def.tile, + }; + next.art = src.clone(); + if next.size_tile_to_art { + next.fit_tile_to_art(); + } + let tile = next.tile; // Copies made from the same next id are equal when the art matches the tile art. let fresh = |art: &[Arc]| copies(&mut Document::clone(d), art); - if fresh(&old) == fresh(&src) { + if tile == def.tile && fresh(&def.art) == fresh(&src) { return Ok(json!({ "name": name })); } s.edit("Replace Pattern Art", |d, _| { let art: Vec> = copies(d, &src).into_iter().map(Arc::new).collect(); if let Some(def) = d.pattern_mut(&name) { def.art = art; - if def.size_tile_to_art { - def.fit_tile_to_art(); - } + def.tile = tile; } Ok(()) })?; Ok(json!({ "name": name })) } +/// The tile art and the tile that art `src` (in paint order) gives a pattern: an unpainted +/// rectangle at the back of the art ([`frame_marker`]), or at the back of a lone plain group as +/// `pattern.placeArt` places it, is the tile and is left out of the art, and that group's members +/// are the art. Without such a rectangle the art is `src` and there is no tile. +fn tile_and_art(src: Vec>) -> (Vec>, Option) { + let mut art = src; + if let [g] = art.as_slice() + && let NodeKind::Group { children, clip: false } = &g.kind + && children.first().is_some_and(|c| frame_marker(c).is_some()) + && **g == Node::group(g.id, children.clone()) + { + art = children.clone(); + } + match art.first().and_then(|c| frame_marker(c)) { + Some(tile) => (art.split_off(1), Some(tile)), + None => (art, None), + } +} + +/// `pattern.placeArt`: a copy of pattern `name`'s tile art in one group, with an unpainted +/// rectangle of its tile at the back, centered on (`x`, `y`) (default: the center of the first +/// artboard) in the layer new art goes into, and selected, as one undo step. The pattern does not +/// change; `object.pattern.replaceArt` reads the rectangle back as the tile ([`tile_and_art`]). +fn pattern_place_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "pattern.placeArt"; + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); + let d = &s.doc()?.doc; + let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?); + let def = d.pattern(&name).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + if def.art.is_empty() { + return Err(bad(C, "no artwork")); + } + let unpainted = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0); + let marker = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(def.tile), unpainted); + let mut art = Node::group(NodeId(0), std::iter::once(Arc::new(marker)).chain(def.art.iter().cloned()).collect()); + if let Some(r) = art.geometric_bounds_with(&d.symbol_boxes()) { + art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false); + } + let parent = s.doc()?.target_parent()?; + let id = s.edit("Place Pattern Art", |d, sel| { + let art = d.reid(&art); + let id = art.id; + d.insert(parent, usize::MAX, art)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + /// What a piece of art uses by name, for [`paints_pattern`]. #[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Uses<'a> { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..5898abc113 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -480,6 +480,7 @@ pub(super) const ALLOWED: &[&str] = &[ "pattern.delete", "pattern.list", "pattern.options", + "pattern.placeArt", "pattern.transform", "perspective.attach", "perspective.draw", diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index 01f8e76fbc..d45376ae82 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -222,8 +222,9 @@ fn blue_rect(s: &mut Session) -> NodeId { } /// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo -/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the -/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles. +/// step: the pattern keeps its name, swatch, place and options, the tile keeps its size and moves as +/// far as the art's bounds moved, art painted with it keeps the paint, and the selected art stays on +/// the canvas, selected. Undo and Redo swap the two tiles. #[test] fn replace_art_gives_a_pattern_new_tile_art() { let mut s = session(); @@ -243,7 +244,9 @@ fn replace_art_gives_a_pattern_new_tile_art() { assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle"); assert_eq!(def.art[0].appearance, node(&s, blue).appearance); assert_ne!(def.art[0].id, blue, "a copy with an id of its own"); - assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay"); + // The red square's bounds start at (0, 0) and the blue rectangle's at (100, 100). + assert_eq!(def.tile, old.tile + vectorcraft_geom::Vec2::new(100.0, 100.0), "the tile moves with the art"); + assert_eq!((def.tile_type, &def.name), (old.tile_type, &old.name), "the options stay"); assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch"); assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern"); assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays"); @@ -282,6 +285,151 @@ fn replace_art_that_matches_the_tile_art_records_nothing() { assert_eq!(doc(&s), &before); } +/// The geometric bounds of object `id`. +fn bounds_of(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +/// Place Pattern Art places a copy of the tile art in a group with an unpainted rectangle of the +/// tile at its back, centered where it is asked for (by default the first artboard's center), in +/// the current layer, selected, as one undo step; the pattern does not change. +#[test] +fn place_art_places_the_tile_art_with_its_tile() { + let mut s = session(); + let red = make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(-5.0, -5.0, 15.0, 15.0)); + let steps = s.doc().unwrap().history.undo.len(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Place Pattern Art"))); + assert_eq!(st.selection.objects.to_vec(), vec![id], "the copy is selected"); + assert_eq!(st.doc.parent_of(id), Some(st.doc.layers[0].id), "in the current layer"); + assert_eq!(doc(&s).pattern("Dots").unwrap(), &def, "the pattern stays as it was"); + let group = node(&s, id); + let NodeKind::Group { children, clip: false } = &group.kind else { panic!("a group: {:?}", group.kind) }; + let [marker, art] = children.as_slice() else { panic!("the tile and the art: {children:?}") }; + // The tile, centered on (200, 150), is unpainted; the art keeps its place in the tile. + assert_eq!(marker.geometric_bounds(), Some(Rect::new(190.0, 140.0, 210.0, 160.0))); + assert!(marker.appearance.fill_paint().is_none() && marker.appearance.stroke().is_none_or(|k| k.paint.is_none())); + assert_eq!(art.geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + assert_eq!(art.appearance, def.art[0].appearance); + assert!(art.id != red && art.id != def.art[0].id, "a copy with an id of its own"); + // Without a position: the first artboard's center (the document is 400 × 400). + let centered = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap()); + assert_eq!(bounds_of(&s, centered).center(), Point::new(200.0, 200.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(centered).is_none(), "Undo removes the copies"); +} + +/// The placed copy, edited and given back with Replace Pattern Art, becomes the tile art, and its +/// rectangle becomes the tile: the art keeps its place in the tile, so the pattern draws the same +/// arrangement with the new art. Given back unchanged, nothing is recorded. +#[test] +fn placed_art_given_back_keeps_its_place_in_the_tile() { + let mut s = session(); + make_dots(&mut s); + s.execute("select.none", &json!({})).unwrap(); + let id = id_of(&s.execute("pattern.placeArt", &json!({"name": "Dots", "x": 200, "y": 150})).unwrap()); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let def = doc(&s).pattern("Dots").unwrap().clone(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 210.0, 160.0), "the rectangle is the tile"); + assert_eq!(def.art.len(), 1, "the rectangle is not part of the art: {:?}", def.art); + assert_eq!(def.art[0].geometric_bounds(), Some(Rect::new(195.0, 145.0, 205.0, 155.0))); + let old = before.pattern("Dots").unwrap(); + let place = |tile: Rect, art: &[Arc]| vectorcraft_doc::live::nodes_bounds(art).unwrap().origin() - tile.origin(); + assert_eq!(place(def.tile, &def.art), place(old.tile, &old.art), "the art keeps its place in the tile"); + // Given back again without a change: nothing to record. + let (again, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [id.0]})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(doc(&s), &again); + // Edited (the art recolored and the rectangle widened, ungrouped): the new art and tile. + let NodeKind::Group { children, .. } = &node(&s, id).kind else { panic!("a group") }; + let (marker, art) = (children[0].id, children[1].id); + s.execute("paint.setFill", &json!({"ids": [art.0], "color": "#0000ff"})).unwrap(); + sel(&mut s, &[id]); + s.execute("object.ungroup", &json!({})).unwrap(); + assert!(doc(&s).node(id).is_none() && doc(&s).node(marker).is_some() && doc(&s).node(art).is_some(), "ungrouped"); + s.execute("object.transform", &json!({"ids": [marker.0], "matrix": [2, 0, 0, 1, -190, 0]})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [marker.0, art.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.tile, Rect::new(190.0, 140.0, 230.0, 160.0), "the widened rectangle is the tile"); + assert_eq!(def.art.len(), 1); + assert_eq!(def.art[0].appearance, node(&s, art).appearance, "the recolored art"); +} + +/// Only an unpainted rectangle at the back of the art is the tile: a painted one, or an unpainted +/// one in front of other art, is tile art like any other, and a rectangle alone leaves no art. +#[test] +fn only_an_unpainted_rectangle_at_the_back_is_the_tile() { + let mut s = session(); + make_dots(&mut s); + let back = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let front = rect(&mut s, 110.0, 110.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [front.0], "color": "#00ff00"})).unwrap(); + // Painted: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "color": "#ffffff"})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted, but in front of the other art: art. + s.execute("paint.setFill", &json!({"ids": [back.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [back.0], "none": true})).unwrap(); + sel(&mut s, &[back]); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art.len(), 2); + // Unpainted and at the back: the tile. + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!((def.art.len(), def.tile), (1, Rect::new(100.0, 100.0, 140.0, 140.0))); + // A rectangle alone is a tile with no art. + let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0]})).unwrap_err(); + assert!(err.to_string().contains("select the art for the pattern tile"), "{err}"); +} + +/// Place Pattern Art is refused, changing nothing, for a missing or unknown name, a position that +/// is not a number, a pattern with no art, while a pattern is edited and on a locked layer. +#[test] +fn place_art_is_refused_without_changing_anything() { + let mut s = session(); + make_dots(&mut s); + doc_mut(&mut s).patterns.push(vectorcraft_doc::pattern::PatternDef::new("Empty", vec![])); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let unchanged = |s: &Session, case: &str| { + assert_eq!(doc(s), &before, "{case}: the document stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step"); + }; + for (case, p, why) in [ + ("no name", json!({}), "missing name"), + ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`"), + ("x not a number", json!({"name": "Dots", "x": "100"}), "`x` must be a number"), + ("y not a number", json!({"name": "Dots", "y": true}), "`y` must be a number"), + ("no art", json!({"name": "Empty"}), "no artwork"), + ] { + let err = s.execute("pattern.placeArt", &p).unwrap_err(); + assert!(err.to_string().contains(why), "{case}: {err}"); + unchanged(&s, case); + } + let layer = doc(&s).layers[0].id; + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": true})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert_eq!(err.to_string(), "the target layer is locked or hidden"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "locked: unchanged"); + s.execute("layer.setProps", &json!({"ids": [layer.0], "locked": false})).unwrap(); + s.execute("object.pattern.edit", &json!({"name": "Dots"})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("pattern.placeArt", &json!({"name": "Dots"})).unwrap_err(); + assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}"); + assert_eq!((doc(&s), s.doc().unwrap().history.undo.len()), (&before, steps), "while editing: unchanged"); +} + /// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art, /// while a pattern is edited, and for art painted with the pattern itself, directly, through /// another pattern, through a symbol, through the paints a graph stores, through a graph design a diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 9cdec919b5..898c044c35 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -57,8 +57,9 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: /// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on /// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary` /// for a brush library's). A Brushes panel scatter, art or pattern -/// brush dropped where there is no art places a copy of its art there (`brush.placeArt`). A chip -/// follows the pointer meanwhile. +/// brush dropped where there is no art places a copy of its art there (`brush.placeArt`), and so +/// does a Swatches panel pattern swatch, with its tile (`pattern.placeArt`). A chip follows the +/// pointer meanwhile. pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) { crate::panels::swatches::drag_preview(app, ui.ctx()); let Some(pos) = ui.input(|i| i.pointer.interact_pos()) else { return }; @@ -119,6 +120,15 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } + // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile + // art with its tile, centered where it is dropped, to edit and Alt-drag back onto the swatch. + if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) { + let at = xf.to_doc(pos); + if let Err(e) = app.run("pattern.placeArt", json!({"name": pattern, "x": at.x, "y": at.y})) { + app.status(e); + } + return; + } let Some(hit) = hit else { return }; let Some(st) = app.session.active() else { return }; let (cmd, params) = match &*d { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..908f7a7844 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9842,6 +9842,50 @@ fn a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there() { } } +#[test] +fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { + use vectorcraft_color::{Color, Paint}; + use widgets::{PanelDrag, SwatchRows}; + 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": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let tile = app.session.execute("shape.rectangle", &json!({"x": 300, "y": 20, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("object.pattern.make", &json!({"ids": [tile], "name": "Checks", "edit": false})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let drop = |app: &mut VectorcraftApp, d: PanelDrag, at: Point| { + let at = xf.to_screen(at); + egui::DragAndDrop::set_payload(&ctx, d); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]); + }; + let swatch = |name: &str, paint: Paint| { + let rows = SwatchRows { grabbed: name.into(), names: vec![name.into()], groups: false }; + PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None } + }; + let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks")); + let undo_len = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let undo = undo_len(&app); + // A color swatch, and a pattern from elsewhere than the Swatches panel, place nothing. + drop(&mut app, swatch("Red", Paint::solid(Color::from_hex("#ed1c24").unwrap())), Point::new(250.0, 220.0)); + drop(&mut app, PanelDrag::paint(vectorcraft_doc::pattern::pattern_paint("Checks")), Point::new(250.0, 220.0)); + assert_eq!(undo_len(&app), undo); + // The pattern swatch: a copy of its tile art and tile, centered where it lands, selected. + drop(&mut app, pattern.clone(), Point::new(250.0, 220.0)); + let st = app.session.active().unwrap(); + assert_eq!(undo_len(&app), undo + 1, "{}", app.ui.status); + assert_eq!(st.history.undo.last().unwrap().label, "Place Pattern Art"); + let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; + let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); + assert!((b.center() - Point::new(250.0, 220.0)).hypot() < 0.1, "{b:?}"); + // On art, the swatch fills it as before. + drop(&mut app, pattern, Point::new(100.0, 100.0)); + let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); + assert!(matches!(&n, Paint::Pattern { pattern, .. } if pattern == "Checks"), "{n:?}"); +} + #[test] fn a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..f3f2642b89 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7518,6 +7518,7 @@ breakText Glyphs Глифи Place Brush Art Поставяне на графика на четка Replace Brush Art Замяна на графика на четка Replace Pattern Art Замяна на графика на мостра + Place Pattern Art Поставяне на графика на мостра Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Щрихи използват тази четка. Да се приложи ли новата графика към тези щрихи, или те да останат както са и да се добави копие на четката с новата графика? Apply to Strokes Прилагане към щрихите Leave Strokes Оставяне на щрихите diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..dfeda0bf71 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7567,6 +7567,7 @@ shape Open Otvoren Place Brush Art Postavi crtež četkice Replace Brush Art Zamijeni crtež četkice Replace Pattern Art Zamijeni crtež uzorka + Place Pattern Art Postavi crtež uzorka Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Potezi koriste ovu četkicu. Primijeniti novi crtež na te poteze ili ih ostaviti kakvi jesu i dodati kopiju četkice s novim crtežom? Apply to Strokes Primijeni na poteze Leave Strokes Ostavi poteze diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..4fae84451b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8399,6 +8399,7 @@ breakText Glyphs Glifs Place Brush Art Col·loca l’art del pinzell Replace Brush Art Substitueix l’art del pinzell Replace Pattern Art Substitueix l’art del motiu + Place Pattern Art Col·loca l’art del motiu Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Hi ha traços que fan servir aquest pinzell. Voleu aplicar l’art nou a aquests traços, o deixar-los com estan i afegir una còpia del pinzell amb l’art nou? Apply to Strokes Aplica als traços Leave Strokes Deixa els traços diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..6a003e834f 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8380,6 +8380,7 @@ breakText Glyphs Glyfy Place Brush Art Umístit kresbu štětce Replace Brush Art Nahradit kresbu štětce Replace Pattern Art Nahradit kresbu vzorku + Place Pattern Art Umístit kresbu vzorku Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Tahy používají tento štětec. Použít novou kresbu na tyto tahy, nebo je ponechat beze změny a přidat kopii štětce s novou kresbou? Apply to Strokes Použít na tahy Leave Strokes Ponechat tahy diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..4d4e1d1791 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10436,6 +10436,7 @@ breakText Glyphs Glyffer Place Brush Art Placér penselgrafik Replace Brush Art Erstat penselgrafik Replace Pattern Art Erstat mønstergrafik + Place Pattern Art Placér mønstergrafik Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Streger bruger denne pensel. Anvend den nye grafik på stregerne, eller lad dem være, som de er, og tilføj en kopi af penslen med den nye grafik? Apply to Strokes Anvend på streger Leave Strokes Bevar streger diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..9ee0901afe 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8005,6 +8005,7 @@ breakText Glyphs Glyphen Place Brush Art Pinselgrafik platzieren Replace Brush Art Pinselgrafik ersetzen Replace Pattern Art Mustergrafik ersetzen + Place Pattern Art Mustergrafik platzieren Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturen verwenden diesen Pinsel. Die neue Grafik auf diese Konturen anwenden oder sie unverändert lassen und eine Kopie des Pinsels mit der neuen Grafik hinzufügen? Apply to Strokes Auf Konturen anwenden Leave Strokes Konturen beibehalten diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..195ea82836 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8371,6 +8371,7 @@ breakText Glyphs Γλύφοι Place Brush Art Τοποθέτηση σχεδίου πινέλου Replace Brush Art Αντικατάσταση σχεδίου πινέλου Replace Pattern Art Αντικατάσταση σχεδίου μοτίβου + Place Pattern Art Τοποθέτηση σχεδίου μοτίβου Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Περιγράμματα χρησιμοποιούν αυτό το πινέλο. Να εφαρμοστεί το νέο σχέδιο σε αυτά τα περιγράμματα ή να μείνουν ως έχουν και να προστεθεί αντίγραφο του πινέλου με το νέο σχέδιο; Apply to Strokes Εφαρμογή στα περιγράμματα Leave Strokes Διατήρηση περιγραμμάτων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..e0d1f9cad3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8357,6 +8357,7 @@ breakText Glyphs Glifos Place Brush Art Colocar ilustración del pincel Replace Brush Art Reemplazar ilustración del pincel Replace Pattern Art Reemplazar ilustración del motivo + Place Pattern Art Colocar ilustración del motivo Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Algunos trazos usan este pincel. ¿Aplicar la nueva ilustración a esos trazos, o dejarlos como están y añadir una copia del pincel con la nueva ilustración? Apply to Strokes Aplicar a los trazos Leave Strokes Dejar los trazos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..c82597b70b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8447,6 +8447,7 @@ breakText Glyphs Merkit Place Brush Art Sijoita siveltimen kuvitus Replace Brush Art Korvaa siveltimen kuvitus Replace Pattern Art Korvaa kuvion kuvitus + Place Pattern Art Sijoita kuvion kuvitus Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Viivat käyttävät tätä sivellintä. Käytetäänkö uutta kuvitusta näissä viivoissa, vai jätetäänkö ne ennalleen ja lisätään siveltimestä kopio, jossa on uusi kuvitus? Apply to Strokes Käytä viivoihin Leave Strokes Jätä viivat ennalleen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..b4a1357166 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8376,6 +8376,7 @@ breakText Glyphs Glyphes Place Brush Art Placer l’illustration de la forme Replace Brush Art Remplacer l’illustration de la forme Replace Pattern Art Remplacer l’illustration du motif + Place Pattern Art Placer l’illustration du motif Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Des contours utilisent cette forme. Appliquer la nouvelle illustration à ces contours, ou les laisser tels quels et ajouter une copie de la forme avec la nouvelle illustration ? Apply to Strokes Appliquer aux contours Leave Strokes Conserver les contours diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..2696806612 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -5150,6 +5150,7 @@ antiAlias Sharp શાર્પ Place Brush Art બ્રશ આર્ટ પ્લેસ કરો Replace Brush Art બ્રશ આર્ટ બદલો Replace Pattern Art પેટર્ન આર્ટ બદલો + Place Pattern Art પેટર્ન આર્ટ પ્લેસ કરો Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? સ્ટ્રોક્સ આ બ્રશ વાપરે છે. તે સ્ટ્રોક્સ પર નવી આર્ટ લાગુ કરવી છે કે તેમને જેમ છે તેમ રાખીને નવી આર્ટવાળી બ્રશની નકલ ઉમેરવી છે? Apply to Strokes સ્ટ્રોક્સ પર લાગુ કરો Leave Strokes સ્ટ્રોક્સ જેમ છે તેમ રાખો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..1c00d27a9a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4531,6 +4531,7 @@ arrowhead Feather पंख Place Brush Art ब्रश आर्टवर्क रखें Replace Brush Art ब्रश आर्टवर्क बदलें Replace Pattern Art पैटर्न आर्टवर्क बदलें + Place Pattern Art पैटर्न आर्टवर्क रखें Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? स्ट्रोक्स इस ब्रश का उपयोग कर रहे हैं। नया आर्टवर्क उन स्ट्रोक्स पर लागू करें, या उन्हें जैसा है वैसा छोड़कर नए आर्टवर्क वाले ब्रश की एक कॉपी जोड़ें? Apply to Strokes स्ट्रोक्स पर लागू करें Leave Strokes स्ट्रोक्स जैसे हैं वैसे छोड़ें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..ef865a6414 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8366,6 +8366,7 @@ breakText Glyphs Glifák Place Brush Art Ecsetgrafika elhelyezése Replace Brush Art Ecsetgrafika cseréje Replace Pattern Art Mintázatgrafika cseréje + Place Pattern Art Mintázatgrafika elhelyezése Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Körvonalak használják ezt az ecsetet. Alkalmazod az új grafikát ezekre a körvonalakra, vagy változatlanul hagyod őket, és hozzáadod az ecset egy másolatát az új grafikával? Apply to Strokes Alkalmazás a körvonalakra Leave Strokes Körvonalak megtartása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..8372f7f977 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8221,6 +8221,7 @@ breakText Glyphs Glif Place Brush Art Tempatkan karya seni kuas Replace Brush Art Ganti karya seni kuas Replace Pattern Art Ganti karya seni pola + Place Pattern Art Tempatkan karya seni pola Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Stroke menggunakan kuas ini. Terapkan karya seni baru ke stroke tersebut, atau biarkan apa adanya dan tambahkan salinan kuas dengan karya seni baru? Apply to Strokes Terapkan ke Stroke Leave Strokes Biarkan Stroke diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..c2cf171f71 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8043,6 +8043,7 @@ breakText Glyphs Glifi Place Brush Art Inserisci grafica del pennello Replace Brush Art Sostituisci grafica del pennello Replace Pattern Art Sostituisci grafica del motivo + Place Pattern Art Inserisci grafica del motivo Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Alcune tracce usano questo pennello. Applicare la nuova grafica a queste tracce, o lasciarle come sono e aggiungere una copia del pennello con la nuova grafica? Apply to Strokes Applica alle tracce Leave Strokes Lascia le tracce diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..75bf59ef58 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9932,6 +9932,7 @@ breakText Glyphs 字形 Place Brush Art ブラシのアートを配置 Replace Brush Art ブラシのアートを置き換え Replace Pattern Art パターンのアートを置き換え + Place Pattern Art パターンのアートを配置 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? このブラシは線で使われています。新しいアートをそれらの線に適用しますか?それとも線をそのままにして、新しいアートを持つブラシのコピーを追加しますか? Apply to Strokes 線に適用 Leave Strokes 線を保持 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ae0f3fea37 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10554,6 +10554,7 @@ breakText Glyphs გლიფები Place Brush Art ფუნჯის ნახატის განთავსება Replace Brush Art ფუნჯის ნახატის ჩანაცვლება Replace Pattern Art პატერნის ნახატის ჩანაცვლება + Place Pattern Art პატერნის ნახატის განთავსება Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? კონტურები იყენებს ამ ფუნჯს. გამოყენებულ იქნას ახალი ნახატი ამ კონტურებზე, თუ დარჩეს ისინი როგორც არის და დაემატოს ფუნჯის ასლი ახალი ნახატით? Apply to Strokes კონტურებზე გამოყენება Leave Strokes კონტურების დატოვება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..0c8afe603c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8015,6 +8015,7 @@ breakText Glyphs 글리프 Place Brush Art 브러시 아트 배치 Replace Brush Art 브러시 아트 바꾸기 Replace Pattern Art 패턴 아트 바꾸기 + Place Pattern Art 패턴 아트 배치 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 선에서 이 브러시를 사용합니다. 새 아트를 해당 선에 적용하시겠습니까, 아니면 선을 그대로 두고 새 아트로 브러시 사본을 추가하시겠습니까? Apply to Strokes 선에 적용 Leave Strokes 선 유지 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..cf3aa33af9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10274,6 +10274,7 @@ breakText Glyphs Glyphs Place Brush Art Penseelillustratie plaatsen Replace Brush Art Penseelillustratie vervangen Replace Pattern Art Patroonillustratie vervangen + Place Pattern Art Patroonillustratie plaatsen Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Contouren gebruiken dit penseel. De nieuwe illustratie op deze contouren toepassen, of ze laten zoals ze zijn en een kopie van het penseel met de nieuwe illustratie toevoegen? Apply to Strokes Op contouren toepassen Leave Strokes Contouren behouden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..ae16f5e361 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8239,6 +8239,7 @@ breakText Glyphs Glify Place Brush Art Umieść kompozycję pędzla Replace Brush Art Zastąp kompozycję pędzla Replace Pattern Art Zastąp kompozycję wzorka + Place Pattern Art Umieść kompozycję wzorka Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Obrysy używają tego pędzla. Zastosować nową kompozycję do tych obrysów, czy pozostawić je bez zmian i dodać kopię pędzla z nową kompozycją? Apply to Strokes Zastosuj do obrysów Leave Strokes Pozostaw obrysy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..59275fc6c3 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8399,6 +8399,7 @@ breakText Glyphs Glifos Place Brush Art Colocar Arte do Pincel Replace Brush Art Substituir Arte do Pincel Replace Pattern Art Substituir Arte do Padrão + Place Pattern Art Colocar Arte do Padrão Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Traçados usam este pincel. Aplicar a nova arte a esses traçados, ou deixá-los como estão e adicionar uma cópia do pincel com a nova arte? Apply to Strokes Aplicar aos Traçados Leave Strokes Manter Traçados diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..010a3c8e26 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8371,6 +8371,7 @@ breakText Glyphs Глифы Place Brush Art Поместить рисунок кисти Replace Brush Art Заменить рисунок кисти Replace Pattern Art Заменить рисунок узора + Place Pattern Art Поместить рисунок узора Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обводки используют эту кисть. Применить новый рисунок к этим обводкам или оставить их как есть и добавить копию кисти с новым рисунком? Apply to Strokes Применить к обводкам Leave Strokes Оставить обводки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..8f5b68b23c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8415,6 +8415,7 @@ breakText Glyphs Glyfer Place Brush Art Placera penselgrafik Replace Brush Art Ersätt penselgrafik Replace Pattern Art Ersätt mönstergrafik + Place Pattern Art Placera mönstergrafik Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturer använder den här penseln. Använd den nya grafiken på konturerna, eller låt dem vara som de är och lägg till en kopia av penseln med den nya grafiken? Apply to Strokes Använd på konturer Leave Strokes Behåll konturer diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..27abc76472 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10270,6 +10270,7 @@ breakText Glyphs Glifler Place Brush Art Fırça Çizimini Yerleştir Replace Brush Art Fırça Çizimini Değiştir Replace Pattern Art Desen Çizimini Değiştir + Place Pattern Art Desen Çizimini Yerleştir Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturlar bu fırçayı kullanıyor. Yeni çizim bu konturlara uygulansın mı, yoksa konturlar olduğu gibi bırakılıp fırçanın yeni çizimli bir kopyası mı eklensin? Apply to Strokes Konturlara Uygula Leave Strokes Konturları Bırak diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..41ecd25cf7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8025,6 +8025,7 @@ breakText Glyphs Гліфи Place Brush Art Розмістити малюнок пензля Replace Brush Art Замінити малюнок пензля Replace Pattern Art Замінити малюнок візерунка + Place Pattern Art Розмістити малюнок візерунка Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обведення використовують цей пензель. Застосувати новий малюнок до цих обведень чи залишити їх як є і додати копію пензля з новим малюнком? Apply to Strokes Застосувати до обведень Leave Strokes Залишити обведення diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..61bfc96683 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8071,6 +8071,7 @@ breakText Glyphs Glyph Place Brush Art Đặt đối tượng của cọ Replace Brush Art Thay đối tượng của cọ Replace Pattern Art Thay đối tượng của họa tiết + Place Pattern Art Đặt đối tượng của họa tiết Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Có nét đang dùng cọ này. Áp dụng đối tượng mới cho các nét đó, hay giữ nguyên chúng và thêm một bản sao của cọ với đối tượng mới? Apply to Strokes Áp dụng cho nét Leave Strokes Giữ nguyên nét diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..cf31b8b7e3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8249,6 +8249,7 @@ breakText Glyphs 字形 Place Brush Art 置入画笔图稿 Replace Brush Art 替换画笔图稿 Replace Pattern Art 替换图案图稿 + Place Pattern Art 置入图案图稿 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有描边使用了此画笔。要将新图稿应用到这些描边,还是保留描边不变并添加一个使用新图稿的画笔副本? Apply to Strokes 应用于描边 Leave Strokes 保留描边 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..dd143d13b9 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8073,6 +8073,7 @@ breakText Glyphs 字符 Place Brush Art 置入筆刷圖稿 Replace Brush Art 取代筆刷圖稿 Replace Pattern Art 取代圖樣圖稿 + Place Pattern Art 置入圖樣圖稿 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有筆畫使用了此筆刷。要將新圖稿套用到這些筆畫,還是保留筆畫不變並加入一個使用新圖稿的筆刷複本? Apply to Strokes 套用至筆畫 Leave Strokes 保留筆畫 diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index da6698b6be..4f7edafc41 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -10,8 +10,10 @@ pub enum PanelDrag { /// A paint: Swatches panel tiles, a Fill/Stroke proxy, a Recent Colors chip, a Color Guide /// color or the Gradient panel's thumbnail. Art it is dropped on takes `params` (`{swatch}`, `{color}`, `{gradient}`…; /// null for a colour group, which paints nothing) through the active proxy's - /// `paint.setFill`/`paint.setStroke`; the Gradient panel's ramp takes its colour as a stop; the - /// Swatches panel moves `rows`, or makes a swatch of a paint dragged from elsewhere. `library`: + /// `paint.setFill`/`paint.setStroke`; a Swatches panel pattern swatch dropped where there is no + /// art places a copy of its tile art there (`pattern.placeArt`); the Gradient panel's ramp takes + /// its colour as a stop; the Swatches panel moves `rows`, or makes a swatch of a paint dragged + /// from elsewhere. `library`: /// the Libraries panel colour it is (library id, colour name), which that panel moves to where /// it is dropped. Paint { paint: Paint, params: serde_json::Value, rows: Option, library: Option<(String, String)> }, diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..155232b365 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6174,9 +6174,13 @@ details are VectorCraft's own rules; the help page says only that the option mov `object.pattern.replaceArt {name, ids?}` (Replace Pattern Art) makes copies of the selected art, or of `ids`, the tile art of pattern `name`, as one undo step, and returns `{name}`. The pattern keeps its name, its swatch and the swatch's -place, its tile and its options; with `sizeTileToArt` on, the tile is sized to the new art plus `hSpacing` and -`vSpacing`. Fills and strokes name the pattern, so every object painted with it draws the new tile. The art stays on the -canvas, selected as it was. Art that matches the tile art already records no undo step. The command is off while a +place, and its options. When the backmost object of the art is a rectangle with no fill and no stroke (or the backmost +member of one selected group, as `pattern.placeArt` places it), that rectangle becomes the tile and is left out of the +tile art, and the group's members become the art. Otherwise the tile keeps its size and moves by as much as the top-left +corner of the art's bounds moved from the old tile art's, so art drawn anywhere on the canvas stays in its tile. With +`sizeTileToArt` on, the tile is sized to the new art plus `hSpacing` and `vSpacing`. Fills and strokes name the pattern, +so every object painted with it draws the new tile. The art stays on the canvas, selected as it was. Art and a tile that +match the pattern's already record no undo step. A rectangle alone leaves no art and is refused. The command is off while a pattern is edited ("finish editing the pattern first"), and returns an error, changing nothing, for a missing `name`, a pattern that does not exist, no art, and art painted with the pattern itself, directly or through the symbols, other patterns, graph designs and brushes it uses, or the series and label paints a graph stores. In the Swatches panel, art dragged off the canvas and released with Alt (Option on macOS) held over a @@ -6184,7 +6188,22 @@ pattern swatch runs it with that swatch's pattern; the swatch is outlined while else in the list, or without Alt, the art becomes a new pattern swatch as before. The help page describes replacing a pattern by dragging its edited tile onto the old swatch with Alt or Option held, with the pattern updated in the file (, -archived copy). Keeping the tile, the options and the source art are VectorCraft's own rules. +archived copy). Keeping the tile's size, moving it with the art, the options and the source art are VectorCraft's own +rules. The help page describes a tile bounded by a rectangle that is the backmost object, with no fill and no stroke +(, archived copy). + +`pattern.placeArt {name, x?, y?}` (Place Pattern Art) places a copy of pattern `name`'s tile art, centered on (`x`, `y`) +(default: the center of the first artboard), in the layer new art goes into, selects it, and returns `{id}`, in one undo +step. The copy is one group: a rectangle of the pattern's tile with no fill and no stroke at its back, then the tile art +in its place in the tile, so `object.pattern.replaceArt` reads the edited copy back with the same tile. The pattern does +not change. The command is off while a pattern is edited ("finish editing the pattern first"), and returns an error, +changing nothing, for a missing `name`, a pattern that does not exist, an `x` or `y` that is not a number, a pattern +with no art ("no artwork") and a locked or hidden target layer. In the app, a pattern swatch dragged from the Swatches +panel onto an empty part of the canvas runs it at the drop point; dropped on art, the swatch fills it as before. The +help page describes changing a pattern by dragging its swatch onto the artboard, editing the tile there and Alt-dragging +it back onto the swatch +(, archived copy). The group, +its rectangle, the centering and the default position are VectorCraft's own rules. ```json {"name":"run_command","arguments":{"command":"pattern.options","params":{"showSwatchBounds":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..eadaf243ca 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -925,7 +925,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests/pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). - **Cancel, Delete and rename leave no paint of a missing pattern:** the help page lists Save a Copy, Done and Cancel for leaving pattern editing (https://helpx.adobe.com/illustrator/using/create-edit-patterns.html). Canceling a pattern made for the edit removes it with every swatch of it, a color group's included. Canceling a new pattern, `pattern.delete` and a `pattern.options` rename reach every paint of the pattern: art outside the editing layer, opacity mask art, type runs, symbol definitions, graph designs, the series and label paints a graph keeps for its next redraw, other patterns' tiles (a copy Save a Copy made included), graphic and character styles, brush art, and the fill, stroke and appearance new art takes. Canceling a new pattern and Delete make those paints no paint, a VectorCraft rule; a rename renames them. Canceling the edit of an existing pattern puts its definition back as it was when editing started; after a rename in Pattern Options, it also gives the pattern its old name back with its swatches and paints, unless another pattern, swatch or color group has taken that name. Undo and Redo restore new art's paints with the document. Tests in `tests/pattern.rs` cover each command. - **Move Tile with Art:** Pattern Options has the Move Tile with Art checkbox under Size Tile to Art, and with it on, moving the tile art in pattern editing mode moves the tile with it (). VectorCraft's own rules for what the page leaves open: the tile moves only when a move takes all of the tile art, by the same offset; rotations, scales, copies and anchor moves leave it in place; the option is off for a new pattern. `pattern.options {moveTileWithArt}` sets it and `pattern.list` reports it. Tests in `tests/pattern.rs` and `panels::pattern_options::tests` cover it. -- **Art Alt-dragged onto a pattern swatch replaces its tile art:** the help page describes dragging the edited tile onto the old pattern swatch with Alt (Option on macOS) held to replace the pattern and update it in the file (, archived copy). In the Swatches panel, art released this way over a pattern swatch becomes that pattern's tile art in one undo step (`object.pattern.replaceArt`), and every object painted with the pattern draws the new tile. VectorCraft's own rules: the pattern keeps its name, swatch, tile and options (Size Tile to Art refits the tile), the dragged art stays on the canvas, art that matches the tile records nothing, art painted with the pattern itself is refused, and Alt over any other swatch still makes a new pattern. Tests in `tests/pattern.rs` and `panels::swatches::tests` cover it. +- **Art Alt-dragged onto a pattern swatch replaces its tile art:** the help page describes dragging the edited tile onto the old pattern swatch with Alt (Option on macOS) held to replace the pattern and update it in the file (, archived copy). In the Swatches panel, art released this way over a pattern swatch becomes that pattern's tile art in one undo step (`object.pattern.replaceArt`), and every object painted with the pattern draws the new tile. VectorCraft's own rules: the pattern keeps its name, swatch and options, the tile keeps its size and moves with the art (Size Tile to Art refits the tile), the dragged art stays on the canvas, art that matches the tile records nothing, art painted with the pattern itself is refused, and Alt over any other swatch still makes a new pattern. Tests in `tests/pattern.rs` and `panels::swatches::tests` cover it. +- **A pattern swatch dragged onto empty canvas places its tile art:** the help page describes changing a pattern by dragging its swatch onto the artboard, editing the tile there and dragging it back onto the swatch with Alt (, archived copy), and a tile bounded by a backmost rectangle with no fill and no stroke (). A pattern swatch released over an empty part of the canvas places a copy of the pattern's tile art at the drop point, selected, in one undo step (`pattern.placeArt`); dropped on art, it still fills that art. `object.pattern.replaceArt` reads an unpainted rectangle at the back of the art as the tile. VectorCraft's own rules: the copy is one group with an unpainted rectangle of the tile at its back, centered on the drop point, and the pattern itself does not change. Tests in `tests/pattern.rs` and `canvas::tests` cover it. - **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`. - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** a Transform section comes first (#5219): the reference point the Transform panel and Control bar share, the active artboard's X and Y (of that point) and W and H with the Constrain Width and Height Proportions link, its preset and orientation, and Move and Scale Artwork with Artboard. The Artboards section follows, with the name field, Artboard Options and Fill. The active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). From e94a8aed63ce72c12780f140265119e9269b1ec1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:38:57 -0800 Subject: [PATCH 003/160] Swatches: a drop inside a filled shape fills it with Path Only on With Object Selection by Path Only on, a pattern swatch or a brush with art dropped inside a filled object, away from its outline, found no art under the pointer and placed a copy of the tile art or brush art there. The empty-canvas check now counts fills (and type by its area), as the mesh-point check does, so the drop fills the object instead. The unpainted tile rectangle that object.pattern.replaceArt and brush.replaceArt read also has to run around its four corners in order: a closed path through them in a crossing order is art, not the tile. --- crates/engine/src/cmd/brushsym/brushes.rs | 7 +++++-- crates/engine/src/tests/pattern.rs | 13 +++++++++++++ crates/ui-egui/src/canvas/context.rs | 15 ++++++++++++++- crates/ui-egui/src/canvas/tests.rs | 21 +++++++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index afdf7d9f60..efcb425091 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -769,7 +769,8 @@ pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result { /// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]), and /// the tile such a rectangle at the back of a pattern's art marks (`object.pattern.replaceArt`): the /// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its -/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance. +/// bounds in order around them (either way), without curves, whose fills and strokes paint nothing +/// and that has no other appearance. pub(crate) fn frame_marker(n: &Node) -> Option { let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None }; let unpainted = n.appearance.effects.is_empty() @@ -782,7 +783,9 @@ pub(crate) fn frame_marker(n: &Node) -> Option { let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)]; let at_corners = sp.anchors.len() == 4 && sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p) - && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)); + && corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c)) + // Each side, the closing one included, joins two corners that share an edge. + && sp.anchors.iter().zip(sp.anchors.iter().cycle().skip(1)).all(|(a, b)| a.p.x == b.p.x || a.p.y == b.p.y); (unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r) } diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index d45376ae82..36403a736a 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -391,6 +391,19 @@ fn only_an_unpainted_rectangle_at_the_back_is_the_tile() { // A rectangle alone is a tile with no art. let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [back.0]})).unwrap_err(); assert!(err.to_string().contains("select the art for the pattern tile"), "{err}"); + // An unpainted path through the four corners of its bounds in a crossing order is not a + // rectangle: art. + let corners = [(200, 200), (240, 240), (240, 200), (200, 240)]; + let anchors: Vec<_> = corners.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + let bowtie = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [bowtie.0], "none": true})).unwrap(); + sel(&mut s, &[bowtie]); + s.execute("object.arrange.sendToBack", &json!({})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [bowtie.0, front.0]})).unwrap(); + let def = doc(&s).pattern("Dots").unwrap(); + assert_eq!(def.art.len(), 2, "the crossing path is art: {:?}", def.art); + assert_ne!(def.tile, Rect::new(200.0, 200.0, 240.0, 240.0), "the crossing path is not the tile"); } /// Place Pattern Art is refused, changing nothing, for a missing or unknown name, a position that diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index 898c044c35..584332b8af 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -113,6 +113,7 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons // of its art, centered where it is dropped, to edit and Alt-drag back onto the brush. if let (None, widgets::PanelDrag::Brush { name, def }) = (&hit, &*d) && matches!(def["type"].as_str(), Some("scatter" | "art" | "pattern")) + && no_art_at(app, xf.to_doc(pos), xf.zoom) { let at = xf.to_doc(pos); if let Err(e) = app.run("brush.placeArt", json!({"name": name, "x": at.x, "y": at.y})) { @@ -122,7 +123,9 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } // A pattern swatch from the Swatches panel dropped where there is no art: a copy of its tile // art with its tile, centered where it is dropped, to edit and Alt-drag back onto the swatch. - if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) { + if let (None, widgets::PanelDrag::Paint { paint: vectorcraft_color::Paint::Pattern { pattern, .. }, rows: Some(_), .. }) = (&hit, &*d) + && no_art_at(app, xf.to_doc(pos), xf.zoom) + { let at = xf.to_doc(pos); if let Err(e) = app.run("pattern.placeArt", json!({"name": pattern, "x": at.x, "y": at.y})) { app.status(e); @@ -177,6 +180,16 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } } +/// Whether no art is under document point `p` at `zoom`, with fills counted even with Object +/// Selection by Path Only and type objects by their area even with Type Object Selection by Path +/// Only: a brush's or a pattern swatch's art is placed only there. +fn no_art_at(app: &VectorcraftApp, p: vectorcraft_geom::Point, zoom: f64) -> bool { + hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, type_path_only: false, ..opt }) + }) + .is_none() +} + /// The selected, editable gradient mesh and its points that a solid color dropped at document /// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh /// (fills count even with Object Selection by Path Only, and clipping applies), and the points are diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 908f7a7844..8b59e2734d 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -9840,6 +9840,19 @@ fn a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there() { assert_eq!(n.children().unwrap()[0].name.as_deref(), Some("Side Tile")); } } + // With Object Selection by Path Only, inside a filled rectangle and away from its outline is + // still on art: nothing is placed. (The placed copies are undone first.) + for _ in 0..3 { + app.session.execute("edit.undo", &json!({})).unwrap(); + } + app.session.execute("shape.rectangle", &json!({"x": 250, "y": 200, "width": 100, "height": 80})).unwrap(); + app.session.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let before = app.session.active().unwrap().history.undo.len(); + drop(&mut app, "Arrow", Point::new(300.0, 240.0)); + assert_eq!(app.session.active().unwrap().history.undo.len(), before, "{}", app.ui.status); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); } #[test] @@ -9880,6 +9893,14 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { let [placed] = st.selection.objects.as_slice() else { panic!("one object selected: {:?}", st.selection.objects) }; let b = st.doc.node(*placed).unwrap().geometric_bounds().unwrap(); assert!((b.center() - Point::new(250.0, 220.0)).hypot() < 0.1, "{b:?}"); + // With Object Selection by Path Only, inside the filled rectangle and away from its outline is + // still on art: nothing is placed. + app.session.execute("paint.setFill", &json!({"ids": [id], "color": "#ffffff"})).unwrap(); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let before = undo_len(&app); + drop(&mut app, pattern.clone(), Point::new(100.0, 100.0)); + assert_eq!(undo_len(&app), before, "{}", app.ui.status); + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); // On art, the swatch fills it as before. drop(&mut app, pattern, Point::new(100.0, 100.0)); let n = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); From 71e2f35b3b65b9f6d4827eeb1fef0e2571d62d1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:41:54 -0800 Subject: [PATCH 004/160] Web: the Paintbrush records an airbrush pen's stylus wheel The web build reads Pointer Events' tangentialPressure (-1..1, https://www.w3.org/TR/pointerevents3/#dom-pointerevent-tangentialpressure) for each pen sample, including the positions a fast stroke's events coalesce, and gives the Paintbrush the wheel as 0..1, as the macOS reader does. Pointer Events give 0 for a pen without a wheel, so 0 counts as no wheel until the pen has reported another value since it came near; another pen, the other end, a canceled press and leaving the hover range start afresh. Mouse and finger input reads no wheel. The canvas now pairs the feed's per-move poses with the moves of a frame that carries touch events (the web pen), keeping the touch's force as the pressure, so each move keeps its own wheel. --- apps/vectorcraft-web/src/pencil.rs | 191 ++++++++++++++++++++++++++--- crates/ui-egui/src/canvas/drag.rs | 7 +- crates/ui-egui/src/canvas/tests.rs | 59 +++++++++ docs/target-app-parity.md | 4 +- 4 files changed, 241 insertions(+), 20 deletions(-) diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 88b85e9d50..620d38ef1f 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -50,11 +50,31 @@ pub struct Pointers { eraser: bool, /// The pen's pressure and end for the canvas (`Services::stylus`). stylus: StylusFeed, + /// The pen whose finger wheel is read ([`Pointers::wheel`]). + wheel: Option, +} + +/// A pen, by pointer id and the end it is turned to, and whether it has reported a tangential +/// pressure other than 0 since it came near. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Wheel { + id: i32, + eraser: bool, + reads: bool, } impl Default for Pointers { fn default() -> Self { - Self { events: vec![], pen: None, fingers: vec![], primary: None, button: None, eraser: false, stylus: StylusFeed::on_ui_thread() } + Self { + events: vec![], + pen: None, + fingers: vec![], + primary: None, + button: None, + eraser: false, + stylus: StylusFeed::on_ui_thread(), + wheel: None, + } } } @@ -67,6 +87,8 @@ struct Input<'a> { id: i32, button: i16, pressure: f32, + /// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel. + tangential: f32, modifiers: egui::Modifiers, } @@ -93,9 +115,29 @@ impl Pointers { self.stylus.clone() } - /// A pen moved or pressed with `pressure`, with the end it last pressed with. - fn pen_sample(&self, pressure: f32) { - self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser, pose: PenPose::default() })); + /// A pen pressed, moved or lifted with `pressure` and `wheel`, with the end it last pressed + /// with. With `moved`, the sample comes with one `PointerMoved` and the feed keeps it for that + /// move ([`StylusFeed::set_move`]), so the canvas pairs each move with its own wheel. + fn pen_sample(&self, pressure: f32, wheel: Option, moved: bool) { + let sample = PenSample { pressure, eraser: self.eraser, pose: PenPose { wheel, ..PenPose::default() } }; + if moved { + self.stylus.set_move(sample); + } else { + self.stylus.set_sample(Some(sample)); + } + } + + /// The finger wheel of pen `id`, turned to the end it last pressed with, for a sample with + /// Pointer Events' `tangentialPressure` (−1..1, + /// ): [`PenPose`]'s + /// wheel of 0..1, −1 at 0 and 1 at 1, a value past either end clamped. Pointer Events give 0 + /// for a pen without a wheel, so 0 reads as none until that pen, with that end, has reported a + /// value other than 0 since it came near. A value that is not a number is none. + fn wheel(&mut self, id: i32, tangential: f32) -> Option { + let known = self.wheel.is_some_and(|w| w.id == id && w.eraser == self.eraser && w.reads); + let reads = known || (tangential.is_finite() && tangential != 0.0); + self.wheel = Some(Wheel { id, eraser: self.eraser, reads }); + (reads && tangential.is_finite()).then(|| (tangential.clamp(-1.0, 1.0) + 1.0) / 2.0) } fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option) { @@ -135,7 +177,10 @@ impl Pointers { } /// Follow one pointer event; `true` if it was the pen's or a finger's (taken from eframe). - fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32)], on_canvas: bool) -> bool { + /// + /// `coalesced` holds the positions the pen reported since the last event, each with its + /// pressure and tangential pressure, the last one at `pos`. + fn feed(&mut self, kind: &str, e: &Input<'_>, pos: Pos2, coalesced: &[(Pos2, f32, f32)], on_canvas: bool) -> bool { let id = e.id; if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") { // Another pointer moved while no pen presses (a palm under a pen pressing is @@ -164,19 +209,24 @@ impl Pointers { if let Some(end) = end { self.eraser = end; } - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.pen = Some(id); self.touch(PEN_DEVICE, id, TouchPhase::Start, pos, force); self.press(id, pos, button, e.modifiers); } "pointermove" if self.pen == Some(id) => { - self.pen_sample(e.pressure); // The positions the pen reported between two events (up to 240 a second - // on an iPad), each with its pressure, so fast strokes keep their curve. - for c in coalesced.iter().take(coalesced.len().saturating_sub(1)) { - self.touch(PEN_DEVICE, id, TouchPhase::Move, c.0, Some(c.1)); - self.events.push(Event::PointerMoved(c.0)); + // on an iPad), each with its pressure and wheel, so fast strokes keep + // their curve. + for &(at, pressure, tangential) in coalesced.iter().take(coalesced.len().saturating_sub(1)) { + let wheel = self.wheel(id, tangential); + self.pen_sample(pressure, wheel, true); + self.touch(PEN_DEVICE, id, TouchPhase::Move, at, Some(pressure)); + self.events.push(Event::PointerMoved(at)); } + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.touch(PEN_DEVICE, id, TouchPhase::Move, pos, force); self.events.push(Event::PointerMoved(pos)); } @@ -190,12 +240,19 @@ impl Pointers { } // Pointer Events report no end while a pen hovers: it keeps the end it // last pressed with. - self.pen_sample(e.pressure); + let wheel = self.wheel(id, e.tangential); + self.pen_sample(e.pressure, wheel, true); self.events.push(Event::PointerMoved(pos)); } "pointerup" | "pointercancel" if self.pen == Some(id) => { - let phase = if kind == "pointerup" { TouchPhase::End } else { TouchPhase::Cancel }; - self.pen_sample(0.0); + let (phase, wheel) = if kind == "pointerup" { + // Lifted, the pen hovers on and keeps what it read of its wheel. + (TouchPhase::End, self.wheel(id, e.tangential)) + } else { + self.wheel = None; + (TouchPhase::Cancel, None) + }; + self.pen_sample(0.0, wheel, false); self.pen = None; self.touch(PEN_DEVICE, id, phase, pos, None); self.release(pos, e.modifiers); @@ -205,6 +262,11 @@ impl Pointers { if kind == "pointerleave" && self.primary.is_none() && on_canvas { self.events.push(Event::PointerGone); } + // Left the hover range or canceled: the pen reads its wheel afresh. + let gone = (kind == "pointerleave" && on_canvas && self.pen.is_none()) || kind == "pointercancel"; + if gone && self.wheel.is_some_and(|w| w.id == id) { + self.wheel = None; + } return self.pen.is_some(); } } @@ -277,7 +339,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, let z = runner.egui_ctx().zoom_factor(); let pos = egui::pos2((e.client_x() as f32 - rect.left() as f32) / z, (e.client_y() as f32 - rect.top() as f32) / z); let at = |x: i32, y: i32| egui::pos2((x as f32 - rect.left() as f32) / z, (y as f32 - rect.top() as f32) / z); - let coalesced: Vec<(Pos2, f32)> = if kind == "pointermove" + let coalesced: Vec<(Pos2, f32, f32)> = if kind == "pointermove" && e.pointer_type() == "pen" // Safari before 17 hasn't it, and calling a missing method would abort the app. && js_sys::Reflect::has(&e, &"getCoalescedEvents".into()).unwrap_or(false) @@ -285,7 +347,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, e.get_coalesced_events() .iter() .filter_map(|c| c.dyn_into::().ok()) - .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0))) + .map(|c| (at(c.client_x(), c.client_y()), c.pressure().clamp(0.0, 1.0), c.tangential_pressure())) .collect() } else { vec![] @@ -296,6 +358,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, id: e.pointer_id(), button: e.button(), pressure: e.pressure(), + tangential: e.tangential_pressure(), // Same semantics as eframe's modifiers_from_mouse_event. modifiers: egui::Modifiers { alt: e.alt_key(), @@ -344,7 +407,7 @@ mod tests { use super::*; fn input(pointer_type: &str, button: i16) -> Input<'_> { - Input { pointer_type, id: 7, button, pressure: 0.6, modifiers: egui::Modifiers::default() } + Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, modifiers: egui::Modifiers::default() } } fn reset() { @@ -501,6 +564,100 @@ mod tests { reset(); } + fn pen_at(button: i16, tangential: f32) -> Input<'static> { + Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, modifiers: egui::Modifiers::default() } + } + + fn wheels(feed: &StylusFeed) -> Vec> { + feed.take_moves().into_iter().map(|(_, q)| q.wheel).collect() + } + + /// An airbrush pen's finger wheel (Pointer Events' `tangentialPressure`, −1..1) reaches the + /// feed as 0..1 with each move, once the pen has reported a value other than 0. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + assert!(p.feed("pointerdown", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + for t in [0.0, -1.0, 0.5, 0.0, 3.0, f32::NAN, -0.5] { + assert!(p.feed("pointermove", &pen_at(-1, t), Pos2::ZERO, &[], true)); + } + assert_eq!( + wheels(&feed), + [None, None, Some(0.0), Some(0.75), Some(0.5), Some(1.0), None, Some(0.25)], + "none until reported; then 0 is half way, past the ends is clamped and not a number is none" + ); + assert!(p.feed("pointerup", &pen_at(0, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.5), "the lift keeps the wheel"); + reset(); + } + + /// The positions a fast stroke's event coalesced keep their own wheel, in order, and the + /// event's own position comes last with its own. + #[test] + fn coalesced_moves_keep_their_wheel() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + let (a, b, c) = (Pos2::new(1.0, 2.0), Pos2::new(3.0, 4.0), Pos2::new(5.0, 6.0)); + assert!(p.feed("pointerdown", &pen_at(0, -1.0), Pos2::ZERO, &[], true)); + let coalesced = [(a, 0.3, -0.5), (b, 0.4, 0.5), (c, 0.5, 0.75)]; + assert!(p.feed("pointermove", &pen_at(-1, 1.0), c, &coalesced, true)); + let moved: Vec = p.take().into_iter().filter_map(|e| if let Event::PointerMoved(at) = e { Some(at) } else { None }).collect(); + let kept = feed.take_moves(); + assert_eq!(moved, [Pos2::ZERO, a, b, c]); + assert_eq!(kept.iter().map(|(_, q)| q.wheel).collect::>(), [Some(0.0), Some(0.25), Some(0.75), Some(1.0)]); + assert_eq!(kept.iter().map(|&(f, _)| f).collect::>(), [0.6, 0.3, 0.4, 0.6], "each move keeps its pressure too"); + reset(); + } + + /// A pen that leaves the hover range, a canceled press, another pen and the other end each + /// read the wheel afresh; a lift into hover does not. A mouse or a finger reads no wheel. + #[test] + fn the_wheel_is_read_afresh_for_each_pen_and_end() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + let learn = |p: &mut Pointers, button: i16| { + assert!(p.feed("pointerdown", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(button, 0.5), Pos2::ZERO, &[], true)); + }; + let hover = |p: &mut Pointers, id: i32| { + let mut e = pen_at(-1, 0.0); + e.id = id; + e.pressure = 0.0; + assert!(p.feed("pointermove", &e, Pos2::ZERO, &[], true)); + }; + learn(&mut p, 0); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&Some(0.5)), "a lift into hover keeps it"); + p.feed("pointerleave", &pen_at(-1, 0.0), Pos2::ZERO, &[], true); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&None), "left the hover range"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointercancel", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a canceled press"); + hover(&mut p, 7); + assert_eq!(wheels(&feed).last(), Some(&None), "after a canceled press"); + learn(&mut p, 0); + hover(&mut p, 8); + assert_eq!(wheels(&feed).last(), Some(&None), "another pen"); + learn(&mut p, 0); + assert!(p.feed("pointerdown", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&None), "the other end"); + assert!(p.feed("pointerup", &pen_at(ERASER_BUTTON, 0.0), Pos2::ZERO, &[], true)); + for (pointer_type, kind) in [("mouse", "pointermove"), ("touch", "pointerdown"), ("touch", "pointermove")] { + let mut other = pen_at(0, 0.5); + (other.pointer_type, other.id) = (pointer_type, 10); + p.feed(kind, &other, Pos2::ZERO, &[], true); + assert_eq!(feed.pose(), None, "{pointer_type} {kind}"); + assert!(feed.take_moves().is_empty(), "{pointer_type} {kind}"); + } + reset(); + } + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the /// eraser end for the canvas's next frame. #[test] diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 512df6e9a9..a96873d5aa 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -193,7 +193,7 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// The positions this frame's pointer moves passed through before its last one, each with the /// pen force a touch event gave just before it, or the pressure the host's feed kept for that move /// ([`StylusFeed::take_moves`], macOS), if any, and the tilt and rotation the feed kept for that -/// move (empty when the pen read neither), if any. The last move is the pointer's position; the +/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). The last move is the pointer's position; the /// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no /// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, /// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that @@ -222,6 +222,11 @@ pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option< _ => {} } } + // A web pen's feed kept a pose (its wheel) for each of its moves: paired from the end, + // as below, with the touch's force kept as the pressure. + for (m, &(_, q)) in moves.iter_mut().rev().zip(samples.iter().rev()) { + m.2 = Some(q); + } } else if !samples.is_empty() { // The feed's last sample is the last move's: pair them from the end. A lift's 0 is // no pressure (the press keeps its last touch). diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..8a642f7667 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -11983,6 +11983,65 @@ fn moves_in_the_release_frame_reach_the_paintbrush_with_their_tilt() { } } +/// The web build's pen comes as touch events with its pressure as their force, and its feed keeps +/// a wheel for each move: [`frame_moves`] keeps the touch's force and pairs each move with its own +/// pose from the end, and the last move's pose comes second. +#[test] +fn frame_moves_pair_a_web_pens_touches_with_the_feeds_poses() { + let ctx = egui::Context::default(); + let (a, b, c) = (pos2(10.0, 20.0), pos2(20.0, 30.0), pos2(30.0, 40.0)); + let events = [pen(egui::TouchPhase::Move, a, 0.2), pen(egui::TouchPhase::Move, b, 0.8), pen(egui::TouchPhase::Move, c, 0.6)].concat(); + let feed = StylusFeed::default(); + let wheel = |w: f32| PenPose { wheel: Some(w), ..PenPose::default() }; + for (p, w) in [(0.9, 0.0), (0.2, 0.25), (0.8, 0.5), (0.6, 0.75)] { + feed.set_move(crate::stylus::PenSample { pressure: p, pose: wheel(w), ..Default::default() }); + } + let (mut moves, mut last) = (vec![], None); + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| (moves, last) = frame_moves(ui, Some(&feed), None)); + out.textures_delta.clear(); + assert_eq!(moves, [(a, Some(0.2), Some(wheel(0.25))), (b, Some(0.8), Some(wheel(0.5)))], "an older move's sample is left over"); + assert_eq!(last, Some(wheel(0.75))); +} + +/// A web pen's stroke reaches the Paintbrush with each move's pressure, from its touch, and each +/// move's finger wheel, from the feed. +#[test] +fn a_web_pens_wheel_reaches_the_paintbrush_with_each_move() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let feed = StylusFeed::default(); + app.services.stylus = Some(feed.clone()); + app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + app.select_tool("paintbrush"); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let at = |x: f64| xf.to_screen(Point::new(x, 300.0)); + let moved = |pressure: f32, wheel: f32| { + feed.set_move(crate::stylus::PenSample { pressure, pose: PenPose { wheel: Some(wheel), ..PenPose::default() }, ..Default::default() }) + }; + moved(0.5, 0.0); + frame(&mut app, &ctx, pen(egui::TouchPhase::Start, at(300.0), 0.5)); + let mut events = vec![]; + for (x, pressure, wheel) in [(340.0, 0.3, 0.25), (380.0, 0.7, 0.5), (420.0, 0.9, 0.75), (460.0, 0.4, 1.0)] { + moved(pressure, wheel); + events.extend(pen(egui::TouchPhase::Move, at(x), pressure)); + } + frame(&mut app, &ctx, events); + frame(&mut app, &ctx, pen(egui::TouchPhase::End, at(460.0), 0.4)); + let (cmd, p) = app.session.journal.last().unwrap().clone(); + assert_eq!(cmd, "path.freehand"); + let points = p["points"].as_array().unwrap(); + let column = |i: usize| -> Vec { points.iter().filter_map(|s| s.get(i).and_then(serde_json::Value::as_f64)).collect() }; + let (pressures, wheels) = (column(2), column(6)); + for (pressure, wheel) in [(0.3, 0.25), (0.7, 0.5), (0.9, 0.75)] { + let paired = points.iter().any(|s| { + let near = |i: usize, v: f64| s.get(i).and_then(serde_json::Value::as_f64).is_some_and(|got| (got - v).abs() < 0.01); + near(2, pressure) && near(6, wheel) + }); + assert!(paired, "{pressure} with {wheel}: {pressures:?} {wheels:?}"); + } +} + /// The last move of a frame reaches the Paintbrush with the tilt the host's feed kept for that /// move, not with a later pen sample that came without a move. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..dba4dd200d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2057,7 +2057,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2065,7 +2065,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). - - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). + - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, on macOS from AppKit's `tangentialPressure`, and in the web build from Pointer Events' `tangentialPressure` (), for each move of a pen including the positions a fast stroke's events coalesce; Windows pointer messages have no field for it. Pointer Events give 0 for a pen without a wheel, so in the web build, as on macOS, 0 counts as no wheel until the pen has reported another value since it came near; the web build reads the wheel afresh for another pen, the other end, a canceled press and a pen that left the hover range. That rule is VectorCraft's own. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft), `pencil::tests::an_airbrush_wheel_goes_into_the_feed`, `pencil::tests::coalesced_moves_keep_their_wheel` and `pencil::tests::the_wheel_is_read_afresh_for_each_pen_and_end` (vectorcraft-web), `canvas::tests::a_web_pens_wheel_reaches_the_paintbrush_with_each_move` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. Bristle Brush Options and `brush.new` take a bristle brush name of at most 31 characters, as the Brushes page states for the Bristle Brush Options. The Name field stops taking characters at 31, and `brush.new` and `brush.options` refuse a longer new name with an error that names the limit. The page does not say how the limit counts characters or what happens to longer names already saved; counting characters and the number added to a taken name, keeping longer saved names, and leaving `brush.duplicate` unlimited are VectorCraft's own rules. A bristle brush that a document or a saved file already holds under a longer name keeps it, and the other brush types take a name of any length. Test: `bristle_brush_names_have_at_most_31_characters` in `tests/brushsym.rs`. Public reference: [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) (archived copy). From 32fa158676215acf084360fd0b8e43e52b4c8fbe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:20:02 -0800 Subject: [PATCH 005/160] Stylus: docs name the web build as a source of the airbrush wheel The stylus module doc and StylusFeed::set_move now say the web build reads the wheel from Pointer Events' tangentialPressure and keeps a pose for each move. The frame_moves doc comment is rewrapped. --- crates/ui-egui/src/canvas/drag.rs | 15 ++++++++------- crates/ui-egui/src/stylus.rs | 9 +++++---- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index a96873d5aa..71e09a39ff 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -193,13 +193,14 @@ pub(super) type FrameMove = (Pos2, Option, Option); /// The positions this frame's pointer moves passed through before its last one, each with the /// pen force a touch event gave just before it, or the pressure the host's feed kept for that move /// ([`StylusFeed::take_moves`], macOS), if any, and the tilt and rotation the feed kept for that -/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). The last move is the pointer's position; the -/// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no -/// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels, -/// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that -/// button's button-up in this frame, if it came: the moves after it are hover, and the button-up's -/// position is the pointer's. The last move before it is left out only when it is at that -/// position; its tilt and rotation come second either way. +/// move (empty when the pen read neither), if any, with touch events too (the web build's pen). +/// The last move is the pointer's position; the tilt and rotation the feed kept for it come +/// second, if any. A mouse's moves count too, with no pressure: a fast mouse stroke otherwise keeps +/// one position a frame, a sample every few pixels, too few for a low Fidelity to follow the hand +/// (#3328). With `release`, the moves stop at that button's button-up in this frame, if it came: +/// the moves after it are hover, and the button-up's position is the pointer's. The last move +/// before it is left out only when it is at that position; its tilt and rotation come second +/// either way. pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option) -> (Vec, Option) { let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default(); ui.input(|i| { diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs index 0b27d24127..1111b5983e 100644 --- a/crates/ui-egui/src/stylus.rs +++ b/crates/ui-egui/src/stylus.rs @@ -12,8 +12,9 @@ //! each pointer message of a pen before winit handles it. The canvas uses the pressure when a //! frame's events carry no touch force, and the tilt and rotation for each press, drag and release. //! An airbrush pen's finger wheel comes with the tilt and rotation ([`PenPose::wheel`]) where the -//! host reads it: from XInput2 on X11 and from AppKit on macOS. The app does not read it on -//! Windows, whose pointer messages have no field for it, or in the web build. +//! host reads it: from XInput2 on X11, from AppKit on macOS and from Pointer Events' +//! `tangentialPressure` in the web build. The app does not read it on Windows, whose pointer +//! messages have no field for it. //! //! The feed also says which end of the pen moved. Turning the pen to its eraser end selects the //! Eraser tool, and turning it back to the tip selects the tool used before @@ -157,8 +158,8 @@ impl StylusFeed { } /// Like [`Self::set_sample`], for a pen sample that comes with one pointer move of the window, - /// read before the window handles the move (macOS): its pressure, tilt and rotation are also - /// kept for that move ([`Self::take_moves`]). + /// read before the window handles the move (macOS and the web build): its pressure, tilt, + /// rotation and wheel are also kept for that move ([`Self::take_moves`]). pub fn set_move(&self, sample: PenSample) { self.set_sample(Some(sample)); let mut pen = self.lock(); From 8833fde4a962923df8ebc4a6c15bc8bcb05fbaee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:04:53 -0800 Subject: [PATCH 006/160] Web: the stylus wheel stays learned when the pen hovers across the canvas edge A hovering pen that moved off the canvas onto another element cleared what it had read of its airbrush wheel, so back on the canvas a centered wheel (0) read as no wheel. The pen now reads its wheel afresh only when a pointerleave names no element it moved onto (relatedTarget), which is how leaving the hover range is reported, on the canvas or off it. --- apps/vectorcraft-web/src/pencil.rs | 38 ++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/apps/vectorcraft-web/src/pencil.rs b/apps/vectorcraft-web/src/pencil.rs index 620d38ef1f..f19939bde8 100644 --- a/apps/vectorcraft-web/src/pencil.rs +++ b/apps/vectorcraft-web/src/pencil.rs @@ -89,6 +89,9 @@ struct Input<'a> { pressure: f32, /// Pointer Events' `tangentialPressure`, −1..1: an airbrush pen's finger wheel. tangential: f32, + /// Whether the event names an element the pointer moved onto (`relatedTarget`): a pen leaving + /// one element for another is still in its hover range. + entered: bool, modifiers: egui::Modifiers, } @@ -262,8 +265,10 @@ impl Pointers { if kind == "pointerleave" && self.primary.is_none() && on_canvas { self.events.push(Event::PointerGone); } - // Left the hover range or canceled: the pen reads its wheel afresh. - let gone = (kind == "pointerleave" && on_canvas && self.pen.is_none()) || kind == "pointercancel"; + // Left the hover range (a leave onto no element, on the canvas or off it) + // or canceled: the pen reads its wheel afresh. Moving onto another element + // keeps what it read. + let gone = (kind == "pointerleave" && !e.entered && self.pen.is_none()) || kind == "pointercancel"; if gone && self.wheel.is_some_and(|w| w.id == id) { self.wheel = None; } @@ -359,6 +364,7 @@ pub fn install(runner: &eframe::WebRunner, canvas: &web_sys::HtmlCanvasElement, button: e.button(), pressure: e.pressure(), tangential: e.tangential_pressure(), + entered: e.related_target().is_some(), // Same semantics as eframe's modifiers_from_mouse_event. modifiers: egui::Modifiers { alt: e.alt_key(), @@ -407,7 +413,7 @@ mod tests { use super::*; fn input(pointer_type: &str, button: i16) -> Input<'_> { - Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, modifiers: egui::Modifiers::default() } + Input { pointer_type, id: 7, button, pressure: 0.6, tangential: 0.0, entered: false, modifiers: egui::Modifiers::default() } } fn reset() { @@ -565,7 +571,7 @@ mod tests { } fn pen_at(button: i16, tangential: f32) -> Input<'static> { - Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, modifiers: egui::Modifiers::default() } + Input { pointer_type: "pen", id: 7, button, pressure: 0.6, tangential, entered: false, modifiers: egui::Modifiers::default() } } fn wheels(feed: &StylusFeed) -> Vec> { @@ -658,6 +664,30 @@ mod tests { reset(); } + /// A hovering pen that moves off the canvas onto another element and back keeps what it read + /// of its wheel; one that leaves the hover range off the canvas reads it afresh. + #[test] + fn the_wheel_survives_crossing_the_canvas_edge() { + reset(); + let mut p = Pointers::default(); + let feed = p.stylus(); + assert!(p.feed("pointerdown", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + assert!(p.feed("pointerup", &pen_at(0, 0.5), Pos2::ZERO, &[], true)); + let mut hover = pen_at(-1, 0.0); + hover.pressure = 0.0; + let mut onto = pen_at(-1, 0.0); + (onto.pressure, onto.entered) = (0.0, true); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + assert!(!p.feed("pointermove", &hover, Pos2::ZERO, &[], false)); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&Some(0.5)), "moved onto another element and back"); + p.feed("pointerleave", &onto, Pos2::ZERO, &[], true); + p.feed("pointerleave", &hover, Pos2::ZERO, &[], false); + assert!(p.feed("pointermove", &hover, Pos2::ZERO, &[], true)); + assert_eq!(wheels(&feed).last(), Some(&None), "left the hover range off the canvas"); + reset(); + } + /// A palm that lands or moves while the eraser end presses is rejected, and the feed keeps the /// eraser end for the canvas's next frame. #[test] From b57d3393eb6f3dc14cfbde0260816440fca08ee0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:09:31 -0800 Subject: [PATCH 007/160] 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 008/160] 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 009/160] 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 010/160] 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 90752660adc593f619518d6882b357a0ee6fe63c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:18:50 -0800 Subject: [PATCH 011/160] Scripts: documents give scripts their variables, data sets and variable libraries A script's Document has variables, dataSets, activeDataset, variablesLocked, importVariables(file) and exportVariables(file), with the Variables, Variable, Datasets and Dataset classes and the VariableKind enumeration. Every page item has visibilityVariable, and type, placed and raster images and graphs have contentVariable. Each change runs a variable.* or dataset.* command and joins the run's undo step; a value that changes nothing runs no command. - variable.setBinding binds one object's visibility or content slot to one variable, or to none, in one undo step. - dataset.update takes a name, to update a data set that is not the active one without switching to it. - A File crosses to the host as its path under a hidden key, and a plain object that carries the key is refused. importVariables and exportVariables check the path against what the script's own File objects may read or write; the open documents' files do not count. Docs: docs/mcp.md, docs/target-app-parity.md, docs/gaps.md (G6). --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/variablecmds.rs | 89 +- crates/engine/src/file_access.rs | 3 +- crates/engine/src/script/dom.rs | 21 +- crates/engine/src/script/dom/variables.rs | 802 ++++++++++++++++++ crates/engine/src/script/mod.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_variables.rs | 433 ++++++++++ crates/js/src/file_classes.rs | 13 + crates/js/src/host.rs | 12 +- crates/js/src/host_classes.rs | 13 + crates/js/src/lib.rs | 2 +- docs/gaps.md | 3 +- docs/mcp.md | 36 +- docs/target-app-parity.md | 1 + 16 files changed, 1416 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/script/dom/variables.rs create mode 100644 crates/engine/src/tests/script_variables.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..538b9e0dbf 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -952,6 +952,8 @@ pub use variablecmds::utf16_order_without_mark; /// file: its size limit, its text, its cells and the data `graph.setData` takes from them. pub use graph::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph_data_text, graph_grid_from_text}; +/// The kind of variable that drives an object's content (`variable.setBinding`). +pub(crate) use variablecmds::content_kind; /// The Variables panel's sort (`variable.sort`) and its rows in that order. pub use variablecmds::{VariableSort, VariableSortKey, variable_order}; diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..33aaab396e 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -727,6 +727,7 @@ pub(super) const ALLOWED: &[&str] = &[ "variable.makeTextDynamic", "variable.makeVisibilityDynamic", "variable.rename", + "variable.setBinding", "variable.sort", "variable.unbind", ]; diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index ea6647b7a4..fdd4231dc3 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -451,6 +451,73 @@ fn unbind(s: &mut Session, p: &Value) -> Result { Ok(json!({"unbound": n})) } +/// The kind of variable that drives the content of `n`: text for type, image for an image object +/// and graph for a graph root. `None` for other objects, which have only a visibility slot. +pub(crate) fn content_kind(n: &vectorcraft_doc::Node) -> Option { + match &n.kind { + NodeKind::Text(_) => Some(VariableKind::Text), + NodeKind::Image(_) => Some(VariableKind::Image), + _ if n.extras().graph.is_some() => Some(VariableKind::Graph), + _ => None, + } +} + +/// The variables of `kind` bound to `id`, in the order they are defined. +fn bound_of_kind(vars: &Variables, id: NodeId, kind: VariableKind) -> Vec { + let Some(bound) = vars.bindings.get(&id) else { return Vec::new() }; + vars.variables.iter().filter(|v| v.kind == kind && bound.contains(&v.name)).map(|v| v.name.clone()).collect() +} + +/// The slot `variable.setBinding` names: an object's visibility, or its content. +fn slot_kind(doc: &Document, id: NodeId, p: &Value, cmd: &str) -> Result<(&'static str, VariableKind)> { + let node = doc.node(id).ok_or(EngineError::NoNode(id))?; + match str_param(p, "slot") { + Some("visibility") => Ok(("visibility", VariableKind::Visibility)), + Some("content") => { + content_kind(node).map(|k| ("content", k)).ok_or_else(|| bad(cmd, format!("node {} has no content a variable can drive", id.0))) + } + _ => Err(bad(cmd, "`slot` must be `visibility` or `content`")), + } +} + +/// Bind one object's visibility or content to one variable, or to none, in one undo step: the +/// object's other variables of that slot's kind are unbound. The content of type takes a text +/// variable, of a linked image an image variable and of a graph root a graph variable; an embedded +/// image can't be bound to an image variable. The checks of `variable.bind` apply, and nothing +/// changes when one fails. A call that leaves the bindings as they were adds no undo step. +fn set_binding(s: &mut Session, p: &Value) -> Result { + const C: &str = "variable.setBinding"; + let id = p.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| bad(C, "`id` must be an object id"))?; + let variable = match p.get("variable") { + None | Some(Value::Null) => None, + Some(v) => Some(named(v.as_str(), "variable", C)?), + }; + let doc = &s.doc()?.doc; + let (slot, kind) = slot_kind(doc, id, p, C)?; + if let Some(name) = &variable { + let have = doc.variables.variable(name).map(|v| v.kind).ok_or_else(|| bad(C, format!("no variable named `{name}`")))?; + if have != kind { + return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); + } + check_bindable(doc, &[id], kind, C)?; + if matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); + } + } + let unbound: Vec = bound_of_kind(&doc.variables, id, kind).into_iter().filter(|n| Some(n) != variable.as_ref()).collect(); + let label = if variable.is_some() { "Bind Variable" } else { "Unbind Variable" }; + edit_variables(s, label, |vars| { + for n in &unbound { + vars.unbind(id, n); + } + if let Some(n) = &variable { + vars.bind(id, n); + } + Ok(()) + })?; + Ok(json!({"id": id.0, "slot": slot, "variable": variable, "unbound": unbound})) +} + /// The `variable` a command names, which must be defined; `None` when it names none. fn defined_variable(s: &Session, p: &Value, cmd: &str) -> Result> { let name = optional_name(p, "variable", cmd)?; @@ -690,13 +757,18 @@ fn dataset_capture(s: &mut Session, p: &Value) -> Result { /// other than a visibility variable, locked or inside a locked layer or group, or, for any /// variable, on a locked artboard) keeps the row's value. With `all`, every other variable the /// objects report a value for is added to the row. Without an active row there is nothing to -/// update, so say so rather than picking one. With every bound object locked, no value is -/// written; an update that writes no value adds no undo step. +/// update, so say so rather than picking one. `name` updates that row instead, and leaves the +/// active row as it is. With every bound object locked, no value is written; an update that +/// writes no value adds no undo step. fn dataset_update(s: &mut Session, p: &Value) -> Result { const C: &str = "dataset.update"; let all = bool_or(p, "all", false); + let given = match p.get("name") { + None => None, + Some(v) => Some(named(v.as_str(), "name", C)?), + }; let st = s.doc()?; - let Some(name) = st.doc.variables.active_dataset.clone() else { + let Some(name) = given.or_else(|| st.doc.variables.active_dataset.clone()) else { return Err(bad(C, "no active data set")); }; if !anything_bound(&st.doc) { @@ -975,6 +1047,15 @@ pub fn specs() -> Vec { has_doc, unbind ), + cmd!( + "variable.setBinding", + "Bind Variable", + [], + None, + "{id, slot: visibility|content, variable?} bind the object `id`'s visibility or content to one variable, or with `variable` left out or null to none, in one undo step (none when the bindings stay as they were): the object's other variables of that slot's kind are unbound. The content of type takes a text variable, of a linked image an image variable and of a graph root a graph variable; other objects have no content slot, and an embedded image can't be bound to an image variable. A variable of another kind is refused, and so is art variable.bind refuses → {id, slot, variable, unbound: [name…]}", + has_doc, + set_binding + ), cmd!( "variable.lock", "Lock Variables", @@ -1027,7 +1108,7 @@ pub fn specs() -> Vec { "Update Data Set", ["Window", "Variables"], None, - "{all?: bool} write what the bound objects hold now into the active dataset, for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", + "{all?: bool, name?} write what the bound objects hold now into the active dataset (with `name`, into that dataset, leaving the active one as it is), for each variable the dataset holds; a variable whose objects report no value (gone, on a locked artboard, or, for a variable other than a visibility variable, locked or inside a locked layer or group) keeps the dataset's value. `all: true` also adds every other variable the objects report a value for; `left` names the variables it didn't write → {values, left}", has_doc, dataset_update ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..f61179f43d 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -300,7 +300,8 @@ impl ScriptGate { ScriptGate { also: Some(also), ..self.clone() } } - fn check(&self, path: &str, access: Access) -> Result<(), String> { + /// May `path` be read (or written) through this gate? + pub(crate) fn check(&self, path: &str, access: Access) -> Result<(), String> { if let Some(also) = &self.also { also.check(path, access)?; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index dd17bb579e..a7303cf4e6 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,15 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod variables; + +pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; + +/// After each command a script runs ([`variables::after_command`]). +pub(super) fn after_command(h: &Host, id: &str) { + variables::after_command(h, id); +} + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -85,13 +94,14 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; 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, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, whether a call's own savepoint +/// ([`atomically`]) is open, and the `Variable` and `Dataset` objects it gave out. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + vars: variables::Handles, } impl State { @@ -1660,6 +1670,7 @@ 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)?; } + variables::define_enums(realm)?; let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -1714,6 +1725,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "Document", m)), ); + document.extend(variables::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1763,7 +1775,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "tags", "uRL", "uuid", - "visibilityVariable", "wrapInside", "wrapOffset", "wrapped", @@ -1776,8 +1787,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .into_iter() .map(|m| later(l, "PageItem", m)), ); + page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None))); + classes.extend(variables::classes(l)); 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", &[]))]) } diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs new file mode 100644 index 0000000000..270a7cfc08 --- /dev/null +++ b/crates/engine/src/script/dom/variables.rs @@ -0,0 +1,802 @@ +//! Variables and data sets in the script object model: `Document.variables`, `dataSets`, +//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`, +//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the +//! help pages , +//! , +//! , +//! , +//! , +//! and +//! describe them. Every change runs +//! one of the `variable.*` and `dataset.*` commands. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change +//! made through the object keeps the object working; once the name leaves the document any other +//! way (a delete, a rename by another command, an undo, a kind change by another command, or an +//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or +//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most +//! [`MAX_HANDLES`] of each. +//! - Collections list variables and data sets in the order the document holds them, counted from +//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`. +//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first +//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data +//! set named `Data Set 1` and so on, which becomes the active one. +//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`, +//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file +//! declared without one VectorCraft knows, and cannot be given. +//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order. +//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows +//! its values in the art, as `display()` does. +//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the +//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the +//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all. +//! An embedded image (`RasterItem`) cannot take an image variable. +//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the +//! script may read, or write, as its `File` objects may: the files of the open documents do not +//! count. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; + +use serde_json::json; +use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, file_ref_path, host_ref}; + +use super::{ + Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, + handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, +}; +use crate::doc::{Node, Variable, VariableKind}; +use crate::file_access::Access; + +/// The error for a `Variable` whose variable left the document, or that came from an earlier run. +pub const STALE_VARIABLE: &str = "Stale variable"; +/// The error for a `Dataset` whose data set left the document, or that came from an earlier run. +pub const STALE_DATASET: &str = "Stale data set"; +/// The most `Variable` objects, and the most `Dataset` objects, one run gives out. +pub const MAX_HANDLES: usize = 10_000; + +/// The kinds, each with the name of its `VariableKind` member. +const KINDS: [(VariableKind, &str); 5] = [ + (VariableKind::Text, "TEXTUAL"), + (VariableKind::Visibility, "VISIBILITY"), + (VariableKind::Image, "IMAGE"), + (VariableKind::Graph, "GRAPH"), + (VariableKind::Unknown, "Unknown"), +]; + +/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a +/// variable (`None` for a data set) and whether it still names it. +struct Entry { + uid: u64, + name: String, + kind: Option, + alive: bool, +} + +/// The objects of one class a run gave out: each one's handle is its index here. +#[derive(Default)] +struct Table { + entries: Vec, + /// The entry that names each document's name, while it does. + live: HashMap<(u64, String), usize>, +} + +impl Table { + /// The entry for `name` of the document `uid`, made when there is none. + fn slot(&mut self, uid: u64, name: &str, kind: Option, what: &str) -> std::result::Result { + if let Some(&at) = self.live.get(&(uid, name.to_string())) + && self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind) + { + return Ok(at); + } + if self.entries.len() >= MAX_HANDLES { + return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run"))); + } + self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true }); + let at = self.entries.len() - 1; + self.live.insert((uid, name.to_string()), at); + Ok(at) + } + + /// The entry `at` no longer names anything. + fn kill(&mut self, at: usize) { + if let Some(e) = self.entries.get_mut(at) { + e.alive = false; + let k = (e.uid, std::mem::take(&mut e.name)); + if self.live.get(&k) == Some(&at) { + self.live.remove(&k); + } + } + } + + /// The entry `at` names `name`, of `kind`, from now on: a rename made through it. + fn rename(&mut self, at: usize, name: &str, kind: Option) { + let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return }; + self.kill(at); + if let Some(e) = self.entries.get_mut(at) { + *e = Entry { uid, name: name.to_string(), kind, alive: true }; + } + self.live.insert((uid, name.to_string()), at); + } + + /// Kills each live entry `keep` refuses. + fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) { + let gone: Vec = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect(); + for at in gone { + self.kill(at); + } + } +} + +/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last +/// checked against it. +#[derive(Default)] +pub(super) struct Handles { + vars: RefCell, + sets: RefCell
, + seen: RefCell>, +} + +/// After each command a script runs: the objects whose variable or data set it removed stop +/// working, so one made again under the same name does not bring them back. A command that replaces +/// the data sets (an import) stops every `Dataset` of its document. +pub(super) fn after_command(h: &Host, id: &str) { + let hs = &h.dom.vars; + if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { + return; + } + let Ok(s) = h.session.try_borrow() else { return }; + let replaced = matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import").then(|| s.active().map(|st| st.uid)).flatten(); + let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); + let changed: HashSet = { + let seen = hs.seen.borrow(); + now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect() + }; + *hs.seen.borrow_mut() = now; + if changed.is_empty() && replaced.is_none() { + return; + } + let mut kinds: HashMap> = HashMap::new(); + let mut sets: HashMap> = HashMap::new(); + for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) { + let vars = &st.doc.variables; + kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect()); + sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect()); + } + hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind); + hs.sets + .borrow_mut() + .sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str())))); +} + +fn kind_text(k: VariableKind) -> Data { + let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n); + text(format!("VariableKind.{name}")) +} + +fn kind_of(d: &Data) -> std::result::Result { + let found = match d { + Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k), + _ => None, + }; + match found { + Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())), + Some(k) => Ok(k), + None => Err(HostError::Type("kind must be a VariableKind value".into())), + } +} + +/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes. +fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("the {what} is too long"))); + } + Ok(s) +} + +/// The `name` field of a command's result. +fn result_name(d: &Data) -> Option { + let Data::Object(o) = d else { return None }; + o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None }) +} + +fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer { + let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?; + Ok(host_ref("Variable", &[float(h.run), float(at as u64)])) +} + +fn set_ref(h: &Host, uid: u64, name: &str) -> Answer { + let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?; + Ok(host_ref("Dataset", &[float(h.run), float(at as u64)])) +} + +/// A variable or data set an object names: its document, its handle's index and its name. +struct Named { + doc: Doc, + at: usize, + name: String, + kind: Option, +} + +/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its +/// document. +fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result { + let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) }; + let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) }; + let stale = || HostError::Error(stale.into()); + if whole(run) != Some(h.run) { + return Err(stale()); + } + let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?; + let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets }; + let (uid, name, kind) = { + let t = table.borrow(); + let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?; + (e.uid, e.name.clone(), e.kind) + }; + let doc = find_doc(h, float(h.run), float(uid)); + let there = doc.is_some_and(|doc| { + with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() } + }) + }); + match doc { + Some(doc) if there => Ok(Named { doc, at, name, kind }), + _ => { + table.borrow_mut().kill(at); + Err(stale()) + } + } +} + +fn this_var(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), true) +} + +fn this_set(h: &Host, a: &[Data]) -> std::result::Result { + named_of(h, arg(a, 0), false) +} + +/// The index argument of a collection's indexer: a whole number, or `None`. +fn index_arg(d: &Data) -> Option { + match d { + Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()), + _ => None, + } +} + +// ---- Document ---- + +fn this_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Document") +} + +fn doc_variables(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Variables", &[float(h.run), float(doc.uid)])) +} + +fn doc_datasets(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)])) +} + +fn doc_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked))) +} + +/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so. +fn doc_set_locked(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) }; + if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked { + on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?; + } + Ok(Data::Undefined) +} + +fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Null), + } +} + +/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active +/// one and the art already shows it. +fn display(h: &Host, set: &Named) -> Answer { + let shown = with_doc(h, set.doc, |_, st| { + let vars = &st.doc.variables; + vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values())) + }); + if !shown { + on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?; + } + Ok(Data::Undefined) +} + +fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + if handle_of(arg(a, 1), "Dataset").is_none() { + return Err(HostError::Type("activeDataset must be a Dataset".into())); + } + let set = named_of(h, arg(a, 1), false)?; + if set.doc.uid != doc.uid { + return Err(HostError::Error("the data set is in another document".into())); + } + display(h, &set) +} + +/// The path of the `File` argument of `what`, which must be a file the script may reach for +/// `access` through its own `File` objects. +fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result { + let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) }; + if path.chars().count() > super::super::files::MAX_PATH_CHARS { + return Err(HostError::Range(format!("{what}: the path is too long"))); + } + let gate = h.disk.borrow().gate(Vec::new()); + gate.check(path, access).map_err(HostError::Error)?; + Ok(path.to_string()) +} + +/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's +/// variables and data sets with the library's. +fn doc_import(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "importVariables", Access::Read)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +/// `exportVariables(file)`: `variable.saveLibrary` into the file. +fn doc_export(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_arg(h, a, "exportVariables", Access::Write)?; + on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?; + Ok(Data::Undefined) +} + +// ---- Variables ---- + +fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Variables") +} + +fn vars_typename(h: &Host, a: &[Data]) -> Answer { + vars_doc(h, a)?; + Ok(text("Variables")) +} + +fn vars_length(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64))) +} + +fn vars_parent(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn vars_at(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) { + Some(v) => var_ref(h, doc.uid, &v), + None => Ok(Data::Undefined), + } +} + +fn vars_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.variables.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.variable(name).cloned()) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v)) +} + +fn vars_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => vars_by_name(h, a), + Data::Number(_) => match vars_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the +/// first free name). → the new variable. +fn vars_add(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let name = with_doc(h, doc, |_, st| { + let vars = &st.doc.variables; + (1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default() + }); + on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?; + var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text }) +} + +/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is +/// none. +fn vars_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = vars_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Variable ---- + +fn var_typename(h: &Host, a: &[Data]) -> Answer { + this_var(h, a)?; + Ok(text("Variable")) +} + +fn var_parent(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(doc_ref(h, v.doc.uid)) +} + +fn var_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_var(h, a)?.name)) +} + +/// `name = text`: `variable.rename`, which trims it, with no command when the name stays. +fn var_set_name(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == v.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind); + Ok(Data::Undefined) +} + +fn var_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown))) +} + +/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot +/// hold it and drops the variable's values, with no command when the kind stays. +fn var_set_kind(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + let kind = kind_of(arg(a, 1))?; + if Some(kind) == v.kind { + return Ok(Data::Undefined); + } + on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?; + h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind)); + Ok(Data::Undefined) +} + +fn var_page_items(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + with_doc(h, v.doc, |_, st| { + let ids: Vec = + st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect(); + if ids.len() > MAX_LISTED { + return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects"))); + } + h.charge_call(16 * ids.len() as u64)?; + Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect())) + }) +} + +/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values. +fn var_remove(h: &Host, a: &[Data]) -> Answer { + let v = this_var(h, a)?; + on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?; + h.dom.vars.vars.borrow_mut().kill(v.at); + Ok(Data::Undefined) +} + +// ---- Datasets ---- + +fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Datasets") +} + +fn sets_typename(h: &Host, a: &[Data]) -> Answer { + sets_doc(h, a)?; + Ok(text("Datasets")) +} + +fn sets_length(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64))) +} + +fn sets_parent(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn sets_at(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) }; + match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) { + Some(name) => set_ref(h, doc.uid, &name), + None => Ok(Data::Undefined), + } +} + +fn sets_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let name = name_arg(arg(a, 1), "name")?; + let found = with_doc(h, doc, |_, st| { + h.charge_call(st.doc.variables.datasets.len() as u64)?; + Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone())) + })?; + found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n)) +} + +fn sets_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => sets_by_name(h, a), + Data::Number(_) => match sets_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new +/// data set and makes it the active one. → the new data set. +fn sets_add(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?; + let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?; + set_ref(h, doc.uid, &name) +} + +/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is +/// none. +fn sets_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = sets_doc(h, a)?; + let names: Vec = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect()); + if !names.is_empty() { + on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?; + } + Ok(Data::Undefined) +} + +// ---- Dataset ---- + +fn set_typename(h: &Host, a: &[Data]) -> Answer { + this_set(h, a)?; + Ok(text("Dataset")) +} + +fn set_parent(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + Ok(doc_ref(h, d.doc.uid)) +} + +fn set_name(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_set(h, a)?.name)) +} + +/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays. +fn set_set_name(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let to = name_arg(arg(a, 1), "name")?; + if to.trim() == d.name { + return Ok(Data::Undefined); + } + let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?; + let name = result_name(&r).unwrap_or_else(|| to.trim().to_string()); + h.dom.vars.sets.borrow_mut().rename(d.at, &name, None); + Ok(Data::Undefined) +} + +fn set_display(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + display(h, &d) +} + +/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no +/// command when it already holds what the bound objects hold. +fn set_update(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + let same = with_doc(h, d.doc, |_, st| { + let doc = &st.doc; + let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some()); + bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values())) + }); + if !same { + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?; + } + Ok(Data::Undefined) +} + +/// `dataset.remove()`: `dataset.delete` of this data set. +fn set_remove(h: &Host, a: &[Data]) -> Answer { + let d = this_set(h, a)?; + on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?; + h.dom.vars.sets.borrow_mut().kill(d.at); + Ok(Data::Undefined) +} + +// ---- Page items ---- + +/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its +/// content. +fn slot_kind(n: &Node, content: bool) -> std::result::Result { + if !content { + return Ok(VariableKind::Visibility); + } + crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into())) +} + +/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's +/// kind bound to the object, in the order the variables are defined, or `null`. +fn binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let found = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned()) + })?; + match found { + Some(v) => var_ref(h, item.doc.uid, &v), + None => Ok(Data::Null), + } +} + +/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of +/// the object's document, or with none for `null`. No command runs when the object already has just +/// that binding of the slot's kind. +fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer { + let item = item_of(h, arg(a, 0))?; + let variable = match arg(a, 1) { + Data::Null => None, + d if handle_of(d, "Variable").is_some() => { + let v = named_of(h, d, true)?; + if v.doc.uid != item.doc.uid { + return Err(HostError::Error("the variable is in another document".into())); + } + Some(v.name) + } + _ => return Err(HostError::Type("give a Variable or null".into())), + }; + let same = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let kind = slot_kind(n, content)?; + let vars = &st.doc.variables; + let bound = vars.bindings.get(&item.id); + let held: Vec<&str> = + vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect(); + Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::>()) + })?; + if !same { + let slot = if content { "content" } else { "visibility" }; + edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?; + } + Ok(Data::Undefined) +} + +fn item_visibility(h: &Host, a: &[Data]) -> Answer { + binding(h, a, false) +} + +fn item_set_visibility(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, false) +} + +fn item_content(h: &Host, a: &[Data]) -> Answer { + binding(h, a, true) +} + +fn item_set_content(h: &Host, a: &[Data]) -> Answer { + set_binding(h, a, true) +} + +// ---- Registration ---- + +/// The members this module adds to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("variables", get(l, doc_variables)), + ("dataSets", get(l, doc_datasets)), + ("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset)), + ("variablesLocked", property(l, doc_locked, doc_set_locked)), + ("importVariables", method(l, doc_import)), + ("exportVariables", method(l, doc_export)), + ]) +} + +/// The members this module adds to `PageItem`. +pub(super) fn page_item_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility))]) +} + +/// The members this module adds to the page item class `class`. +pub(super) fn item_members(l: &Link, class: &str) -> Vec<(String, HostMember)> { + match class { + "TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => named(vec![("contentVariable", property(l, item_content, item_set_content))]), + _ => Vec::new(), + } +} + +/// The classes this module adds. +pub(super) fn classes(l: &Link) -> Vec { + vec![ + class( + "Variables", + None, + named(vec![ + ("typename", get(l, vars_typename)), + ("length", get(l, vars_length)), + ("parent", get(l, vars_parent)), + ("index", method(l, vars_index)), + ("getByName", method(l, vars_by_name)), + ("add", method(l, vars_add)), + ("removeAll", method(l, vars_remove_all)), + ]), + Some(function(l, vars_at)), + ), + class( + "Variable", + None, + named(vec![ + ("typename", get(l, var_typename)), + ("parent", get(l, var_parent)), + ("name", property(l, var_name, var_set_name)), + ("kind", property(l, var_kind, var_set_kind)), + ("pageItems", get(l, var_page_items)), + ("remove", method(l, var_remove)), + ]), + None, + ), + class( + "Datasets", + None, + named(vec![ + ("typename", get(l, sets_typename)), + ("length", get(l, sets_length)), + ("parent", get(l, sets_parent)), + ("index", method(l, sets_index)), + ("getByName", method(l, sets_by_name)), + ("add", method(l, sets_add)), + ("removeAll", method(l, sets_remove_all)), + ]), + Some(function(l, sets_at)), + ), + class( + "Dataset", + None, + named(vec![ + ("typename", get(l, set_typename)), + ("parent", get(l, set_parent)), + ("name", property(l, set_name, set_set_name)), + ("display", method(l, set_display)), + ("update", method(l, set_update)), + ("remove", method(l, set_remove)), + ]), + None, + ), + ] +} + +/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings. +pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect(); + realm.define_host_object("VariableKind", items) +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..0780a34e98 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1346,6 +1346,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + dom::after_command(host, &id); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..f62236f90f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_variables; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs new file mode 100644 index 0000000000..e60afb03d2 --- /dev/null +++ b/crates/engine/src/tests/script_variables.rs @@ -0,0 +1,433 @@ +//! Variables and data sets in the script object model: `Document.variables` and `dataSets`, the +//! variables page items are bound to, Lock Variables, and `importVariables` and `exportVariables`. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::tests_links::{Folder, RED, place, png, write}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A document with a type object and a rectangle. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Hello"})).unwrap()["id"].as_u64().unwrap()); + let r = NodeId(s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + (s, t, r) +} + +fn variables(s: &Session) -> Vec<(String, &'static str)> { + s.active().unwrap().doc.variables.variables.iter().map(|v| (v.name.clone(), v.kind.label())).collect() +} + +#[test] +fn variables_collection_adds_finds_renames_and_removes() { + let (mut s, _, _) = doc(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var v = app.activeDocument.variables; + vc.log(v.length); vc.log(v.typename); vc.log(v.parent.typename); + var a = v.add(), b = v.add(); + vc.log([a.name, b.name, a.kind, v.length].join()); + b.name = 'title'; b.kind = VariableKind.VISIBILITY; + vc.log([b.name, b.kind, v.getByName('title').name, v.index(0).name, v[1].name].join()); + vc.log(v[2] === undefined && v[-1] === undefined && v[0.5] === undefined); + a.remove(); vc.log(v.length); vc.log(b.parent.typename + ',' + b.typename);"#, + ); + assert_eq!( + out, + vec![ + json!(0), + json!("Variables"), + json!("Document"), + json!("Variable1,Variable2,VariableKind.TEXTUAL,2"), + json!("title,VariableKind.VISIBILITY,title,Variable1,title"), + json!(true), + json!(1), + json!("Document,Variable") + ] + ); + assert_eq!(variables(&s), vec![("title".to_string(), "visibility")]); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + assert!(failure(&mut s, "app.activeDocument.variables.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(4);").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.variables.index(true);").contains("name or an index")); +} + +#[test] +fn variable_names_and_kinds_are_checked_before_anything_changes() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "a", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "b", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 'a';").contains("already exists")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = ' ';").contains("newName")); + assert!(failure(&mut s, "app.activeDocument.variables[1].name = 5;").contains("must be a string")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = 'text';").contains("VariableKind")); + assert!(failure(&mut s, "app.activeDocument.variables[0].kind = VariableKind.Unknown;").contains("Unknown")); + let long = "x".repeat(5000); + assert!(failure(&mut s, &format!("app.activeDocument.variables[0].name = '{long}';")).contains("too long")); + // Setting what the variable already has runs no command. + log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'a'; v.name = ' a '; v.kind = VariableKind.TEXTUAL;"); + assert_eq!(undo_steps(&s), before); + assert_eq!(variables(&s), vec![("a".to_string(), "text"), ("b".to_string(), "text")]); +} + +#[test] +fn a_variable_object_goes_stale_and_stays_stale_when_the_name_comes_back() { + let (mut s, _, _) = doc(); + let e = failure( + &mut s, + "var v = app.activeDocument.variables.add();\ + vc.run('variable.delete', {names: ['Variable1']}); vc.run('variable.define', {name: 'Variable1', kind: 'text'});\ + v.name;", + ); + assert!(e.contains("Stale variable"), "{e}"); + // A failed run keeps nothing, so the variable is defined outside the script. + s.execute("variable.define", &json!({"name": "Variable1", "kind": "text"})).unwrap(); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; vc.run('variable.rename', {name: 'Variable1', kind: 'image'}); v.kind;"); + assert!(e.contains("Stale variable"), "{e}"); + let e = failure(&mut s, "var v = app.activeDocument.variables[0]; v.remove(); vc.run('edit.undo'); v.name;"); + assert!(e.contains("Stale variable"), "{e}"); + // A rename through the object keeps it. + assert_eq!(log(&mut s, "var v = app.activeDocument.variables[0]; v.name = 'renamed'; vc.log(v.name);"), vec![json!("renamed")]); + // A named engine keeps its globals, but an object from an earlier run is stale. + run(&mut s, "#targetengine keepvars\nvar held = app.activeDocument.variables[0];").unwrap(); + let e = failure(&mut s, "#targetengine keepvars\nheld.name;"); + assert!(e.contains("Stale variable"), "{e}"); +} + +#[test] +fn collections_from_an_earlier_run_throw_on_every_member() { + let (mut s, _, _) = doc(); + run(&mut s, "#targetengine keepcols\nvar v = app.activeDocument.variables, d = app.activeDocument.dataSets;").unwrap(); + for member in ["v.typename", "v.parent", "v.length", "d.typename", "d.parent", "d.length"] { + let e = failure(&mut s, &format!("#targetengine keepcols\n{member};")); + assert!(e.contains("Stale document"), "{member}: {e}"); + } +} + +#[test] +fn content_and_visibility_variables_bind_one_variable_per_slot() { + let (mut s, t, r) = doc(); + for (name, kind) in [("title", "text"), ("other", "text"), ("show", "visibility"), ("hide", "visibility")] { + s.execute("variable.define", &json!({"name": name, "kind": kind})).unwrap(); + } + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, v = d.variables, t = d.pageItems[0], r = d.pageItems[1]; + vc.log(t.contentVariable === null && t.visibilityVariable === null); + t.contentVariable = v.getByName('title'); t.contentVariable = v.getByName('other'); + r.visibilityVariable = v.getByName('show'); r.visibilityVariable = v.getByName('hide'); + vc.log(t.contentVariable.name + ',' + r.visibilityVariable.name); + vc.log(v.getByName('hide').pageItems.length + ',' + v.getByName('hide').pageItems[0].typename); + vc.log(r.contentVariable === undefined);"#, + ); + assert_eq!(out, vec![json!(true), json!("other,hide"), json!("1,PathItem"), json!(true)]); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["other".to_string()])); + assert_eq!(vars.bindings.get(&r).map(|b| b.iter().cloned().collect::>()), Some(vec!["hide".to_string()])); + assert_eq!(undo_steps(&s), before + 1); + // A variable of another kind is refused, and nothing changes; null unbinds that slot only. + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables.getByName('show');"); + assert!(e.contains("visibility variable"), "{e}"); + let e = failure(&mut s, "var d = app.activeDocument; d.pageItems[1].visibilityVariable = d.variables.getByName('title');"); + assert!(e.contains("text variable"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.pageItems[0].contentVariable = 'title';").contains("Variable or null")); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.bindings.get(&t).map(|b| b.iter().cloned().collect::>()), Some(vec!["show".to_string()])); + // Assigning the binding the object already has runs no command. + let steps = undo_steps(&s); + log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('show'); d.pageItems[0].contentVariable = null;", + ); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn an_embedded_image_cannot_take_an_image_variable() { + let dir = Folder::new("script-vars-embedded"); + let path = dir.file("red.png"); + write(&path, &png(10, 10, RED)); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = place(&mut s, &path); + s.execute("variable.define", &json!({"name": "photo", "kind": "image"})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument; d.pageItems[0].contentVariable = d.variables[0]; vc.log(d.pageItems[0].contentVariable.name);"); + assert_eq!(out, vec![json!("photo")]); + s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + s.execute("variable.unbind", &json!({"ids": [id.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); + assert!(e.contains("embedded image"), "{e}"); + assert!(s.active().unwrap().doc.variables.bindings.is_empty()); +} + +#[test] +fn data_sets_capture_display_update_and_remove() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + r#"var d = app.activeDocument, sets = d.dataSets; + vc.log(sets.length + ',' + (d.activeDataset === null)); + var one = sets.add(); + vc.run('text.setText', {id: TEXT_ID, text: 'World'}); + var two = sets.add(); + vc.log([one.name, two.name, sets.length, d.activeDataset.name].join()); + one.display(); vc.log(d.activeDataset.name); + vc.run('text.setText', {id: TEXT_ID, text: 'Again'}); + two.update(); vc.log(d.activeDataset.name); + two.name = 'Second'; vc.log(sets.getByName('Second').name + ',' + sets.index(1).name); + d.activeDataset = two; vc.log(d.activeDataset.name); + one.remove(); vc.log(sets.length);"# + .replace("TEXT_ID", &t.0.to_string()) + .as_str(), + ); + assert_eq!( + out, + vec![ + json!("0,true"), + json!("Data Set 1,Data Set 2,2,Data Set 2"), + json!("Data Set 1"), + json!("Data Set 1"), + json!("Second,Second"), + json!("Second"), + json!(1) + ] + ); + let vars = &s.active().unwrap().doc.variables; + assert_eq!(vars.datasets.len(), 1); + assert_eq!(vars.datasets[0].values.get("title"), Some(&vectorcraft_doc::DataValue::Text("Again".into()))); + assert_eq!(vars.active_dataset.as_deref(), Some("Second")); + assert_eq!(undo_steps(&s), before + 1, "one undo step for the run"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; x.remove(); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); + log(&mut s, "app.activeDocument.dataSets.removeAll(); app.activeDocument.dataSets.removeAll();"); + assert!(s.active().unwrap().doc.variables.datasets.is_empty()); + assert!(failure(&mut s, "app.activeDocument.activeDataset = 'Data Set 1';").contains("must be a Dataset")); +} + +#[test] +fn update_of_a_data_set_that_holds_the_art_runs_no_command() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let before = undo_steps(&s); + let r = run(&mut s, "var x = app.activeDocument.dataSets[0]; x.update(); x.display(); app.activeDocument.activeDataset = x;").unwrap(); + assert_eq!(undo_steps(&s), before); + assert_eq!(r["slowestCommands"], json!([]), "{r}"); +} + +#[test] +fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({})).unwrap(); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + +#[test] +fn variables_locked_refuses_new_variables_but_not_bindings() { + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "show", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log(d.variablesLocked); d.variablesLocked = true; d.variablesLocked = true;\ + d.pageItems[1].visibilityVariable = d.variables[0]; vc.log(d.variablesLocked);", + ); + assert_eq!(out, vec![json!(false), json!(true)]); + assert!(s.active().unwrap().doc.variables.locked); + let e = failure(&mut s, "app.activeDocument.variables.add();"); + assert!(e.contains("locked"), "{e}"); + assert!(failure(&mut s, "app.activeDocument.variablesLocked = 1;").contains("true or false")); + assert_eq!(variables(&s).len(), 1); +} + +/// A variable library of two variables and two data sets, written for these tests from the elements +/// and attributes `variable.loadLibrary` reads: `variableSets`, `variableSet`, `variables` of +/// `variable` elements with `varName` and `trait`, and `sampleDataSets` of `sampleDataSet` elements +/// with `dataSetName`. +const LIBRARY: &str = r#" + + + + + + + + <p>Hello</p>true + <p>World</p>false + + + +"#; + +/// A fresh folder with a `main` folder for the script, by its real path. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-vars-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// Runs `main/main.jsx` in `base` with `text`, on `s`. +fn run_file(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +#[test] +fn import_variables_replaces_the_variables_and_keeps_compatible_bindings() { + let base = folder("import"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.define", &json!({"name": "gone", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + let before = undo_steps(&s); + let r = run_file( + &mut s, + &base, + "var d = app.activeDocument; d.importVariables(new File('lib.xml'));\ + vc.log(d.variables.length + ',' + d.dataSets.length + ',' + d.dataSets[1].name);\ + d.dataSets.getByName('Two').display(); vc.log(d.pageItems[0].contentVariable.name);", + ) + .unwrap(); + assert_eq!(r["log"], json!(["2,2,Two", "title"])); + assert_eq!(variables(&s), vec![("title".to_string(), "text"), ("badge".to_string(), "visibility")]); + assert_eq!(s.active().unwrap().doc.story_text(t), "World"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn import_variables_takes_only_a_file_the_script_may_read() { + let base = folder("import-refused"); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + std::fs::write(base.join("outside.xml"), LIBRARY).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let fail = |s: &mut Session, text: &str| run_file(s, &base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string(); + assert!(fail(&mut s, "app.activeDocument.importVariables('lib.xml');").contains("needs a File")); + assert!(fail(&mut s, "app.activeDocument.importVariables(new Folder('.'));").contains("needs a File")); + let outside = base.join("outside.xml").to_string_lossy().replace('\\', "/"); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{outside}'));")); + assert!(e.contains("access denied"), "{e}"); + // The open document's own file is refused, though the script's commands may open it. + let saved = base.join("doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let e = fail(&mut s, &format!("app.activeDocument.importVariables(new File('{}'));", saved.replace('\\', "/"))); + assert!(e.contains("access denied"), "{e}"); + // A plain object cannot pass for a File. + let e = fail(&mut s, "var o = {}; o['\\u0000fileRef'] = new File('lib.xml').fsName; app.activeDocument.importVariables(o);"); + assert!(e.contains("not plain data"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn import_variables_refuses_hostile_libraries_before_any_edit() { + let base = folder("import-hostile"); + let external = r#"]>"#; + std::fs::write(base.join("main/external.xml"), external).unwrap(); + let deep = format!("{}{}", "".repeat(300), "".repeat(300)); + std::fs::write(base.join("main/deep.xml"), deep).unwrap(); + let mut big = LIBRARY.as_bytes().to_vec(); + big.resize((8 << 20) + 1, b' '); + std::fs::write(base.join("main/big.xml"), big).unwrap(); + let twice = LIBRARY.replace("varName=\"badge\"", "varName=\"title\""); + std::fs::write(base.join("main/twice.xml"), twice).unwrap(); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "keep", "kind": "text"})).unwrap(); + let before = undo_steps(&s); + for (file, says) in [("external.xml", "document type declaration"), ("deep.xml", "deep"), ("big.xml", "larger than"), ("twice.xml", "twice")] { + let e = run_file(&mut s, &base, &format!("app.activeDocument.importVariables(new File('{file}'));")).unwrap_err().to_string(); + assert!(e.contains(says), "{file}: {e}"); + } + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); + assert_eq!(undo_steps(&s), before); + // Locked variables refuse a library that would delete or define one. + s.execute("variable.lock", &json!({"locked": true})).unwrap(); + std::fs::write(base.join("main/lib.xml"), LIBRARY).unwrap(); + let e = run_file(&mut s, &base, "app.activeDocument.importVariables(new File('lib.xml'));").unwrap_err().to_string(); + assert!(e.contains("locked"), "{e}"); + assert_eq!(variables(&s), vec![("keep".to_string(), "text")]); +} + +#[test] +fn export_variables_writes_a_library_that_import_reads_back() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.capture", &json!({"name": "Row"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, f = new File(Folder.temp + '/out.xml');\ + d.exportVariables(f); f.open('r'); var x = f.read(); f.close(); vc.log(x);\ + d.variables.removeAll(); d.importVariables(f); vc.log(d.variables[0].name + ',' + d.dataSets[0].name);", + ); + let xml = out[0].as_str().unwrap(); + for part in ["varName=\"title\"", "trait=\"textcontent\"", "dataSetName=\"Row\"", "

Hello

"] { + assert!(xml.contains(part), "{part} in {xml}"); + } + assert_eq!(out[1], json!("title,Row")); +} + +#[test] +fn export_variables_writes_only_where_the_script_may_write() { + let base = folder("export-refused"); + let (mut s, _, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + // The open document's own file is refused, though the script's commands may save it. + let saved = base.join("main/doc.vectorcraft").to_string_lossy().into_owned(); + s.execute("file.saveAs", &json!({"path": saved})).unwrap(); + let before = std::fs::read(&saved).unwrap(); + let path = saved.replace('\\', "/"); + let e = run_file(&mut s, &base, &format!("app.activeDocument.exportVariables(new File('{path}'));")).unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert_eq!(std::fs::read(&saved).unwrap(), before); + // The script's own folder is only read. + let e = run_file(&mut s, &base, "app.activeDocument.exportVariables(new File('out.xml'));").unwrap_err().to_string(); + assert!(e.contains("access denied"), "{e}"); + assert!(!base.join("main/out.xml").exists()); + assert!(run_file(&mut s, &base, "app.activeDocument.exportVariables('out.xml');").unwrap_err().to_string().contains("needs a File")); + // A library that cannot be written leaves no file. + s.execute("variable.rename", &json!({"name": "title", "newName": "has space"})).unwrap(); + let e = failure(&mut s, "app.activeDocument.exportVariables(new File(Folder.temp + '/bad.xml'));"); + assert!(e.contains("can't be saved"), "{e}"); + let out = + log(&mut s, "var f = new File(Folder.temp + '/bad.xml'); try { app.activeDocument.exportVariables(f); } catch (e) {} vc.log(f.exists);"); + assert_eq!(out, vec![json!(false)]); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index c962bf9679..59f385cabb 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -92,6 +92,19 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { }) } +/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose +/// path is in its own slot. `None` for anything else, a `Folder` included. +pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult> { + let Some(c) = &i.files else { return Ok(None) }; + if i.object(id)?.proto != Some(c.file_proto) { + return Ok(None); + } + Ok(match slot(i, id, PATH)? { + Value::String(s) => Some(s.to_rust_string()), + _ => None, + }) +} + fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { if let Value::String(s) = &value { i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?; diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index f34c9cff8e..26ab1e14ed 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -190,8 +190,8 @@ struct Reading { ancestors: Vec, path: Vec, function: Rc, - /// Objects of host classes are read as [`crate::host_ref`] gives them, and a plain object - /// that has [`crate::HOST_REF_KEY`] is refused. + /// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under + /// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused. hosted: bool, } @@ -261,6 +261,12 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } + if r.hosted + && let Some(path) = crate::file_classes::file_path(self, id)? + { + self.charge_reading(r, path.len().saturating_add(16))?; + return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))])); + } let shape = match &self.object(id)?.class { Class::Host(_) if r.hosted => { return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); @@ -313,7 +319,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && name == crate::HOST_REF_KEY { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..4a790957c6 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -110,6 +110,19 @@ pub fn host_ref(class: &str, handle: &[f64]) -> Data { Data::Object(vec![(HOST_REF_KEY.to_string(), Data::Array(list))]) } +/// The one key of the [`Data`] object that stands for a script's `File` in the arguments of a host +/// class's member ([`file_ref_path`]). A plain object a script made that carries it is refused. +pub const FILE_REF_KEY: &str = "\u{0}fileRef"; + +/// The path of the `File` that `d`, an argument of a host class's member, stands for. +pub fn file_ref_path(d: &Data) -> Option<&str> { + let Data::Object(items) = d else { return None }; + match items.as_slice() { + [(k, Data::String(path))] if k == FILE_REF_KEY => Some(path), + _ => None, + } +} + /// The class and handle of the object `d` stands for, when it is one [`host_ref`] made. pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { let Data::Object(items) = d else { return None }; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..e3141d9e0f 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -82,7 +82,7 @@ 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::{FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, file_ref_path, 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}; diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..4c92dafa13 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + documents, each document's selection and its page items, and each document's variables, data sets and variable + libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 5f873fe10a..2d35d2d0b9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2675,6 +2675,29 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and + `exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables` + (https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets` + (https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/) have `length`, `parent`, `[i]`, `index(key)`, + `getByName(name)`, `add()` and `removeAll()`. A `Variable` (https://ai-scripting.docsforadobe.dev/jsobjref/Variable/) + has `name`, `kind`, `pageItems` and `remove()`, and a `Dataset` (https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/) + has `name`, `display()`, `update()` and `remove()`. Every page item has `visibilityVariable`, and a `TextFrame`, + `PlacedItem`, `RasterItem` or `GraphItem` has `contentVariable` as well + (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each change runs a `variable.*` or `dataset.*` command: + `variables.add()` runs `variable.define` of a text variable named `Variable1`, `Variable2` and so on (the first free + name), `dataSets.add()` runs `dataset.capture`, `display()` and assigning `activeDataset` run `dataset.select`, + `update()` runs `dataset.update {name}`, assigning `visibilityVariable` or `contentVariable` runs + `variable.setBinding`, `importVariables` runs `variable.loadLibrary` and `exportVariables` runs + `variable.saveLibrary`. `kind` is one of the strings of the enumeration `VariableKind` + (`"VariableKind.TEXTUAL"`, `VISIBILITY`, `IMAGE`, `GRAPH` and `Unknown`); `Unknown` cannot be assigned. + VectorCraft's own rules: a `Variable` or `Dataset` names its variable or data set by name. A rename made through + it keeps it working; once the name leaves the document any other way (a delete, an undo, a rename or kind change by + another command, or an import that replaces the data sets), it throws `Stale variable` or `Stale data set`, also + after the name comes back. A run gives out at most 10,000 of each. `visibilityVariable` and `contentVariable` give + the first bound variable of their kind in the order the variables were defined, or `null`, and `null` unbinds. + `importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or + write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs + no command. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -4267,7 +4290,13 @@ already walks Image Trace. Short agent entry points: defined in. Names compare without regard to case; by object, unbound variables come first and variables bound to several objects last, and ties go by name. Another `by` value, or a `descending` that is not true or false, is an error. The sort is panel state, not saved and not an undo step; `variable.list` lists the variables in - that order and reports it as `sort: {by, descending}`. + that order and reports it as `sort: {by, descending}`. `variable.setBinding {id, slot: visibility|content, + variable?}` binds one object to `variable` for one slot and unbinds the object's other variables of that slot's + kind: `visibility` takes a visibility variable, and `content` the kind that drives the object (text for type, image + for a linked image, graph for a graph). Without `variable`, or with null, it unbinds them all. A variable of + another kind, an object of no content kind, and an embedded image for an image variable are errors, and nothing + changes. One undo step, and none when the object already has just that binding → `{id, slot, variable, + unbound}`. - Data sets: `dataset.list`, `dataset.new {name, values?}`, `dataset.set {name, newName?, values?}` (`newName` also renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / @@ -5038,8 +5067,9 @@ locked; `skipped` counts those objects. A `dataset.import` error about a value says why it was refused: a visibility value other than true, false, 1, 0, yes or no, or a graph value longer than 262,144 bytes. -`dataset.update {all?}` writes what the bound objects hold now into the active data set, for each variable that the -data set holds. A variable whose objects report no value, because they are deleted or, for a text, image or graph +`dataset.update {all?, name?}` writes what the bound objects hold now into the active data set, for each variable that +the data set holds. With `name`, it writes into that data set instead and the active data set stays as it is; a +`name` that is not a string, or names no data set, is an error. A variable whose objects report no value, because they are deleted or, for a text, image or graph variable, locked or inside a locked layer or group, or for any variable on a locked artboard, keeps the data set's value. With `all: true` it also adds every other variable that the objects report a value for. The reply gives `values`, the number of values it wrote, and `left`, the variables it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..a760266f23 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - 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`. From 6db0f6c1adef609bba16c8eec4ce0a37e178d2ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:15:47 -0800 Subject: [PATCH 012/160] Scripts: visibility variables on embedded images, data sets kept after a no-op import - variable.setBinding refuses an embedded image only for an image variable, so a script can bind an embedded image's visibility. - A Dataset object stays usable after dataset.import, variable.loadLibrary or variable.import leaves the document's data sets as they were, or the import is put back; it goes stale only when the data sets change. - script.check reports a document's exportVariables as filesWritten and file.write, and the script host test lists the variable and data set names the host adds. Docs: docs/mcp.md. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/script/dom.rs | 10 +++++++-- crates/engine/src/script/dom/variables.rs | 22 ++++++++++++++----- crates/engine/src/script/mod.rs | 3 ++- crates/engine/src/tests/script_variables.rs | 19 ++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 18 +++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 2 +- crates/scriptcheck/src/catalog.rs | 3 +++ crates/scriptcheck/src/tests.rs | 8 +++++++ docs/mcp.md | 7 +++--- 10 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index fdd4231dc3..28022865e6 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -500,7 +500,7 @@ fn set_binding(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); } check_bindable(doc, &[id], kind, C)?; - if matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + if kind == VariableKind::Image && matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); } } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a7303cf4e6..7e46779791 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -42,9 +42,15 @@ mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; +/// What [`after_command`] compares with, taken before each command a script runs +/// ([`variables::before_command`]). +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + variables::before_command(h, id) +} + /// After each command a script runs ([`variables::after_command`]). -pub(super) fn after_command(h: &Host, id: &str) { - variables::after_command(h, id); +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { + variables::after_command(h, before); } /// The error for a member read or called with no document open. diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs index 270a7cfc08..d36c9f1f45 100644 --- a/crates/engine/src/script/dom/variables.rs +++ b/crates/engine/src/script/dom/variables.rs @@ -46,7 +46,7 @@ use super::{ Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, }; -use crate::doc::{Node, Variable, VariableKind}; +use crate::doc::{DataSet, Node, Variable, VariableKind}; use crate::file_access::Access; /// The error for a `Variable` whose variable left the document, or that came from an earlier run. @@ -138,16 +138,28 @@ pub(super) struct Handles { seen: RefCell>, } +/// The data sets of the active document before a command that may replace them (an import), while +/// the run holds a `Dataset`; `None` for any other command. +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() { + return None; + } + let s = h.session.try_borrow().ok()?; + s.active().map(|st| (st.uid, st.doc.variables.datasets.clone())) +} + /// After each command a script runs: the objects whose variable or data set it removed stop -/// working, so one made again under the same name does not bring them back. A command that replaces -/// the data sets (an import) stops every `Dataset` of its document. -pub(super) fn after_command(h: &Host, id: &str) { +/// working, so one made again under the same name does not bring them back. An import that leaves +/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset` +/// of that document, also when the new data sets reuse the names; an import that failed, was put +/// back or left the data sets as they were stops none. +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { let hs = &h.dom.vars; if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { return; } let Ok(s) = h.session.try_borrow() else { return }; - let replaced = matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import").then(|| s.active().map(|st| st.uid)).flatten(); + let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid)); let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); let changed: HashSet = { let seen = hs.seen.borrow(); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0780a34e98..39acd9897b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1313,6 +1313,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let params = params.clone(); let session = host.session.clone(); let started = clock(); + let before = dom::before_command(host, &id); let r = { let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) @@ -1346,7 +1347,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } - dom::after_command(host, &id); + dom::after_command(host, before); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs index e60afb03d2..5ff2301bbf 100644 --- a/crates/engine/src/tests/script_variables.rs +++ b/crates/engine/src/tests/script_variables.rs @@ -188,6 +188,13 @@ fn an_embedded_image_cannot_take_an_image_variable() { let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); assert!(e.contains("embedded image"), "{e}"); assert!(s.active().unwrap().doc.variables.bindings.is_empty()); + // Its visibility still takes a visibility variable. + s.execute("variable.define", &json!({"name": "shown", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('shown'); vc.log(d.pageItems[0].visibilityVariable.name);", + ); + assert_eq!(out, vec![json!("shown")]); } #[test] @@ -259,6 +266,18 @@ fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { assert!(e.contains("Stale data set"), "{e}"); } +#[test] +fn an_import_that_leaves_the_data_sets_as_they_were_keeps_the_data_set_objects() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.import", &json!({"csv": "title\nNew"})).unwrap(); + let out = log(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); vc.log(x.name);"); + assert_eq!(out.len(), 1, "{out:?}"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nOther'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + #[test] fn variables_locked_refuses_new_variables_but_not_bindings() { let (mut s, _, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..4519f35c5e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -70,6 +71,23 @@ const INSIDE: &[(&str, &str)] = &[ "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ getRelativeURI modified name parent path relativeURI resolve selectDlg toString", ), + // Variables and data sets. `importVariables` reads the library file it is given. + ("", "Dataset Datasets Variable VariableKind Variables"), + ("VariableKind.", "GRAPH IMAGE TEXTUAL Unknown VISIBILITY"), + ("Variables.", "prototype"), + ("Variables.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Variable.", "prototype"), + ("Variable.prototype.", "constructor kind kind= name name= pageItems parent remove typename"), + ("Datasets.", "prototype"), + ("Datasets.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Dataset.", "prototype"), + ("Dataset.prototype.", "constructor display name name= parent remove typename update"), + ("Document.prototype.", "activeDataset activeDataset= dataSets importVariables variables variablesLocked variablesLocked="), + ("PageItem.prototype.", "visibilityVariable visibilityVariable="), + ("GraphItem.prototype.", "contentVariable contentVariable="), + ("PlacedItem.prototype.", "contentVariable contentVariable="), + ("RasterItem.prototype.", "contentVariable contentVariable="), + ("TextFrame.prototype.", "contentVariable contentVariable="), ]; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..eef0fb77c1 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -301,7 +301,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if file && catalog::FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..940b1db4e0 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -72,6 +72,9 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; +// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportVariables"]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..1f4c9f3e70 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,14 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. +#[test] +fn export_variables_writes_a_file() { + let r = report("var f = new File(p);\napp.activeDocument.importVariables(f);\napp.activeDocument.exportVariables(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 2d35d2d0b9..7d454966ce 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,9 +2558,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, - `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, - `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). + File object's `length`, `hidden` or `readonly` counts too, and so does a document's `exportVariables`), + `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), + `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` + (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, template literals and XML literals that aren't closed, brackets that don't match, syntax newer than ES3 and unknown directives) and notes on its text (bytes that aren't valid UTF-8, mixed line endings, and nesting deeper From ee7576975ed005cac23c428c3de33ec47cb55050 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:10:19 -0800 Subject: [PATCH 013/160] Scripts: the script check counts exportVariables named in brackets as a file write doc['exportVariables'](f) now reports file.write and filesWritten on its line, as the dot form does. Reading the method without calling it reports nothing. --- crates/scriptcheck/src/analyze/features.rs | 10 ++++++++++ crates/scriptcheck/src/tests.rs | 15 +++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index eef0fb77c1..b7630e064b 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -287,6 +287,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; + // `doc['exportVariables'](f)`: a document method named by a string literal in brackets. + if is(h0, "]") + && is(h2, "[") + && let Some(name) = h1.filter(|s| s.kind == T::Str) + && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + return; + } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1f4c9f3e70..785ebf6c62 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -538,6 +538,21 @@ fn export_variables_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); } +/// `exportVariables` called with its name as a string literal in brackets writes the file too; +/// reading the method without calling it does not. +#[test] +fn export_variables_in_brackets_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument['importVariables'](f);\n", + "app.activeDocument[\"exportVariables\"](f);\n", + "var d = app.activeDocument; d['exportVariables'] (f);\n", + "var n = d['exportVariables'];\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] From e67211f07036a29014aeec2e27179b7488d416ab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:17:06 -0800 Subject: [PATCH 014/160] Fix #8583: document tab titles draw in a condensed face, so more tabs fit Desktop builds with a craft-fonts checkout that has Noto Sans Condensed SemiBold in its opt-in Latin catalog (fonts/latin-manifest.txt) embed that one face as vectorcraft_text::CONDENSED_UI_FONT. Tab titles draw in a new theme::FONT_TAB family headed by it, scaled to the x-height of the interface's semibold face, with the semibold faces after it on its baseline. In a 1280 pt window, 9 tabs named "Poster draft N" fit whole instead of 8. Without CRAFT_FONTS_DIR, on the web, or with a checkout that lacks the row (a build warning), FONT_TAB is the semibold family and tabs look as before. The tab tests that count tabs measure in the semibold face. --- crates/text/build.rs | 71 +++++++++++++++++++----- crates/text/src/craft_fonts.rs | 3 + crates/text/src/lib.rs | 11 +++- crates/ui-egui/src/chrome/tabs.rs | 9 +-- crates/ui-egui/src/i18n/tests.rs | 1 + crates/ui-egui/src/tests/tab_overflow.rs | 41 +++++++++++++- crates/ui-egui/src/theme.rs | 53 +++++++++++++++++- crates/ui-egui/src/ui_fonts.rs | 2 +- docs/development.md | 6 ++ docs/ui-parity.md | 1 + 10 files changed, 171 insertions(+), 27 deletions(-) diff --git a/crates/text/build.rs b/crates/text/build.rs index 5402ddbe07..5979c6557c 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -12,6 +12,10 @@ //! `fonts//` beside the wasm instead of embedding (`cargo xtask web-fonts` copies them //! there; `apps/vectorcraft-web/src/fonts.rs` fetches them). A list line the manifest lacks is left //! out with a warning, never an error, and never costs the desktop its fonts. +//! +//! On native targets it writes `CONDENSED_UI_FONT`: the condensed face document tab titles draw in +//! (`CONDENSED_UI_FACE`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. A +//! checkout without that row leaves it `None` with a warning, never an error. use std::fmt::Write as _; use std::path::{Path, PathBuf}; @@ -25,7 +29,7 @@ fn main() { println!("cargo::rerun-if-changed=web-fonts.txt"); println!("cargo::rerun-if-changed=build/web_fonts.rs"); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); - let (mut fonts, mut web) = (String::new(), String::new()); + let (mut fonts, mut web, mut condensed) = (String::new(), String::new(), String::from("None")); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|d| !d.is_empty()).map(PathBuf::from) { let dir = from_workspace(dir); match craft_fonts(&dir) { @@ -48,8 +52,16 @@ fn main() { Err(e) if required => println!("cargo::error=web-fonts.txt: {e}"), Err(e) => println!("cargo::warning=web build fetches no craft fonts: web-fonts.txt: {e}"), } + if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a != "wasm32") { + match condensed_ui_font(&dir) { + Ok(entry) => condensed = format!("Some({entry})"), + Err(e) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), + } + } } - let src = format!("pub static CRAFT_FONTS: &[CraftFont] = &[\n{fonts}];\npub static WEB_FONTS: &[WebFont] = &[\n{web}];\n"); + let src = format!( + "pub static CRAFT_FONTS: &[CraftFont] = &[\n{fonts}];\npub static WEB_FONTS: &[WebFont] = &[\n{web}];\npub static CONDENSED_UI_FONT: Option = {condensed};\n" + ); let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_fonts.rs"); // Unchanged output keeps its mtime. Rewritten just before this crate compiles, it can read as // newer than that compile where cargo's recorded times lose their sub-second part (ecryptfs @@ -91,23 +103,52 @@ fn craft_fonts(dir: &Path) -> Result { if wasm && !(*family == WEB_FONT.0 && *style == WEB_FONT.1) { continue; } - let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; - // The manifest is supplier data: embed only regular files inside the checkout. - if !path.starts_with(&root) || !path.is_file() { - return Err(format!("{file}: not a file inside the font checkout")); - } - println!("cargo::rerun-if-changed={}", path.display()); - let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); - let _ = writeln!( - out, - " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},", - scripts.join(", "), - path.display().to_string(), - ); + let _ = writeln!(out, " {},", craft_font(dir, &root, family, style, file, scripts)?); } Ok(out) } +/// The `CraftFont { .. }` initialiser of one manifest row of the checkout `dir` (canonical `root`). +fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, scripts: &str) -> Result { + let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; + // The manifest is supplier data: embed only regular files inside the checkout. + if !path.starts_with(root) || !path.is_file() { + return Err(format!("{file}: not a file inside the font checkout")); + } + println!("cargo::rerun-if-changed={}", path.display()); + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); + Ok(format!( + "CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }}", + scripts.join(", "), + path.display().to_string(), + )) +} + +/// The condensed craft-fonts face (family, style) document tab titles draw in, from the opt-in +/// Latin catalog. +const CONDENSED_UI_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + +/// The `CraftFont { .. }` initialiser of [`CONDENSED_UI_FACE`]'s row in `fonts/latin-manifest.txt`. +fn condensed_ui_font(dir: &Path) -> Result { + let manifest = dir.join("fonts/latin-manifest.txt"); + // A checkout without the catalog is watched through its folder, so the build runs again once + // the catalog appears. + let watched = if manifest.is_file() { manifest.clone() } else { dir.join("fonts") }; + println!("cargo::rerun-if-changed={}", watched.display()); + let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e} (an older craft-fonts?)", manifest.display()))?; + let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; + let row = text + .lines() + .map(str::trim) + .filter(|l| !l.is_empty() && !l.starts_with('#')) + .map(|l| l.split(" | ").map(str::trim).collect::>()) + .find(|f| f.first() == Some(&CONDENSED_UI_FACE.0) && f.get(1) == Some(&CONDENSED_UI_FACE.1)); + let Some([family, style, file, scripts, ..]) = row.as_deref() else { + return Err(format!("{} {} not in {} (an older craft-fonts?)", CONDENSED_UI_FACE.0, CONDENSED_UI_FACE.1, manifest.display())); + }; + craft_font(dir, &root, family, style, file, scripts) +} + /// One `WebFont { .. }` initialiser per `web-fonts.txt` line, from its craft-fonts manifest row, and /// the listed faces the manifest lacks (an older craft-fonts checkout), which are left out. fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index 24eef3de40..68ddc548b9 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -3,6 +3,9 @@ //! Built with `CRAFT_FONTS_DIR=`, [`CRAFT_FONTS`] holds every font in its //! manifest (Japanese UI and document fonts, Arabic fonts and Noto Sans Thai); built without it, //! it is empty and that text falls back to the installed system fonts. Release builds always set it. See `build.rs`. +//! [`CONDENSED_UI_FONT`] is the condensed face document tab titles draw in, from the checkout's +//! opt-in Latin catalog: `None` on wasm32, without `CRAFT_FONTS_DIR`, or with a checkout that +//! lacks it. /// A font from the optional craft-fonts build input (empty unless built with `CRAFT_FONTS_DIR`). pub struct CraftFont { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7b70b9c5a2..2028639af4 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -37,7 +37,7 @@ pub mod thread; pub use bitmap::GlyphImage; pub use context_alternates::{ContextAlternate, ContextAlternates, alternate_changes, alternates_in_context, is_alternate_feature}; -pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; +pub use craft_fonts::{CONDENSED_UI_FONT, CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont}; pub use features::{ EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by, }; @@ -1059,6 +1059,15 @@ pub fn line_metrics(data: &[u8], index: u32) -> Option<(f32, f32, f32, f32)> { Some((f32::from(m.units_per_em.max(1)), m.ascent, m.descent, m.leading)) } +/// The x-height of the font at `index` of `data`, at its default axis settings, in ems. `None` if +/// the font can't be read or gives no x-height. +pub fn x_height(data: &[u8], index: u32) -> Option { + use skrifa::MetadataProvider; + let f = skrifa::FontRef::from_index(data, index).ok()?; + let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()); + m.x_height.filter(|h| *h > 0.0).map(|h| h / f32::from(m.units_per_em.max(1))) +} + #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index b92d1e5d04..1aff4fe1a9 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -56,7 +56,7 @@ pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_window ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); let title = document_window_title(app, w).unwrap_or_default(); - let galley = ui.painter().layout_no_wrap(title, theme::semibold(title_size), t.text_strong); + let galley = ui.painter().layout_no_wrap(title, theme::tab_font(title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); @@ -190,7 +190,8 @@ fn tab_close_box(ui: &Ui, t: &Tokens, xr: egui::Rect, w: f32, id: egui::Id) -> O /// (#746). The first tab that doesn't fit whole fills the room left before the » button with its /// title shortened, when that room holds some of the title (#8584). When the active tab is among /// the last ones and the tabs from it to the end leave room, the tab before them fills that room -/// instead. An active tab wider than the whole strip is shortened to it. +/// instead. An active tab wider than the whole strip is shortened to it. Titles draw in +/// [`theme::FONT_TAB`], a condensed face in builds with craft-fonts (#8583). /// Each view Window › New Window opened has a tab of its own. Windows floating have no tab /// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] @@ -224,7 +225,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let title = window_tab_title(app, w, d); let (text, color) = if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; - let galley = ui.painter().layout_no_wrap(text.clone(), theme::semibold(title_size), color); + let galley = ui.painter().layout_no_wrap(text.clone(), theme::tab_font(title_size), color); (w, text, title, galley) }) .collect(); @@ -258,7 +259,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { break; } let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; - let (galley, fits) = shortened_title(ui.ctx(), text, theme::semibold(title_size), color, left - TAB_PADDING); + let (galley, fits) = shortened_title(ui.ctx(), text, theme::tab_font(title_size), color, left - TAB_PADDING); (galley, left.max(0.0), true, fits) } else { (galley.clone(), *w, false, true) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..7954785e30 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1498,6 +1498,7 @@ fn bundled_fonts_cover_the_catalogs() { egui::FontFamily::Proportional, egui::FontFamily::Name(crate::theme::FONT_UI.into()), egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()), + egui::FontFamily::Name(crate::theme::FONT_TAB.into()), egui::FontFamily::Name(crate::theme::FONT_MONO.into()), ]; for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index 59af211e17..c9f9edec0a 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -44,6 +44,12 @@ fn frame_sized(app: &mut VectorcraftApp, ctx: &egui::Context, size: egui::Vec2, texts } +/// The interface fonts with tab titles in the semibold face, as in a build without craft-fonts' +/// condensed face: the tab counts below are measured in it. +fn install_semibold_tab_fonts(ctx: &egui::Context) { + ctx.set_fonts(crate::theme::interface_fonts_with(None)); +} + fn click(at: Pos2, pressed: bool) -> Event { Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() } } @@ -61,7 +67,7 @@ fn the_tab_that_does_not_fit_whole_fills_the_rest_of_the_strip() { app.session.set_active(0); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); @@ -100,7 +106,7 @@ fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { app.session.set_active(0); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); @@ -118,6 +124,35 @@ fn inactive_tabs_show_the_name_alone_so_more_tabs_fit() { assert!(texts.iter().any(|(t, _)| t == "Tab test 2 @ 100 % (RGB/Preview)"), "the tooltip shows the whole title: {texts:?}"); } +/// With craft-fonts' condensed face, tab titles draw in it at the semibold face's x-height, and +/// more tabs fit whole in the strip of a 1280 pt window than with the semibold face (#8583). +#[test] +fn tab_titles_in_the_condensed_face_fit_more_tabs() { + let Some(condensed) = vectorcraft_text::CONDENSED_UI_FONT.as_ref() else { + eprintln!("skipped: built without craft-fonts' condensed face (set CRAFT_FONTS_DIR to a craft-fonts checkout that has it)"); + return; + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for i in 0..24 { + app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Poster draft {i}")})).unwrap(); + } + app.session.set_active(0); + app.sync_views(); + let mut whole_tabs = |face: Option<&vectorcraft_text::CraftFont>| { + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::interface_fonts_with(face)); + let texts = frame_sized(&mut app, &ctx, egui::vec2(1280.0, 700.0), 0.0, vec![]); + let whole = texts.iter().filter(|(t, _)| t.starts_with("Poster draft") && !t.ends_with('…')).count(); + // The height of an x, in the tab font and in semibold text. + let x = |font: egui::FontId| ctx.fonts_mut(|f| f.layout_no_wrap("x".into(), font, egui::Color32::WHITE)).rows[0].glyphs[0].uv_rect.size.y; + (whole, x(crate::theme::tab_font(40.0)), x(crate::theme::semibold(40.0))) + }; + let (semibold, _, _) = whole_tabs(None); + let (narrow, x_tab, x_semibold) = whole_tabs(Some(condensed)); + assert!(narrow > semibold, "more tabs fit whole in the condensed face: {narrow} against {semibold}"); + assert!((x_tab - x_semibold).abs() <= 1.0, "an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); +} + /// With the last document active, the tabs from it to the end leave room before the » button, and /// the tab before them fills that room with its title shortened instead of the strip ending short /// of the » button (#8584). @@ -132,7 +167,7 @@ fn with_the_last_document_active_the_tab_before_the_shown_ones_fills_the_room() app.session.set_active(7); app.sync_views(); let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); + install_semibold_tab_fonts(&ctx); let texts = frame(&mut app, &ctx, 0.0, vec![]); let mut tabs: Vec<(String, egui::Rect)> = texts.into_iter().filter(|(t, _)| t.starts_with("Tab test")).collect(); tabs.sort_by(|a, b| a.1.left().total_cmp(&b.1.left())); diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index f539ddbe71..11e8af8e22 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -494,16 +494,29 @@ pub fn strong_selected_text(ui: &mut egui::Ui) { pub const FONT_UI: &str = "ui"; pub const FONT_UI_SEMIBOLD: &str = "ui-semibold"; pub const FONT_MONO: &str = "mono"; +/// The family document tab titles draw in. In a build with craft-fonts' condensed face +/// ([`vectorcraft_text::CONDENSED_UI_FONT`]), that face heads it, at the x-height of the +/// [`FONT_UI_SEMIBOLD`] face, followed by the faces of [`FONT_UI_SEMIBOLD`] on its baseline, so +/// more tabs fit in the strip (#8583). Without it the family is [`FONT_UI_SEMIBOLD`]'s. +pub const FONT_TAB: &str = "tab"; pub fn semibold(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_UI_SEMIBOLD.into())) } +/// A document tab's title font ([`FONT_TAB`]). +pub fn tab_font(size: f32) -> FontId { + FontId::new(size, FontFamily::Name(FONT_TAB.into())) +} +/// Whether `family` draws semibold text and takes the bold fallback faces. +pub(crate) fn is_semibold(family: &FontFamily) -> bool { + matches!(family, FontFamily::Name(name) if [FONT_UI_SEMIBOLD, FONT_TAB].contains(&&**name)) +} pub fn mono(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_MONO.into())) } /// Installs the interface's fonts and binds the families the panels and dialogs draw in -/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when +/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_TAB`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when /// its `default_fonts` feature is on (this crate enables it); without any face a family lays out /// tofu, and the `egui_kittest` harness alone panics on a missing glyph. Every context that shows /// these families needs this once: [`crate::VectorcraftApp::ui`] calls it on its first pass, and @@ -520,6 +533,11 @@ pub fn install_fonts(ctx: &egui::Context) { /// whether egui applied them at once or deferred them to the next pass (it must not take input /// or draw with fallback metrics while they are pending). pub fn interface_fonts() -> FontDefinitions { + interface_fonts_with(vectorcraft_text::CONDENSED_UI_FONT.as_ref()) +} + +/// [`interface_fonts`] with `condensed` as the face that heads [`FONT_TAB`]. +pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFont>) -> FontDefinitions { let mut fonts = FontDefinitions::default(); let (ui, semi, mono) = interface_faces(&mut fonts); let stack = |fonts: &FontDefinitions, family: FontFamily| fonts.families.get(&family).cloned().unwrap_or_default(); @@ -529,13 +547,42 @@ pub fn interface_fonts() -> FontDefinitions { let family = |faces: Vec<&str>, fallback: &[String]| -> Vec { faces.into_iter().map(str::to_owned).chain(fallback.iter().cloned()).collect() }; fonts.families.insert(FontFamily::Proportional, family(ui.clone(), &fallback)); - fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), family(semi, &fallback)); + let semi = family(semi, &fallback); + let tab = tab_faces(&mut fonts, &semi, condensed); + fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), semi); + fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); fonts.families.insert(FontFamily::Name(FONT_UI.into()), family(ui, &fallback)); fonts.families.insert(FontFamily::Name(FONT_MONO.into()), family(mono, &mono_fallback)); add_craft_fonts(&mut fonts); fonts } +/// The faces of [`FONT_TAB`], added to `fonts`: `condensed`, scaled to the x-height of the first +/// face of `semi` (the [`FONT_UI_SEMIBOLD`] stack), then a copy of each face of `semi` on its +/// baseline. `semi` itself without `condensed`, or when either face's x-height can't be read. +fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Vec { + let x_height = |data: &FontData| vectorcraft_text::x_height((*data.font).as_ref(), data.index).map(|h| h * data.tweak.scale); + let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data)); + let Some((f, reference)) = condensed.zip(reference) else { return semi.to_vec() }; + let Some(own) = vectorcraft_text::x_height(f.bytes, 0) else { return semi.to_vec() }; + let name = craft_font_name(f); + let head = FontData::from_static(f.bytes).tweak(egui::epaint::text::FontTweak { scale: reference / own, ..Default::default() }); + // `baseline_copies` reads the head of each family it is given: here only this one. + let mut row = FontDefinitions::empty(); + row.font_data.insert(name.clone(), Arc::new(head.clone())); + row.families.insert(FontFamily::Name(FONT_TAB.into()), vec![name.clone()]); + let mut faces = vec![name.clone()]; + for face in semi { + let Some(data) = fonts.font_data.get(face).cloned() else { continue }; + for (copy, data, _) in crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data) { + fonts.font_data.insert(copy.clone(), Arc::new(data)); + faces.push(copy); + } + } + fonts.font_data.insert(name, Arc::new(head)); + faces +} + /// The interface's own faces, added to `fonts`: the names of the regular, semibold and monospace /// faces that head their families, in order. #[cfg(feature = "interface-fonts")] @@ -587,7 +634,7 @@ fn add_craft_fonts(fonts: &mut FontDefinitions) { } } for (family, stack) in fonts.families.iter_mut() { - let bold = *family == FontFamily::Name(FONT_UI_SEMIBOLD.into()); + let bold = is_semibold(family); let copy = |f: &vectorcraft_text::CraftFont| { let name = craft_font_name(f); copies.get(&(family.clone(), name.clone())).cloned().unwrap_or(name) diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 73c1a30891..cb419067e1 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -454,7 +454,7 @@ mod tests { let bottom = |g: &egui::epaint::text::Glyph| g.pos.y + g.uv_rect.offset.y + g.uv_rect.size.y; let glyphs = |text: &str, font: FontId| ctx.fonts_mut(|f| f.layout_no_wrap(text.into(), font, egui::Color32::WHITE)).rows[0].glyphs.clone(); for family in families { - let semibold = family == FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()); + let semibold = crate::theme::is_semibold(&family); for &(regular, bold, c) in &probes { let face = if semibold { bold } else { regular }; for size in [13.0_f32, 24.0, 40.0] { diff --git a/docs/development.md b/docs/development.md index fb30fad2bb..66f925324e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -174,6 +174,12 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- Noto Sans Georgian for the Georgian interface), after the UI fonts and before the installed fonts `ui_fonts.rs` discovers for other scripts. On the web, Noto Sans Georgian is fetched at startup and reaches the UI through `ui_fonts.rs`. +- Document tab titles: on desktop builds, `crates/text/build.rs` also reads one row of the + checkout's opt-in `fonts/latin-manifest.txt`, Noto Sans Condensed SemiBold, as + `vectorcraft_text::CONDENSED_UI_FONT`. `theme::FONT_TAB` draws the titles in it at the + x-height of the interface's semibold face, so more tabs fit in the strip. Without + `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), tab + titles draw in the semibold face. - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..8b5a9f315a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,6 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From 2400aa7712cd7be374ef957fdd4b6caa470293ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:51:26 -0800 Subject: [PATCH 015/160] 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 016/160] 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 017/160] 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 b19d017c317132873d2f69fd9961dec383f4e3f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 20:46:20 -0800 Subject: [PATCH 018/160] JavaScript: Map, Set, WeakMap, WeakSet and typed arrays in ES2015 realms A realm with Options::es2015 now has Map, Set, WeakMap and WeakSet, and ArrayBuffer, DataView and the nine typed arrays from Int8Array to Float64Array with %TypedArray%.from, of and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2). A realm without the option, the ExtendScript realm included, has none of these names. - Map and Set compare keys with SameValueZero and keep insertion order. forEach and iterators skip entries deleted before they reach them and visit entries added during the walk; the collector removes holes and moves live iterators. - WeakMap and WeakSet hold their keys weakly. The collector marks a WeakMap value only once its key is reachable another way and drops the entries of unreachable keys, also when a value refers to its key. - Typed arrays store elements little-endian; DataView is big-endian unless littleEndian is true. Numeric property names are elements or nothing, with the element descriptors of later editions. Copies to the same element type keep every bit. - An ArrayBuffer longer than 2^32 - 1 bytes or than the heap limit is a RangeError before anything is allocated, and every element a method visits takes fuel. - Until the language has iterators, the collection constructors and %TypedArray%.from read an array, a string by code point or an object with a length, by index. A typed array constructor reads an array or an object with a length the same way, and converts a first argument that is not an object to a length. - The %TypedArray%.prototype methods that share an Array method use the element count, and an Array method called on a typed array reads its length property. Array methods visit every element of a typed array longer than 4,096. - Check Script counts new of these constructors as the language's. test262 runs the Map, Set, WeakMap, WeakSet, ArrayBuffer, DataView, TypedArray and TypedArrayConstructors folders in ES2015 realms. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/js/src/builtins.rs | 19 +- crates/js/src/builtins/array.rs | 39 +- crates/js/src/builtins/binary.rs | 1143 +++++++++++++++++++++++++ crates/js/src/builtins/collections.rs | 696 +++++++++++++++ crates/js/src/collections_tests.rs | 412 +++++++++ crates/js/src/heap.rs | 328 ++++++- crates/js/src/interp.rs | 52 +- crates/js/src/lib.rs | 20 +- crates/js/tests/test262.rs | 114 ++- crates/scriptcheck/src/catalog.rs | 20 +- crates/scriptcheck/src/tests.rs | 11 + docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 13 files changed, 2832 insertions(+), 29 deletions(-) create mode 100644 crates/js/src/builtins/binary.rs create mode 100644 crates/js/src/builtins/collections.rs create mode 100644 crates/js/src/collections_tests.rs diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..6c2eff73ca 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -3,13 +3,16 @@ //! `Array`, the error constructors, `Math`, `JSON`, the global functions and constants, Annex //! B's `escape` and `unescape`, and the prototypes primitive values look properties up on, with //! `Boolean.prototype`'s `toString` and `valueOf`. `String`, `Number`, `RegExp` and `Date` are in -//! their own modules. +//! their own modules. A realm with [`crate::Options::es2015`] also has `Map`, `Set`, `WeakMap` and +//! `WeakSet` (in `collections`) and `ArrayBuffer`, `DataView` and the typed arrays (in `binary`). //! //! Every loop in a built-in takes a unit of fuel for each step, and every string, array, object //! or property it makes is checked against the heap limit before it is made, so no built-in can //! run past [`crate::Limits`]. mod array; +pub(crate) mod binary; +pub(crate) mod collections; pub(crate) mod extensions; mod global; mod json; @@ -145,6 +148,10 @@ fn try_install(interp: &mut Interp) -> JsResult<()> { if interp.options.e4x { crate::xml_builtins::install(interp)?; } + if interp.options.es2015 { + collections::install(interp)?; + binary::install(interp)?; + } Ok(()) } @@ -165,8 +172,16 @@ fn key_of(n: f64) -> Key { number_to_str(n).flat() } -/// ToUint32 of an object's `length`. +/// ToUint32 of an object's `length`. While a `%TypedArray%.prototype` method runs the array +/// method it shares, the typed array's length is its element count, whatever its `length` +/// property says (ECMA-262 6.0 section 22.2.3). fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + if interp.typed_length == Some(o) { + interp.typed_length = None; + if let Some(Class::TypedArray(view)) = interp.heap.object(o).map(|obj| &obj.class) { + return Ok(u32::try_from(view.length).unwrap_or(u32::MAX)); + } + } let len = interp.get_from(o, &key("length"), &Value::Object(o))?; Ok(to_uint32(interp.to_number(&len)?)) } diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..1c91d602b0 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -96,15 +96,23 @@ fn numeric_index(k: &[u16]) -> Option { Some(n) } -/// The objects of the prototype chain from `obj`, with how many properties (and String object -/// indices) each holds. +/// The indices a String object or a typed array holds without properties for them. +fn index_count(class: &Class) -> usize { + match class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + } +} + +/// The objects of the prototype chain from `obj`, with how many properties (and String object or +/// typed array indices) each holds. fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { let mut out = Vec::new(); let mut cur = Some(obj); while let Some(id) = cur { let Some(o) = interp.heap.object(id) else { break }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - out.push((id, o.props.len().saturating_add(string_len))); + out.push((id, o.props.len().saturating_add(index_count(&o.class)))); cur = o.proto; } out @@ -141,8 +149,7 @@ impl Indices { } interp.reserve_heap(n.saturating_mul(8).saturating_mul(self.maps.len() + 1))?; let Some(o) = interp.heap.object(id) else { continue }; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; - let present = (0..string_len as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); + let present = (0..index_count(&o.class) as u64).chain(o.props.iter().filter_map(|(k, _)| numeric_index(k))); for p in present { for map in &self.maps { let p = p as i64; @@ -335,13 +342,13 @@ fn locale_item(interp: &mut Interp, v: Value) -> JsResult> { } /// `Array.prototype.join` (section 15.4.4.5). -fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let separator = arg(args, 0); with_this(interp, &this, |interp, o| join_with(interp, o, &separator, join_item)) } /// `Array.prototype.toLocaleString` (section 15.4.4.3). -fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { +pub(super) fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, locale_item)) } @@ -413,7 +420,7 @@ fn push(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { +pub(super) fn reverse(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = u64::from(length_of(interp, o)?); let middle = len / 2; @@ -692,7 +699,7 @@ fn sort_elements(interp: &mut Interp, o: ObjId, len: u64, compare: &Value) -> Js // ---- searching ---- /// `Array.prototype.indexOf` (section 15.4.4.14). -fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -717,7 +724,7 @@ fn index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResu } /// `Array.prototype.lastIndexOf` (section 15.4.4.15). -fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn last_index_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| { let len = f64::from(length_of(interp, o)?); if len == 0.0 { @@ -794,15 +801,15 @@ fn iterate(interp: &mut Interp, this: Value, args: &[Value], kind: Each) -> JsRe }) } -fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn every(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Every) } -fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn some(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Some) } -fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { iterate(interp, this, args, Each::Visit) } @@ -852,10 +859,10 @@ fn fold(interp: &mut Interp, this: Value, args: &[Value], right: bool) -> JsResu }) } -fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, false) } -fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { +pub(super) fn reduce_right(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { fold(interp, this, args, true) } diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs new file mode 100644 index 0000000000..8c10723a74 --- /dev/null +++ b/crates/js/src/builtins/binary.rs @@ -0,0 +1,1143 @@ +//! `ArrayBuffer`, `DataView` and the typed arrays (ECMA-262 6.0 sections 24.1, 24.2 and 22.2): +//! `Int8Array`, `Uint8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`, `Int32Array`, +//! `Uint32Array`, `Float32Array` and `Float64Array`, with `%TypedArray%` and its prototype's +//! methods. A realm has them with [`crate::Options::es2015`]. +//! +//! A buffer's bytes are zero when it is made and never change length; no operation detaches +//! one. Views share their buffer's bytes. Typed arrays store their elements little-endian on +//! every platform, and a `DataView` reads and writes big-endian unless `littleEndian` is true. +//! A typed array's numeric property names are its elements or nothing (section 9.4.5, with the +//! element descriptors of later editions: writable, enumerable and configurable, and an element +//! that cannot be deleted); [`crate::interp::Interp`] calls [`element`], [`set_element`] and +//! [`define_element`] for them. +//! +//! A buffer longer than the realm's heap limit, or than 2^32 - 1 bytes, is a `RangeError`, and +//! every buffer's bytes are checked against the heap before they are allocated. Every element +//! a method visits takes a unit of fuel, and a sort's comparisons take one each. +//! +//! The language has no iterators yet, so constructing from an object and `%TypedArray%.from` +//! read an array, a string (by code point) or an object with a `length`, by index. + +use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; +use super::{arg, array, data, method, native, require_callable, to_integer}; +use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key}; +use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; +use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32}; + +/// The longest buffer, in bytes. +const MAX_BUFFER: u64 = u32::MAX as u64; + +/// The bytes each item a method gathers before it writes them is charged. +const ITEM_BYTES: usize = 16; + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + install_array_buffer(interp)?; + install_data_view(interp)?; + install_typed_arrays(interp) +} + +fn install_array_buffer(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.array_buffer_proto = proto; + let ctor = native(interp, "ArrayBuffer", array_buffer_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "ArrayBuffer", ctor, proto)?; + method(interp, ctor, "isView", is_view, 1)?; + getter(interp, proto, "get byteLength", buffer_byte_length)?; + method(interp, proto, "slice", buffer_slice, 2) +} + +fn install_data_view(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.data_view_proto = proto; + let ctor = native(interp, "DataView", data_view_ctor, 1, NativeKind::Plain, true)?; + super::constructor(interp, "DataView", ctor, proto)?; + getter(interp, proto, "get buffer", view_buffer)?; + getter(interp, proto, "get byteLength", view_byte_length)?; + getter(interp, proto, "get byteOffset", view_byte_offset)?; + let methods: [(&'static str, NativeFn, u32); 16] = [ + ("getInt8", get_int8, 1), + ("getUint8", get_uint8, 1), + ("getInt16", get_int16, 1), + ("getUint16", get_uint16, 1), + ("getInt32", get_int32, 1), + ("getUint32", get_uint32, 1), + ("getFloat32", get_float32, 1), + ("getFloat64", get_float64, 1), + ("setInt8", set_int8, 2), + ("setUint8", set_uint8, 2), + ("setInt16", set_int16, 2), + ("setUint16", set_uint16, 2), + ("setInt32", set_int32, 2), + ("setUint32", set_uint32, 2), + ("setFloat32", set_float32, 2), + ("setFloat64", set_float64, 2), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + Ok(()) +} + +fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + let proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.typed_array_proto = proto; + let ctor = native(interp, "TypedArray", abstract_ctor, 0, NativeKind::Plain, true)?; + interp.intrinsics.es2015.typed_array_ctor = ctor; + data(interp, ctor, "prototype", Value::Object(proto), 0)?; + data(interp, proto, "constructor", Value::Object(ctor), HIDDEN)?; + method(interp, ctor, "from", typed_from, 1)?; + method(interp, ctor, "of", typed_of, 0)?; + for (name, f) in + [("get buffer", ta_buffer as NativeFn), ("get byteLength", ta_byte_length), ("get byteOffset", ta_byte_offset), ("get length", ta_length)] + { + getter(interp, proto, name, f)?; + } + let methods: [(&'static str, NativeFn, u32); 23] = [ + ("copyWithin", copy_within, 2), + ("entries", ta_entries, 0), + ("every", ta_every, 1), + ("fill", fill, 1), + ("filter", filter, 1), + ("find", find, 1), + ("findIndex", find_index, 1), + ("forEach", ta_for_each, 1), + ("indexOf", ta_index_of, 1), + ("join", ta_join, 1), + ("keys", ta_keys, 0), + ("lastIndexOf", ta_last_index_of, 1), + ("map", map, 1), + ("reduce", ta_reduce, 1), + ("reduceRight", ta_reduce_right, 1), + ("reverse", ta_reverse, 0), + ("set", set, 1), + ("slice", slice, 2), + ("some", ta_some, 1), + ("sort", sort, 1), + ("subarray", subarray, 2), + ("toLocaleString", ta_to_locale_string, 0), + ("values", ta_values, 0), + ]; + for (name, f, length) in methods { + method(interp, proto, name, f, length)?; + } + // `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28). + let array_proto = interp.intrinsics.array_proto; + let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?; + interp.define(proto, key("toString"), crate::heap::Prop::Data { value: to_string, flags: HIDDEN })?; + + let ctors: [NativeFn; 9] = + [int8_ctor, uint8_ctor, uint8_clamped_ctor, int16_ctor, uint16_ctor, int32_ctor, uint32_ctor, float32_ctor, float64_ctor]; + for (elem, f) in Elem::ALL.into_iter().zip(ctors) { + let sub_proto = new_proto(interp, proto); + let sub = native(interp, elem.name(), f, 3, NativeKind::Plain, true)?; + if let Some(o) = interp.heap.object_mut(sub) { + o.proto = Some(ctor); + } + super::constructor(interp, elem.name(), sub, sub_proto)?; + #[allow(clippy::cast_precision_loss)] + let size = Value::Number(elem.size() as f64); + data(interp, sub, "BYTES_PER_ELEMENT", size.clone(), 0)?; + data(interp, sub_proto, "BYTES_PER_ELEMENT", size, 0)?; + if let Some(slot) = interp.intrinsics.es2015.typed_ctors.get_mut(elem.index()) { + *slot = sub; + } + if let Some(slot) = interp.intrinsics.es2015.typed_protos.get_mut(elem.index()) { + *slot = sub_proto; + } + } + Ok(()) +} + +// ---- elements ---- + +/// CanonicalNumericIndexString (section 7.1.16): the number a property name stands for when it +/// is the canonical text of that number, `-0` included. +pub(crate) fn canonical_index(k: &[u16]) -> Option { + if let Some(i) = array_index(k) { + return Some(f64::from(i)); + } + let first = *k.first()?; + if !(u16::from(b'0')..=u16::from(b'9')).contains(&first) && !b"-IN".iter().any(|c| u16::from(*c) == first) { + return None; + } + if k == [u16::from(b'-'), u16::from(b'0')] { + return Some(-0.0); + } + let n = string_to_number(k); + (*number_to_str(n).flat() == *k).then_some(n) +} + +/// The position of the element `n` names in a typed array of `length` elements, if it names one. +fn valid_index(n: f64, length: usize) -> Option { + if n.fract() != 0.0 || (n == 0.0 && n.is_sign_negative()) || n < 0.0 || !n.is_finite() { + return None; + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let i = n as usize; + (i < length).then_some(i) +} + +/// The buffer's bytes. +fn bytes(interp: &Interp, buffer: ObjId) -> Option<&[u8]> { + match &interp.heap.object(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +fn bytes_mut(interp: &mut Interp, buffer: ObjId) -> Option<&mut [u8]> { + match &mut interp.heap.object_mut(buffer)?.class { + Class::ArrayBuffer(b) => Some(b), + _ => None, + } +} + +/// Reads a value of `elem` from the start of `b` (GetValueFromBuffer, section 24.1.1.5). +fn decode(b: &[u8], elem: Elem, little: bool) -> Option { + let size = elem.size(); + let raw = b.get(..size)?; + let mut bits = 0u64; + for j in 0..size { + let byte = if little { raw.get(j) } else { raw.get(size - 1 - j) }; + bits |= u64::from(*byte?) << (8 * j); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] + Some(match elem { + Elem::Int8 => f64::from(bits as u8 as i8), + Elem::Uint8 | Elem::Uint8Clamped => f64::from(bits as u8), + Elem::Int16 => f64::from(bits as u16 as i16), + Elem::Uint16 => f64::from(bits as u16), + Elem::Int32 => f64::from(bits as u32 as i32), + Elem::Uint32 => f64::from(bits as u32), + Elem::Float32 => f64::from(f32::from_bits(bits as u32)), + Elem::Float64 => f64::from_bits(bits), + }) +} + +/// ToUint8Clamp (section 7.1.11): rounds to the nearest integer in 0 to 255, ties to even. +pub(crate) fn to_uint8_clamp(n: f64) -> u8 { + if n.is_nan() || n <= 0.0 { + return 0; + } + if n >= 255.0 { + return 255; + } + let f = n.floor(); + let r = if f + 0.5 < n { + f + 1.0 + } else if n < f + 0.5 || f % 2.0 == 0.0 { + f + } else { + f + 1.0 + }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let byte = r as u8; + byte +} + +/// Writes `n` as a value of `elem` at the start of `b` (SetValueInBuffer, section 24.1.1.6). +/// The integer types keep the low bits of ToUint32, which equal those of ToInt8, ToInt16 and +/// ToInt32. +fn encode(b: &mut [u8], elem: Elem, n: f64, little: bool) { + let size = elem.size(); + let bits = match elem { + Elem::Uint8Clamped => u64::from(to_uint8_clamp(n)), + #[allow(clippy::cast_possible_truncation)] + Elem::Float32 => u64::from((n as f32).to_bits()), + Elem::Float64 => n.to_bits(), + _ => u64::from(to_uint32(n)), + }; + for j in 0..size { + let slot = if little { b.get_mut(j) } else { b.get_mut(size - 1 - j) }; + if let Some(slot) = slot { + #[allow(clippy::cast_possible_truncation)] + let byte = (bits >> (8 * j)) as u8; + *slot = byte; + } + } +} + +/// The element of `view` at the index `n`, or `None` when `n` names no element. +pub(crate) fn element(interp: &Interp, view: &View, n: f64) -> Option { + let i = valid_index(n, view.length)?; + let at = view.offset.checked_add(i.checked_mul(view.elem.size())?)?; + decode(bytes(interp, view.buffer)?.get(at..)?, view.elem, true) +} + +/// The view of the typed array `id`. +fn view_of(interp: &Interp, id: ObjId) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(view) => Some(**view), + _ => None, + } +} + +/// Writes `n` to the element at position `i` of `view`, when there is one. +fn write(interp: &mut Interp, view: &View, i: usize, n: f64) { + let Some(at) = i.checked_mul(view.elem.size()).and_then(|o| o.checked_add(view.offset)) else { return }; + if i < view.length + && let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) + { + encode(b, view.elem, n, true); + } +} + +/// Copies `count` elements of `src` from position `from` to `dst` at position `to` byte for byte, as +/// a typed array is copied to one of the same element type (sections 22.2.3.22.2, 22.2.3.23 and +/// 22.2.4.3), so every bit pattern, a NaN's included, is kept. Overlapping ranges of one buffer copy +/// correctly. Each element takes a unit of fuel. +fn copy_elements(interp: &mut Interp, src: &View, from: usize, dst: &View, to: usize, count: usize) -> JsResult<()> { + for _ in 0..count { + interp.use_fuel()?; + } + let size = src.elem.size(); + let (s, d, n) = (src.offset + from * size, dst.offset + to * size, count * size); + if src.buffer == dst.buffer { + if let Some(b) = bytes_mut(interp, src.buffer) + && s + n <= b.len() + && d + n <= b.len() + { + b.copy_within(s..s + n, d); + } + return Ok(()); + } + // The destination's bytes are moved out while the source's are read, so no third copy is made. + let mut out = match &mut interp.object_mut(dst.buffer)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(from_bytes), Some(to_bytes)) = (bytes(interp, src.buffer).and_then(|b| b.get(s..s + n)), out.get_mut(d..d + n)) { + to_bytes.copy_from_slice(from_bytes); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(dst.buffer)?.class { + *b = out; + } + Ok(()) +} + +/// The number a typed array `id`'s numeric property name `k` stands for. +pub(crate) fn typed_key(interp: &Interp, id: ObjId, k: &[u16]) -> Option { + match &interp.heap.object(id)?.class { + Class::TypedArray(_) => canonical_index(k), + _ => None, + } +} + +/// `[[Set]]` of a numeric name of a typed array: the value is converted with ToNumber, then +/// written when the index names an element and ignored otherwise. +pub(crate) fn set_element(interp: &mut Interp, id: ObjId, n: f64, v: &Value) -> JsResult<()> { + let num = interp.to_number(v)?; + if let Some(view) = view_of(interp, id) + && let Some(i) = valid_index(n, view.length) + { + write(interp, &view, i, num); + } + Ok(()) +} + +/// `[[DefineOwnProperty]]` of a numeric name of a typed array (section 9.4.5.3, with the +/// configurable elements of later editions). +pub(crate) fn define_element(interp: &mut Interp, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + let view = view_of(interp, id); + let index = canonical_index(k).zip(view).and_then(|(n, view)| valid_index(n, view.length)); + let refused = + index.is_none() || desc.configurable == Some(false) || desc.enumerable == Some(false) || desc.is_accessor() || desc.writable == Some(false); + if refused { + if throw { + let name = String::from_utf16_lossy(k); + return Err(interp.type_error(&format!("cannot define property '{name}' of a typed array"))); + } + return Ok(false); + } + if let (Some(v), Some(view), Some(i)) = (&desc.value, view, index) { + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(true) +} + +// ---- making buffers and views ---- + +/// ToIndex (section 7.1.17 of later editions): `undefined` is 0, and a negative or too large +/// integer is a `RangeError`. +fn to_index(interp: &mut Interp, v: &Value, what: &str) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(0); + } + let n = to_integer(interp, v)?; + if !(0.0..=9_007_199_254_740_991.0).contains(&n) { + return Err(interp.throw(ErrorType::Range, &format!("{what} must be an integer from 0 to 2^53 - 1"))); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(n as u64) +} + +/// A new zeroed buffer of `len` bytes. A length past [`MAX_BUFFER`] or the heap limit is a +/// `RangeError`; otherwise the bytes and `extra` more are reserved before the buffer is +/// allocated. +fn new_buffer(interp: &mut Interp, len: u64, extra: usize) -> JsResult { + if len > MAX_BUFFER || len > interp.limits.heap_bytes as u64 { + return Err(interp.throw(ErrorType::Range, &format!("an array buffer of {len} bytes is larger than the heap limit allows"))); + } + let len = usize::try_from(len).map_err(|_| interp.throw(ErrorType::Range, "the array buffer is too large"))?; + interp.reserve_heap(OBJECT_BYTES.saturating_add(len).saturating_add(extra))?; + let mut b = Vec::new(); + if b.try_reserve_exact(len).is_err() { + return Err(interp.throw(ErrorType::Range, "the memory for the array buffer could not be allocated")); + } + b.resize(len, 0); + let proto = interp.intrinsics.es2015.array_buffer_proto; + let o = interp.heap.alloc_object(Object::new(Class::ArrayBuffer(b.into_boxed_slice()), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(len); + Ok(o) +} + +/// A new view object of `class` on a buffer that is reachable. Its heap was reserved before. +fn new_view(interp: &mut Interp, class: Class, proto: ObjId) -> ObjId { + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + o +} + +fn typed_proto(interp: &Interp, elem: Elem) -> ObjId { + interp.intrinsics.es2015.typed_protos.get(elem.index()).copied().unwrap_or(interp.intrinsics.es2015.typed_array_proto) +} + +/// A new typed array of `len` zero elements of `elem`, with a new buffer. +fn new_typed(interp: &mut Interp, elem: Elem, len: u64) -> JsResult { + let byte_len = len.saturating_mul(elem.size() as u64); + let buffer = new_buffer(interp, byte_len, OBJECT_BYTES + VIEW_BYTES)?; + let length = usize::try_from(len).unwrap_or(0); + let proto = typed_proto(interp, elem); + Ok(new_view(interp, Class::TypedArray(Box::new(View { buffer, offset: 0, length, elem })), proto)) +} + +/// `new ArrayBuffer(length)` (section 24.1.2.1). +fn array_buffer_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("ArrayBuffer must be called with new")); + } + let len = to_index(interp, &arg(args, 0), "the length")?; + new_buffer(interp, len, 0).map(Value::Object) +} + +/// `ArrayBuffer.isView` (section 24.1.3.1). +fn is_view(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let view = + arg(args, 0).as_object().and_then(|o| interp.heap.object(o)).is_some_and(|o| matches!(o.class, Class::DataView(_) | Class::TypedArray(_))); + Ok(Value::Bool(view)) +} + +fn this_buffer(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + match this.as_object() { + Some(o) if bytes(interp, o).is_some() => Ok(o), + _ => Err(interp.type_error(&format!("ArrayBuffer.prototype.{name} was called on a value that is not an ArrayBuffer"))), + } +} + +fn buffer_len(interp: &Interp, o: ObjId) -> usize { + bytes(interp, o).map_or(0, <[u8]>::len) +} + +fn buffer_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "byteLength")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(buffer_len(interp, o) as f64)) +} + +/// A relative index (as `slice` reads its arguments): negative counts from `len`, and the result +/// is clamped to 0 to `len`. `undefined` gives `default`. +fn relative(interp: &mut Interp, v: &Value, len: usize, default: usize) -> JsResult { + if matches!(v, Value::Undefined) { + return Ok(default); + } + let n = to_integer(interp, v)?; + #[allow(clippy::cast_precision_loss)] + let len_f = len as f64; + let r = if n < 0.0 { (len_f + n).max(0.0) } else { n.min(len_f) }; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(r as usize) +} + +/// `ArrayBuffer.prototype.slice` (section 24.1.4.3). +fn buffer_slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_buffer(interp, &this, "slice")?; + let len = buffer_len(interp, o); + let first = relative(interp, &arg(args, 0), len, 0)?; + let last = relative(interp, &arg(args, 1), len, len)?; + let count = last.saturating_sub(first); + // Each copied byte takes a unit of fuel, charged before the copy is made. + for _ in 0..count { + interp.use_fuel()?; + } + let new = interp.rooted(std::slice::from_ref(&this), |i| new_buffer(i, count as u64, 0))?; + // The new buffer's bytes are moved out while the source's are read, so no third copy is made. + let mut dst = match &mut interp.object_mut(new)?.class { + Class::ArrayBuffer(b) => std::mem::take(b), + _ => return Err(Abrupt::Internal("not an array buffer".into())), + }; + if let (Some(src), Some(to)) = (bytes(interp, o).and_then(|b| b.get(first..first + count)), dst.get_mut(..count)) { + to.copy_from_slice(src); + } + if let Class::ArrayBuffer(b) = &mut interp.object_mut(new)?.class { + *b = dst; + } + Ok(Value::Object(new)) +} + +// ---- DataView ---- + +/// `new DataView(buffer, byteOffset, byteLength)` (section 24.2.2.1). +fn data_view_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + if !constructing { + return Err(interp.type_error("DataView must be called with new")); + } + let buffer = match arg(args, 0).as_object() { + Some(o) if bytes(interp, o).is_some() => o, + _ => return Err(interp.type_error("the first argument of DataView must be an ArrayBuffer")), + }; + let offset = to_index(interp, &arg(args, 1), "the byte offset")?; + let len = buffer_len(interp, buffer) as u64; + if offset > len { + return Err(interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer")); + } + let view_len = match arg(args, 2) { + Value::Undefined => len - offset, + v => to_index(interp, &v, "the byte length")?, + }; + if offset.saturating_add(view_len) > len { + return Err(interp.throw(ErrorType::Range, "the view does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = interp.intrinsics.es2015.data_view_proto; + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(view_len).unwrap_or(0), elem: Elem::Uint8 }; + Ok(Value::Object(new_view(interp, Class::DataView(Box::new(view)), proto))) +} + +fn this_data_view(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + if let Some(Class::DataView(view)) = this.as_object().and_then(|o| interp.heap.object(o)).map(|o| &o.class) { + return Ok(**view); + } + Err(interp.type_error(&format!("DataView.prototype.{name} was called on a value that is not a DataView"))) +} + +fn view_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_data_view(interp, &this, "buffer")?.buffer)) +} + +fn view_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteLength")?.length as f64)) +} + +fn view_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_data_view(interp, &this, "byteOffset")?.offset as f64)) +} + +/// The byte position in the buffer of a `DataView` access of `elem` at `index`, or a +/// `RangeError` when it does not fit in the view (sections 24.2.1.1 and 24.2.1.2). +fn view_position(interp: &mut Interp, view: &View, index: u64, elem: Elem) -> JsResult { + let end = index.saturating_add(elem.size() as u64); + if end > view.length as u64 { + return Err(interp.throw(ErrorType::Range, "the offset is outside the bounds of the DataView")); + } + Ok(view.offset + usize::try_from(index).unwrap_or(0)) +} + +/// GetViewValue (section 24.2.1.1). +fn view_get(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let little = arg(args, 1).truthy(); + let at = view_position(interp, &view, index, elem)?; + let n = bytes(interp, view.buffer).and_then(|b| b.get(at..)).and_then(|b| decode(b, elem, little)).unwrap_or(0.0); + Ok(Value::Number(n)) +} + +/// SetViewValue (section 24.2.1.2): the offset, then the value, then `littleEndian` are read +/// before the bounds are checked. +fn view_set(interp: &mut Interp, this: &Value, args: &[Value], elem: Elem, name: &str) -> JsResult { + let view = this_data_view(interp, this, name)?; + let index = to_index(interp, &arg(args, 0), "the offset")?; + let n = interp.to_number(&arg(args, 1))?; + let little = arg(args, 2).truthy(); + let at = view_position(interp, &view, index, elem)?; + if let Some(b) = bytes_mut(interp, view.buffer).and_then(|b| b.get_mut(at..)) { + encode(b, elem, n, little); + } + Ok(Value::Undefined) +} + +macro_rules! view_methods { + ($($get:ident, $set:ident, $elem:ident, $getname:literal, $setname:literal;)*) => { + $( + fn $get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_get(interp, &this, args, Elem::$elem, $getname) + } + + fn $set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + view_set(interp, &this, args, Elem::$elem, $setname) + } + )* + }; +} + +view_methods! { + get_int8, set_int8, Int8, "getInt8", "setInt8"; + get_uint8, set_uint8, Uint8, "getUint8", "setUint8"; + get_int16, set_int16, Int16, "getInt16", "setInt16"; + get_uint16, set_uint16, Uint16, "getUint16", "setUint16"; + get_int32, set_int32, Int32, "getInt32", "setInt32"; + get_uint32, set_uint32, Uint32, "getUint32", "setUint32"; + get_float32, set_float32, Float32, "getFloat32", "setFloat32"; + get_float64, set_float64, Float64, "getFloat64", "setFloat64"; +} + +// ---- typed array constructors ---- + +/// `%TypedArray%` itself (section 22.2.1.1) cannot be called or constructed. +fn abstract_ctor(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Err(interp.type_error("TypedArray cannot be called or constructed; use a typed array constructor such as Uint8Array")) +} + +/// `new Int8Array(…)` and the other typed array constructors (section 22.2.4). +fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Elem) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{} must be called with new", elem.name()))); + } + let first = arg(args, 0); + let Value::Object(o) = first else { + let len = to_index(interp, &first, "the length")?; + return new_typed(interp, elem, len).map(Value::Object); + }; + if bytes(interp, o).is_some() { + return typed_on_buffer(interp, o, &arg(args, 1), &arg(args, 2), elem).map(Value::Object); + } + if let Some(src) = view_of(interp, o) { + let ta = new_typed(interp, elem, src.length as u64)?; + let dst = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + if src.elem == elem { + copy_elements(interp, &src, 0, &dst, 0, src.length)?; + return Ok(Value::Object(ta)); + } + for i in 0..src.length { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let n = element(interp, &src, i as f64).unwrap_or(0.0); + write(interp, &dst, i, n); + } + return Ok(Value::Object(ta)); + } + let len = length_of(interp, o)?; + let ta = new_typed(interp, elem, len)?; + interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?; + Ok(Value::Object(ta)) +} + +/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`, +/// each converted with ToNumber. +fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> { + let Value::Object(o) = src else { return Ok(()) }; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(*o, &super::key_of(i as f64), src)?; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(()) +} + +/// A typed array on part of `buffer` (section 22.2.4.5). +fn typed_on_buffer(interp: &mut Interp, buffer: ObjId, offset: &Value, length: &Value, elem: Elem) -> JsResult { + let size = elem.size() as u64; + let offset = to_index(interp, offset, "the byte offset")?; + if !offset.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the byte offset of a {} must be a multiple of {size}", elem.name()))); + } + let new_length = match length { + Value::Undefined => None, + v => Some(to_index(interp, v, "the length")?), + }; + let buf_len = buffer_len(interp, buffer) as u64; + let byte_len = match new_length { + None => { + if !buf_len.is_multiple_of(size) { + return Err(interp.throw(ErrorType::Range, &format!("the buffer's length must be a multiple of {size}"))); + } + buf_len.checked_sub(offset).ok_or_else(|| interp.throw(ErrorType::Range, "the byte offset is past the end of the buffer"))? + } + Some(n) => n.saturating_mul(size), + }; + if offset.saturating_add(byte_len) > buf_len { + return Err(interp.throw(ErrorType::Range, "the typed array does not fit in the buffer")); + } + interp.rooted(&[Value::Object(buffer)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = typed_proto(interp, elem); + let view = View { buffer, offset: usize::try_from(offset).unwrap_or(0), length: usize::try_from(byte_len / size).unwrap_or(0), elem }; + Ok(new_view(interp, Class::TypedArray(Box::new(view)), proto)) +} + +macro_rules! typed_ctors { + ($($f:ident, $elem:ident;)*) => { + $( + fn $f(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + typed_ctor(interp, args, constructing, Elem::$elem) + } + )* + }; +} + +typed_ctors! { + int8_ctor, Int8; + uint8_ctor, Uint8; + uint8_clamped_ctor, Uint8Clamped; + int16_ctor, Int16; + uint16_ctor, Uint16; + int32_ctor, Int32; + uint32_ctor, Uint32; + float32_ctor, Float32; + float64_ctor, Float64; +} + +/// The element type of the typed array constructor `this`, as `from` and `of` need. +fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { + let ctors = interp.intrinsics.es2015.typed_ctors; + if let Some(o) = this.as_object() + && let Some(i) = ctors.iter().position(|c| *c == o) + && let Some(elem) = Elem::ALL.get(i) + { + return Ok(*elem); + } + Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) +} + +/// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). +fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + if !interp.is_callable(&this) { + return Err(interp.type_error("TypedArray.from must be called on a typed array constructor")); + } + let map_fn = arg(args, 1); + let mapping = !matches!(map_fn, Value::Undefined); + if mapping { + require_callable(interp, &map_fn, "the map function")?; + } + let this_arg = arg(args, 2); + let source = arg(args, 0); + if !matches!(source, Value::String(_)) { + // An array-like source: each element is read, mapped and written before the next is read. + let src = interp.to_object(&source)?; + let src_value = Value::Object(src); + let len = length_of(interp, src)?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { + for i in 0..len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); + } + Ok(Value::Object(ta)) + }); + } + // A string is read by code point first, as an iterable source is, and then mapped. + let mark = interp.temp_roots.len(); + let mut held = crate::interp::HeldBytes::new(interp); + let gathered = for_each_item(interp, &source, false, |interp, item| { + held.add(interp, ITEM_BYTES)?; + interp.temp_roots.push(item); + Ok(()) + }); + let result = gathered.and_then(|()| { + let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); + let elem = ctor_elem(interp, &this, "from")?; + let ta = new_typed(interp, elem, items.len() as u64)?; + interp.temp_roots.push(Value::Object(ta)); + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, item) in items.into_iter().enumerate() { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; + let n = interp.to_number(&v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }); + interp.temp_roots.truncate(mark); + drop(held); + result +} + +/// `%TypedArray%.of(...items)` (section 22.2.2.2). +fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let elem = ctor_elem(interp, &this, "of")?; + let ta = new_typed(interp, elem, args.len() as u64)?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(ta)], |interp| { + for (i, v) in args.iter().enumerate() { + interp.use_fuel()?; + let n = interp.to_number(v)?; + write(interp, &view, i, n); + } + Ok(Value::Object(ta)) + }) +} + +// ---- %TypedArray%.prototype ---- + +/// The typed array a method was called on (ValidateTypedArray, section 22.2.3.5.1). +fn this_typed(interp: &mut Interp, this: &Value, name: &str) -> JsResult<(ObjId, View)> { + if let Some(o) = this.as_object() + && let Some(view) = view_of(interp, o) + { + return Ok((o, view)); + } + Err(interp.type_error(&format!("TypedArray.prototype.{name} was called on a value that is not a typed array"))) +} + +fn ta_buffer(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Object(this_typed(interp, &this, "buffer")?.1.buffer)) +} + +fn ta_byte_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let view = this_typed(interp, &this, "byteLength")?.1; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number((view.length * view.elem.size()) as f64)) +} + +fn ta_byte_offset(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "byteOffset")?.1.offset as f64)) +} + +fn ta_length(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(this_typed(interp, &this, "length")?.1.length as f64)) +} + +/// The element at position `i`, 0 past the end. +fn at(interp: &Interp, view: &View, i: usize) -> f64 { + #[allow(clippy::cast_precision_loss)] + element(interp, view, i as f64).unwrap_or(0.0) +} + +/// Runs the array prototype's generic method `f` on a typed array, after checking `this`. +/// The array method reads the typed array's element count as its length, not its `length` +/// property. +fn generic(interp: &mut Interp, this: Value, args: &[Value], name: &str, f: NativeFn) -> JsResult { + let (o, _) = this_typed(interp, &this, name)?; + let saved = interp.typed_length.replace(o); + let result = f(interp, this, args, false); + interp.typed_length = saved; + result +} + +macro_rules! generic_methods { + ($($f:ident, $name:literal, $array:path;)*) => { + $( + fn $f(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + generic(interp, this, args, $name, $array) + } + )* + }; +} + +generic_methods! { + ta_every, "every", array::every; + ta_some, "some", array::some; + ta_for_each, "forEach", array::for_each; + ta_index_of, "indexOf", array::index_of; + ta_last_index_of, "lastIndexOf", array::last_index_of; + ta_join, "join", array::join; + ta_reduce, "reduce", array::reduce; + ta_reduce_right, "reduceRight", array::reduce_right; + ta_reverse, "reverse", array::reverse; + ta_to_locale_string, "toLocaleString", array::to_locale_string; +} + +fn iter_of(interp: &mut Interp, this: &Value, kind: IterKind, name: &str) -> JsResult { + let (o, _) = this_typed(interp, this, name)?; + new_iter(interp, o, IterSource::Array, kind, None).map(Value::Object) +} + +fn ta_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Keys, "keys") +} + +fn ta_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Values, "values") +} + +fn ta_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_of(interp, &this, IterKind::Entries, "entries") +} + +/// `fill(value, start, end)` (section 22.2.3.8): the value is converted once, before the range. +fn fill(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "fill")?; + let n = interp.to_number(&arg(args, 0))?; + let start = relative(interp, &arg(args, 1), view.length, 0)?; + let end = relative(interp, &arg(args, 2), view.length, view.length)?; + for i in start..end { + interp.use_fuel()?; + write(interp, &view, i, n); + } + Ok(this) +} + +/// Calls `f(element, index, array)` for each element in order until `stop` says the result is +/// found; returns the index and the element. +fn search(interp: &mut Interp, this: &Value, args: &[Value], name: &str) -> JsResult> { + let (_, view) = this_typed(interp, this, name)?; + let f = arg(args, 0); + require_callable(interp, &f, "the predicate")?; + let this_arg = arg(args, 1); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + return Ok(Some((i, v))); + } + } + Ok(None) +} + +/// `find` (section 22.2.3.10). +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + Ok(search(interp, &this, args, "find")?.map_or(Value::Undefined, |(_, v)| Value::Number(v))) +} + +/// `findIndex` (section 22.2.3.11). +fn find_index(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(search(interp, &this, args, "findIndex")?.map_or(-1.0, |(i, _)| i as f64))) +} + +/// `map` (section 22.2.3.18): a new typed array of the same type holding each callback result. +fn map(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "map")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let out = new_typed(interp, view.elem, view.length as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + interp.rooted(&[Value::Object(out)], |interp| { + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + let n = interp.to_number(&r)?; + write(interp, &dst, i, n); + } + Ok(Value::Object(out)) + }) +} + +/// A new typed array of `elem` holding `values`. +fn typed_from_values(interp: &mut Interp, elem: Elem, values: &[f64]) -> JsResult { + let out = new_typed(interp, elem, values.len() as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + for (i, n) in values.iter().enumerate() { + write(interp, &dst, i, *n); + } + Ok(out) +} + +/// `filter` (section 22.2.3.9). +fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "filter")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let mut held = crate::interp::HeldBytes::new(interp); + let mut kept = Vec::new(); + for i in 0..view.length { + interp.use_fuel()?; + let v = at(interp, &view, i); + #[allow(clippy::cast_precision_loss)] + let r = interp.call(&f, &this_arg, &[Value::Number(v), Value::Number(i as f64), this.clone()])?; + if r.truthy() { + held.add(interp, 8)?; + kept.push(v); + } + } + let out = typed_from_values(interp, view.elem, &kept)?; + drop(held); + Ok(Value::Object(out)) +} + +/// `slice(start, end)` (section 22.2.3.23): a copy of the range in a new buffer. +fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "slice")?; + let start = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + let count = end.saturating_sub(start); + let out = new_typed(interp, view.elem, count as u64)?; + let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + copy_elements(interp, &view, start, &dst, 0, count)?; + Ok(Value::Object(out)) +} + +/// `subarray(begin, end)` (section 22.2.3.26): a new view on the same buffer. +fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "subarray")?; + let begin = relative(interp, &arg(args, 0), view.length, 0)?; + let end = relative(interp, &arg(args, 1), view.length, view.length)?; + interp.rooted(std::slice::from_ref(&this), |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let sub = View { buffer: view.buffer, offset: view.offset + begin * view.elem.size(), length: end.saturating_sub(begin), elem: view.elem }; + let proto = typed_proto(interp, view.elem); + Ok(Value::Object(new_view(interp, Class::TypedArray(Box::new(sub)), proto))) +} + +/// `set(source, offset)` (section 22.2.3.22): writes a typed array's elements, or an array-like +/// object's elements converted with ToNumber, starting at `offset`. A source that does not fit +/// is a `RangeError`. A typed array source is read in full before anything is written, so a +/// source on the same buffer copies correctly. +fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "set")?; + let offset = to_integer(interp, &arg(args, 1))?; + if offset < 0.0 { + return Err(interp.throw(ErrorType::Range, "the offset must not be negative")); + } + let source = arg(args, 0); + let src_view = source.as_object().and_then(|o| view_of(interp, o)); + let src_len = match (&source, src_view) { + (_, Some(v)) => v.length as u64, + (Value::Object(o), None) => length_of(interp, *o)?, + _ => { + let o = interp.to_object(&source)?; + length_of(interp, o)? + } + }; + #[allow(clippy::cast_precision_loss)] + if offset + src_len as f64 > view.length as f64 { + return Err(interp.throw(ErrorType::Range, "the source does not fit in the typed array at that offset")); + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let offset = offset as usize; + let count = usize::try_from(src_len).unwrap_or(0); + if let Some(src) = src_view.filter(|src| src.elem == view.elem) { + copy_elements(interp, &src, 0, &view, offset, count)?; + return Ok(Value::Undefined); + } + if let Some(src) = src_view { + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, count.saturating_mul(8))?; + let mut values = Vec::with_capacity(count); + for i in 0..count { + interp.use_fuel()?; + values.push(at(interp, &src, i)); + } + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, offset + i, n); + } + return Ok(Value::Undefined); + } + let src = interp.to_object(&source)?; + interp.rooted(&[Value::Object(src)], |interp| { + for i in 0..count { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let v = interp.get_from(src, &super::key_of(i as f64), &Value::Object(src))?; + let n = interp.to_number(&v)?; + write(interp, &view, offset + i, n); + } + Ok(Value::Undefined) + }) +} + +/// `copyWithin(target, start, end)` (section 22.2.3.5): moves the bytes of the range within the +/// buffer, overlapping ranges included. +fn copy_within(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (_, view) = this_typed(interp, &this, "copyWithin")?; + let len = view.length; + let to = relative(interp, &arg(args, 0), len, 0)?; + let from = relative(interp, &arg(args, 1), len, 0)?; + let end = relative(interp, &arg(args, 2), len, len)?; + let count = end.saturating_sub(from).min(len - to); + copy_elements(interp, &view, from, &view, to, count)?; + Ok(this) +} + +/// The default order of `sort` (section 22.2.3.25): numeric, with `-0` before `+0` and `NaN` +/// last. +fn default_order(a: f64, b: f64) -> std::cmp::Ordering { + use std::cmp::Ordering; + match (a.is_nan(), b.is_nan()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + _ if a == 0.0 && b == 0.0 => b.is_sign_negative().cmp(&a.is_sign_negative()), + _ => a.partial_cmp(&b).unwrap_or(Ordering::Equal), + } +} + +/// Whether `b` goes before `a`: by `compare` when it is a function, the default order otherwise. +/// Each comparison takes a unit of fuel. +fn goes_before(interp: &mut Interp, compare: &Value, a: f64, b: f64) -> JsResult { + interp.use_fuel()?; + if matches!(compare, Value::Undefined) { + return Ok(default_order(b, a) == std::cmp::Ordering::Less); + } + let r = interp.call(compare, &Value::Undefined, &[Value::Number(a), Value::Number(b)])?; + let n = interp.to_number(&r)?; + Ok(n > 0.0) +} + +/// Sorts `values` stably with a merge sort whose comparisons may fail. +fn merge_sort(interp: &mut Interp, values: &mut Vec, compare: &Value) -> JsResult<()> { + let n = values.len(); + let mut buf = values.clone(); + let mut width = 1; + while width < n { + let mut lo = 0; + while lo < n { + let mid = (lo + width).min(n); + let hi = (lo + 2 * width).min(n); + let (mut i, mut j) = (lo, mid); + for slot in buf.iter_mut().take(hi).skip(lo) { + let take_right = match (values.get(i), values.get(j)) { + (Some(&a), Some(&b)) if i < mid && j < hi => goes_before(interp, compare, a, b)?, + _ => i >= mid, + }; + let pick = if take_right { &mut j } else { &mut i }; + *slot = values.get(*pick).copied().unwrap_or(0.0); + *pick += 1; + } + lo = hi; + } + std::mem::swap(values, &mut buf); + width *= 2; + } + Ok(()) +} + +/// `sort(comparefn)` (section 22.2.3.25). +fn sort(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let compare = arg(args, 0); + if !matches!(compare, Value::Undefined) { + require_callable(interp, &compare, "the comparison function")?; + } + let (_, view) = this_typed(interp, &this, "sort")?; + let mut held = crate::interp::HeldBytes::new(interp); + held.add(interp, view.length.saturating_mul(16))?; + let mut values: Vec = (0..view.length).map(|i| at(interp, &view, i)).collect(); + merge_sort(interp, &mut values, &compare)?; + for (i, n) in values.into_iter().enumerate() { + write(interp, &view, i, n); + } + Ok(this) +} diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs new file mode 100644 index 0000000000..1798707aff --- /dev/null +++ b/crates/js/src/builtins/collections.rs @@ -0,0 +1,696 @@ +//! `Map`, `Set`, `WeakMap` and `WeakSet` (ECMA-262 6.0 sections 23.1 to 23.4), and the iterator +//! objects that `keys`, `values` and `entries` give for Maps, Sets and typed arrays (sections +//! 23.1.5, 23.2.5 and 22.1.5). A realm has them with [`crate::Options::es2015`]. +//! +//! Keys compare with SameValueZero, and a key of `-0` is stored as `+0`. Entries keep the order +//! they were added in; deleting one leaves a hole, so `forEach` and an iterator visit the entries +//! added while they run and skip the ones deleted before they reach them. WeakMap and WeakSet +//! entries hold their key weakly: the collector removes an entry once its key is reachable only +//! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed. +//! +//! The language has no iterators yet, so the constructors read their argument by index: an +//! array or an object with a `length`, or a string by code point. Every entry added is checked +//! against the heap limit before it is added, and every entry visited takes a unit of fuel. + +use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable}; +use crate::heap::{ + COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, + PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes, +}; +use crate::interp::{Abrupt, Interp, JsResult}; +use crate::string_builtins::flat_charged; +use crate::value::{Str, Value}; + +/// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does +/// to the globals. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Es2015 { + pub(crate) map_proto: ObjId, + pub(crate) set_proto: ObjId, + pub(crate) weak_map_proto: ObjId, + pub(crate) weak_set_proto: ObjId, + pub(crate) map_iter_proto: ObjId, + pub(crate) set_iter_proto: ObjId, + pub(crate) array_iter_proto: ObjId, + pub(crate) array_buffer_proto: ObjId, + pub(crate) data_view_proto: ObjId, + /// `%TypedArray%` and its prototype (section 22.2.1). + pub(crate) typed_array_ctor: ObjId, + pub(crate) typed_array_proto: ObjId, + /// The typed array constructors and prototypes, in the order of [`crate::heap::Elem::ALL`]. + pub(crate) typed_ctors: [ObjId; 9], + pub(crate) typed_protos: [ObjId; 9], +} + +impl Es2015 { + pub(crate) fn placeholder() -> Self { + let o = ObjId(0); + Self { + map_proto: o, + set_proto: o, + weak_map_proto: o, + weak_set_proto: o, + map_iter_proto: o, + set_iter_proto: o, + array_iter_proto: o, + array_buffer_proto: o, + data_view_proto: o, + typed_array_ctor: o, + typed_array_proto: o, + typed_ctors: [o; 9], + typed_protos: [o; 9], + } + } + + pub(crate) fn all(&self) -> Vec { + let mut v = vec![ + self.map_proto, + self.set_proto, + self.weak_map_proto, + self.weak_set_proto, + self.map_iter_proto, + self.set_iter_proto, + self.array_iter_proto, + self.array_buffer_proto, + self.data_view_proto, + self.typed_array_ctor, + self.typed_array_proto, + ]; + v.extend(self.typed_ctors); + v.extend(self.typed_protos); + v + } +} + +/// A new ordinary object with `proto`, for a prototype. +pub(crate) fn new_proto(interp: &mut Interp, proto: ObjId) -> ObjId { + interp.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))) +} + +/// Defines a getter `name` on `on`, configurable and not enumerable, as the prototype accessors +/// of ECMAScript 2015 are. +pub(crate) fn getter(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn) -> JsResult<()> { + let g = native(interp, name, f, 0, NativeKind::Plain, false)?; + let prop_name = name.strip_prefix("get ").unwrap_or(name); + interp.define(on, key(prop_name), Prop::Accessor { get: Some(g), set: None, flags: CONFIGURABLE }) +} + +pub(super) fn install(interp: &mut Interp) -> JsResult<()> { + let object_proto = interp.intrinsics.object_proto; + + let map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.map_proto = map_proto; + let map = native(interp, "Map", map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Map", map, map_proto)?; + let map_methods: [(&'static str, NativeFn, u32); 9] = [ + ("get", map_get, 1), + ("set", map_set, 2), + ("has", map_has, 1), + ("delete", map_delete, 1), + ("clear", map_clear, 0), + ("forEach", map_for_each, 1), + ("keys", map_keys, 0), + ("values", map_values, 0), + ("entries", map_entries, 0), + ]; + for (name, f, length) in map_methods { + method(interp, map_proto, name, f, length)?; + } + getter(interp, map_proto, "get size", map_size)?; + + let set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.set_proto = set_proto; + let set = native(interp, "Set", set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "Set", set, set_proto)?; + let set_methods: [(&'static str, NativeFn, u32); 7] = [ + ("has", set_has, 1), + ("add", set_add, 1), + ("delete", set_delete, 1), + ("clear", set_clear, 0), + ("entries", set_entries, 0), + ("forEach", set_for_each, 1), + ("values", set_values, 0), + ]; + for (name, f, length) in set_methods { + method(interp, set_proto, name, f, length)?; + } + getter(interp, set_proto, "get size", set_size)?; + // `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8). + let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?; + interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + + let weak_map_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_map_proto = weak_map_proto; + let weak_map = native(interp, "WeakMap", weak_map_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakMap", weak_map, weak_map_proto)?; + let weak_map_methods: [(&'static str, NativeFn, u32); 4] = + [("delete", weak_map_delete, 1), ("get", weak_map_get, 1), ("has", weak_map_has, 1), ("set", weak_map_set, 2)]; + for (name, f, length) in weak_map_methods { + method(interp, weak_map_proto, name, f, length)?; + } + + let weak_set_proto = new_proto(interp, object_proto); + interp.intrinsics.es2015.weak_set_proto = weak_set_proto; + let weak_set = native(interp, "WeakSet", weak_set_ctor, 0, NativeKind::Plain, true)?; + constructor(interp, "WeakSet", weak_set, weak_set_proto)?; + let weak_set_methods: [(&'static str, NativeFn, u32); 3] = [("add", weak_set_add, 1), ("delete", weak_set_delete, 1), ("has", weak_set_has, 1)]; + for (name, f, length) in weak_set_methods { + method(interp, weak_set_proto, name, f, length)?; + } + + for source in [IterSource::Map, IterSource::Set, IterSource::Array] { + let proto = new_proto(interp, object_proto); + let next: NativeFn = match source { + IterSource::Map => map_iterator_next, + IterSource::Set => set_iterator_next, + IterSource::Array => array_iterator_next, + }; + method(interp, proto, "next", next, 0)?; + match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto = proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto = proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto = proto, + } + } + Ok(()) +} + +// ---- keys ---- + +/// The SameValueZero key of `v`. A string is flattened, its copy charged to the heap. +fn coll_key(interp: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => CollKey::Undefined, + Value::Null => CollKey::Null, + Value::Bool(b) => CollKey::Bool(*b), + Value::Number(n) => CollKey::number(*n), + Value::String(s) => CollKey::String(flat_charged(interp, s)?), + Value::Object(o) => CollKey::Object(o.0), + }) +} + +/// `v`, with `-0` made `+0`, as Map and Set store a key (sections 23.1.3.9 and 23.2.3.1). +fn stored_key(v: Value) -> Value { + match v { + // `-0 + 0` is `+0`, and every other number is unchanged by adding `+0`. + Value::Number(n) => Value::Number(n + 0.0), + v => v, + } +} + +// ---- reading a list ---- + +/// ToLength (section 7.1.15) of an object's `length`. +pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { + let len = interp.get_from(o, &key("length"), &Value::Object(o))?; + let n = super::to_integer(interp, &len)?; + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 }) +} + +/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`, +/// or a string's code points. Any other value is a `TypeError`, and so is an object without a +/// `length` when `need_length` is true. Each item takes a unit of fuel. +pub(crate) fn for_each_item( + interp: &mut Interp, + list: &Value, + need_length: bool, + mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>, +) -> JsResult<()> { + match list { + Value::Object(o) => { + if need_length && !interp.has_property(*o, &key("length"))? { + return Err(interp.type_error("the value is not an array, a string or an object with a length")); + } + let len = length_of(interp, *o)?; + let mut i = 0u64; + while i < len { + interp.use_fuel()?; + #[allow(clippy::cast_precision_loss)] + let item = interp.get_from(*o, &key_of(i as f64), list)?; + f(interp, item)?; + i += 1; + } + Ok(()) + } + Value::String(s) => { + let units = flat_charged(interp, s)?; + let mut i = 0; + while i < units.len() { + interp.use_fuel()?; + let width = match (units.get(i), units.get(i + 1)) { + (Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2, + _ => 1, + }; + let piece = units.get(i..i + width).unwrap_or_default().to_vec(); + let bytes = string_bytes(piece.len()); + interp.reserve_heap(bytes)?; + interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); + f(interp, Value::String(Str::from_units(piece)))?; + i += width; + } + Ok(()) + } + _ => Err(interp.type_error("the value is not an array, a string or an object with a length")), + } +} + +/// Adds the items of `list` to the new collection `target` with its `adder` method, as the +/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item +/// as a `[key, value]` entry. +fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> { + if list.is_nullish() { + return Ok(()); + } + let this = Value::Object(target); + interp.rooted(&[this.clone(), list.clone()], |interp| { + let add = interp.get_from(target, &key(adder), &this)?; + require_callable(interp, &add, adder)?; + interp.rooted(std::slice::from_ref(&add), |interp| { + for_each_item(interp, list, true, |interp, item| { + if !pairs { + return interp.call(&add, &this, &[item]).map(drop); + } + let Value::Object(entry) = item else { return Err(interp.type_error("an entry is not an object")) }; + let k = interp.get_from(entry, &key("0"), &item)?; + let v = interp.rooted(std::slice::from_ref(&k), |interp| interp.get_from(entry, &key("1"), &item))?; + interp.call(&add, &this, &[k, v]).map(drop) + }) + }) + }) +} + +/// A new collection object of `class` with `proto`, filled from `args[0]`. +fn construct(interp: &mut Interp, args: &[Value], constructing: bool, name: &str, class: Class, proto: ObjId) -> JsResult { + if !constructing { + return Err(interp.type_error(&format!("{name} must be called with new"))); + } + interp.reserve_heap(OBJECT_BYTES)?; + let o = interp.heap.alloc_object(Object::new(class, Some(proto))); + let (adder, pairs) = match name { + "Map" | "WeakMap" => ("set", true), + _ => ("add", false), + }; + fill(interp, o, &arg(args, 0), adder, pairs)?; + Ok(Value::Object(o)) +} + +fn map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.map_proto; + construct(interp, args, constructing, "Map", Class::Map(Box::default()), proto) +} + +fn set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.set_proto; + construct(interp, args, constructing, "Set", Class::Set(Box::default()), proto) +} + +fn weak_map_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_map_proto; + construct(interp, args, constructing, "WeakMap", Class::WeakMap(Box::default()), proto) +} + +fn weak_set_ctor(interp: &mut Interp, _: Value, args: &[Value], constructing: bool) -> JsResult { + let proto = interp.intrinsics.es2015.weak_set_proto; + construct(interp, args, constructing, "WeakSet", Class::WeakSet(Box::default()), proto) +} + +// ---- Map and Set ---- + +/// The Map (or with `set`, the Set) a method was called on. +fn this_coll(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::Map(_), false) | (Class::Set(_), true)) + { + return Ok(*o); + } + let name = if set { "Set" } else { "Map" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn coll(interp: &Interp, o: ObjId) -> JsResult<&Coll> { + match &interp.object(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +fn coll_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut Coll> { + match &mut interp.object_mut(o)?.class { + Class::Map(c) | Class::Set(c) => Ok(c), + _ => Err(Abrupt::Internal("not a Map or a Set".into())), + } +} + +/// Adds or replaces the entry of `k`, reserving the heap for a new one first. +fn coll_put(interp: &mut Interp, o: ObjId, k: Value, v: Value) -> JsResult<()> { + let ck = coll_key(interp, &k)?; + if !coll(interp, o)?.has(&ck) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(COLL_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(COLL_ENTRY_BYTES); + } + coll_mut(interp, o)?.set(ck, stored_key(k), v); + Ok(()) +} + +fn map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "get")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(coll(interp, o)?.get(&k).cloned().unwrap_or(Value::Undefined)) +} + +fn map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, false, "set")?; + coll_put(interp, o, arg(args, 0), arg(args, 1))?; + Ok(this) +} + +fn has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "has")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll(interp, o)?.has(&k))) +} + +fn delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "delete")?; + let k = coll_key(interp, &arg(args, 0))?; + Ok(Value::Bool(coll_mut(interp, o)?.delete(&k))) +} + +fn clear(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "clear")?; + let slots = coll(interp, o)?.slots(); + // Clearing visits every position, and each takes a unit of fuel. + for _ in 0..slots { + interp.use_fuel()?; + } + coll_mut(interp, o)?.clear(); + Ok(Value::Undefined) +} + +fn size(interp: &mut Interp, this: &Value, set: bool) -> JsResult { + let o = this_coll(interp, this, set, "size")?; + #[allow(clippy::cast_precision_loss)] + Ok(Value::Number(coll(interp, o)?.len() as f64)) +} + +fn map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, false) +} + +fn map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, false) +} + +fn map_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, false) +} + +fn map_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, false) +} + +fn set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_coll(interp, &this, true, "add")?; + coll_put(interp, o, arg(args, 0), Value::Undefined)?; + Ok(this) +} + +fn set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + has(interp, &this, args, true) +} + +fn set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + delete(interp, &this, args, true) +} + +fn set_clear(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + clear(interp, &this, true) +} + +fn set_size(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + size(interp, &this, true) +} + +/// `forEach` (sections 23.1.3.5 and 23.2.3.6): calls `f` with each entry's value, its key (for a +/// Set, the value again) and the collection, in order, visiting entries added while it runs. The +/// position is kept in an iterator object, so a collection that removes holes moves it. +fn for_each(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_coll(interp, this, set, "forEach")?; + let f = arg(args, 0); + require_callable(interp, &f, "the callback")?; + let this_arg = arg(args, 1); + let source = if set { IterSource::Set } else { IterSource::Map }; + let it = new_iter(interp, o, source, IterKind::Entries, None)?; + interp.rooted(&[Value::Object(it), f.clone(), this_arg.clone()], |interp| { + while let Some((k, v)) = advance(interp, it)? { + let v = if set { k.clone() } else { v }; + interp.call(&f, &this_arg, &[v, k, Value::Object(o)])?; + } + Ok(Value::Undefined) + }) +} + +fn map_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, false) +} + +fn set_for_each(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + for_each(interp, &this, args, true) +} + +// ---- iterators ---- + +/// A new iterator over `target`, with `proto` (by default the prototype for `source`). +pub(crate) fn new_iter(interp: &mut Interp, target: ObjId, source: IterSource, kind: IterKind, proto: Option) -> JsResult { + interp.rooted(&[Value::Object(target)], |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; + let proto = proto.unwrap_or(match source { + IterSource::Map => interp.intrinsics.es2015.map_iter_proto, + IterSource::Set => interp.intrinsics.es2015.set_iter_proto, + IterSource::Array => interp.intrinsics.es2015.array_iter_proto, + }); + let state = IterState { source, kind, target: Some(target), pos: 0 }; + let it = interp.heap.alloc_object(Object::new(Class::Iter(Box::new(state)), Some(proto))); + interp.heap.bytes = interp.heap.bytes.saturating_add(VIEW_BYTES); + Ok(it) +} + +/// The next entry of a Map or Set iterator, or `None` when it has finished. Each position +/// passed takes a unit of fuel. +fn advance(interp: &mut Interp, it: ObjId) -> JsResult> { + loop { + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (Some(target), pos) = (state.target, state.pos) else { return Ok(None) }; + let c = coll(interp, target)?; + let found = (pos < c.slots()).then(|| c.entry(pos).cloned()); + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + match found { + None => { + state.target = None; + return Ok(None); + } + Some(entry) => { + state.pos = pos + 1; + if let Some(entry) = entry { + return Ok(Some(entry)); + } + } + } + } +} + +/// An iterator result object `{ value, done }` (section 7.4.7). +pub(crate) fn iter_result(interp: &mut Interp, value: Value, done: bool) -> JsResult { + interp.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(OBJECT_BYTES + 2 * (PROP_BYTES + string_bytes(5))))?; + let o = interp.new_object(); + interp.define(o, key("value"), Prop::Data { value, flags: OPEN })?; + interp.define(o, key("done"), Prop::Data { value: Value::Bool(done), flags: OPEN })?; + Ok(Value::Object(o)) +} + +/// A new array `[a, b]`. +pub(crate) fn pair(interp: &mut Interp, a: Value, b: Value) -> JsResult { + interp.rooted(&[a.clone(), b.clone()], |interp| { + let arr = new_array(interp, 0)?; + interp.rooted(&[Value::Object(arr)], |interp| { + create_at(interp, arr, 0.0, a.clone())?; + create_at(interp, arr, 1.0, b.clone())?; + Ok(Value::Object(arr)) + }) + }) +} + +/// The iterator a `next` method was called on, when it goes through `source`. +fn this_iter(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult<(ObjId, IterKind)> { + if let Value::Object(o) = this + && let Some(Class::Iter(state)) = interp.heap.object(*o).map(|o| &o.class) + && state.source == source + { + return Ok((*o, state.kind)); + } + Err(interp.type_error(&format!("{name} Iterator.prototype.next was called on a value that is not a {name} Iterator"))) +} + +fn coll_next(interp: &mut Interp, this: &Value, source: IterSource, name: &str) -> JsResult { + let (it, kind) = this_iter(interp, this, source, name)?; + let Some((k, v)) = advance(interp, it)? else { return iter_result(interp, Value::Undefined, true) }; + let value = match (kind, source) { + (IterKind::Keys, _) | (IterKind::Values, IterSource::Set) => k, + (IterKind::Values, _) => v, + (IterKind::Entries, IterSource::Set) => pair(interp, k.clone(), k)?, + (IterKind::Entries, _) => pair(interp, k, v)?, + }; + iter_result(interp, value, false) +} + +fn map_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Map, "Map") +} + +fn set_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + coll_next(interp, &this, IterSource::Set, "Set") +} + +/// `%ArrayIteratorPrototype%.next` (section 22.1.5.2.1) for the iterators of typed arrays. +fn array_iterator_next(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (it, kind) = this_iter(interp, &this, IterSource::Array, "Array")?; + interp.use_fuel()?; + let Class::Iter(state) = &interp.object(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let (target, pos) = (state.target, state.pos); + let element = match target { + Some(t) => match &interp.object(t)?.class { + Class::TypedArray(view) => super::binary::element(interp, view, pos as f64), + _ => None, + }, + None => None, + }; + let Class::Iter(state) = &mut interp.object_mut(it)?.class else { return Err(Abrupt::Internal("not an iterator".into())) }; + let Some(element) = element else { + state.target = None; + return iter_result(interp, Value::Undefined, true); + }; + state.pos = pos + 1; + #[allow(clippy::cast_precision_loss)] + let index = Value::Number(pos as f64); + let value = match kind { + IterKind::Keys => index, + IterKind::Values => Value::Number(element), + IterKind::Entries => pair(interp, index, Value::Number(element))?, + }; + iter_result(interp, value, false) +} + +fn iter_method(interp: &mut Interp, this: &Value, set: bool, kind: IterKind, name: &str) -> JsResult { + let o = this_coll(interp, this, set, name)?; + let source = if set { IterSource::Set } else { IterSource::Map }; + new_iter(interp, o, source, kind, None).map(Value::Object) +} + +fn map_keys(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Keys, "keys") +} + +fn map_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Values, "values") +} + +fn map_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, false, IterKind::Entries, "entries") +} + +fn set_values(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Values, "values") +} + +fn set_entries(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + iter_method(interp, &this, true, IterKind::Entries, "entries") +} + +// ---- WeakMap and WeakSet ---- + +fn this_weak(interp: &mut Interp, this: &Value, set: bool, method: &str) -> JsResult { + if let Value::Object(o) = this + && let Some(obj) = interp.heap.object(*o) + && matches!((&obj.class, set), (Class::WeakMap(_), false) | (Class::WeakSet(_), true)) + { + return Ok(*o); + } + let name = if set { "WeakSet" } else { "WeakMap" }; + Err(interp.type_error(&format!("{name}.prototype.{method} was called on a value that is not a {name}"))) +} + +fn weak(interp: &Interp, o: ObjId) -> JsResult<&WeakColl> { + match &interp.object(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +fn weak_mut(interp: &mut Interp, o: ObjId) -> JsResult<&mut WeakColl> { + match &mut interp.object_mut(o)?.class { + Class::WeakMap(w) | Class::WeakSet(w) => Ok(w), + _ => Err(Abrupt::Internal("not a WeakMap or a WeakSet".into())), + } +} + +/// Adds or replaces the entry of the object `k`; a key that is not an object is a `TypeError`. +fn weak_put(interp: &mut Interp, o: ObjId, k: &Value, v: Value, set: bool) -> JsResult<()> { + let Value::Object(key_obj) = k else { + let what = if set { "a WeakSet value" } else { "a WeakMap key" }; + return Err(interp.type_error(&format!("{what} must be an object"))); + }; + if !weak(interp, o)?.entries.contains_key(&key_obj.0) { + interp.rooted(&[Value::Object(o), k.clone(), v.clone()], |i| i.reserve_heap(WEAK_ENTRY_BYTES))?; + interp.heap.bytes = interp.heap.bytes.saturating_add(WEAK_ENTRY_BYTES); + } + weak_mut(interp, o)?.entries.insert(key_obj.0, v); + Ok(()) +} + +fn weak_map_get(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "get")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Undefined) }; + Ok(weak(interp, o)?.entries.get(&k.0).cloned().unwrap_or(Value::Undefined)) +} + +fn weak_map_set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, false, "set")?; + weak_put(interp, o, &arg(args, 0), arg(args, 1), false)?; + Ok(this) +} + +fn weak_has(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "has")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak(interp, o)?.entries.contains_key(&k.0))) +} + +fn weak_delete(interp: &mut Interp, this: &Value, args: &[Value], set: bool) -> JsResult { + let o = this_weak(interp, this, set, "delete")?; + let Value::Object(k) = arg(args, 0) else { return Ok(Value::Bool(false)) }; + Ok(Value::Bool(weak_mut(interp, o)?.entries.remove(&k.0).is_some())) +} + +fn weak_map_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, false) +} + +fn weak_map_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, false) +} + +fn weak_set_add(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = this_weak(interp, &this, true, "add")?; + weak_put(interp, o, &arg(args, 0), Value::Undefined, true)?; + Ok(this) +} + +fn weak_set_has(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_has(interp, &this, args, true) +} + +fn weak_set_delete(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + weak_delete(interp, &this, args, true) +} diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs new file mode 100644 index 0000000000..7c00b29532 --- /dev/null +++ b/crates/js/src/collections_tests.rs @@ -0,0 +1,412 @@ +use crate::heap::{Class, key}; +use crate::value::Value; +use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind}; + +fn es2015() -> Options { + Options { es2015: true, ..Options::default() } +} + +fn realm() -> Realm { + Realm::with_options(es2015(), Limits::default()) +} + +fn run(src: &str) -> JsValue { + match realm().run(src) { + Ok(v) => v, + Err(e) => panic!("{src}\n{e:?}"), + } +} + +fn truth(src: &str) { + assert_eq!(run(src), JsValue::Bool(true), "{src}"); +} + +fn string(src: &str) -> String { + match run(src) { + JsValue::String(s) => s, + other => panic!("{src}: {other:?}"), + } +} + +/// The run throws an error whose message starts with `name`. +fn throws(src: &str, name: &str) { + match realm().run(src) { + Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"), + other => panic!("{src}: {other:?}"), + } +} + +fn limit(limits: &Limits, src: &str) -> LimitKind { + match Realm::with_options(es2015(), limits.clone()).run(src) { + Err(RunError { kind: RunErrorKind::Limit(k), .. }) => k, + other => panic!("{src}: {other:?}"), + } +} + +/// The object a global variable holds. +fn global_object(realm: &mut Realm, name: &str) -> crate::heap::ObjId { + let interp = realm.interp(); + let global = interp.global; + match interp.heap.object(global).and_then(|g| g.props.get(&key(name))) { + Some(crate::heap::Prop::Data { value: Value::Object(o), .. }) => *o, + _ => panic!("{name} is not an object"), + } +} + +// ---- realms ---- + +#[test] +fn realms_without_the_option_keep_the_es5_globals() { + for options in [Options::default(), Options { e4x: true, ..Options::default() }] { + let mut realm = Realm::with_options(options, Limits::default()); + let names = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array \ + Uint32Array Float32Array Float64Array"; + for name in names.split_whitespace() { + assert_eq!(realm.run(&format!("typeof {name}")).unwrap(), JsValue::String("undefined".into()), "{name}"); + } + } + truth("typeof Map === 'function' && typeof Float64Array === 'function' && typeof TypedArray === 'undefined'"); +} + +// ---- Map and Set ---- + +#[test] +fn keys_compare_with_same_value_zero() { + truth("var m = new Map(); m.set(NaN, 1); m.get(NaN) === 1 && m.has(0 / 0) && m.size === 1"); + truth("var m = new Map(); m.set(-0, 'a'); m.get(0) === 'a' && m.has(-0) && 1 / m.keys().next().value === Infinity"); + truth("var s = new Set([0, -0, NaN, NaN]); s.size === 2 && 1 / s.values().next().value === Infinity"); + truth("var m = new Map(); m.set('1', 'string').set(1, 'number'); m.size === 2 && m.get('1') === 'string' && m.get(1) === 'number'"); + truth("var a = {}, b = {}; var m = new Map([[a, 1], [b, 2]]); m.get(a) === 1 && m.get(b) === 2 && m.get({}) === undefined"); + truth("var m = new Map(); m.set('ab' + 'c', 1); m.get('abc') === 1"); +} + +#[test] +fn entries_keep_the_order_they_were_added_in() { + assert_eq!( + string( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); m.set('a', 9); m.delete('b'); m.set('b', 4); \ + var out = []; m.forEach(function (v, k, map) { out.push(k + v + (map === m)); }); out.join()" + ), + "a9true,c3true,b4true" + ); + assert_eq!(string("var s = new Set(['x', 'y']); var out = []; s.forEach(function (v, k) { out.push(v + k); }); out.join()"), "xx,yy"); +} + +#[test] +fn for_each_skips_deleted_entries_and_visits_added_ones() { + assert_eq!( + string( + "var m = new Map([[1, 'a'], [2, 'b'], [3, 'c']]); var out = []; \ + m.forEach(function (v, k) { out.push(v); if (k === 1) { m.delete(2); m.set(4, 'd'); } }); out.join()" + ), + "a,c,d" + ); + assert_eq!( + string("var s = new Set([1, 2]); var out = []; s.forEach(function (v) { out.push(v); if (v < 4) s.add(v + 2); }); out.join()"), + "1,2,3,4,5" + ); + assert_eq!(string("var s = new Set([1, 2, 3]); var out = []; s.forEach(function (v) { out.push(v); s.clear(); }); out.join()"), "1"); +} + +#[test] +fn iterators_step_through_live_entries() { + truth( + "var m = new Map([['a', 1], ['b', 2], ['c', 3]]); var it = m.entries(); var first = it.next(); m.delete('b'); m.set('d', 4); \ + var second = it.next(), third = it.next(), last = it.next(); \ + first.value.join() === 'a,1' && !first.done && second.value.join() === 'c,3' && third.value.join() === 'd,4' && \ + last.done && last.value === undefined && it.next().done", + ); + truth("var s = new Set(['p']); var e = s.entries().next().value; e[0] === 'p' && e[1] === 'p' && s.keys === s.values"); + truth("Object.prototype.toString.call(new Map().keys()) === '[object Map Iterator]'"); + throws("var it = new Map().keys(); it.next.call(new Set().values());", "TypeError"); +} + +#[test] +fn constructors_read_arrays_strings_and_array_likes() { + truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'"); + truth("new Set('ab\u{1F600}b').size === 3"); + truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2"); + truth("new Map(null).size === 0 && new Set(undefined).size === 0"); + truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'"); + throws("Map()", "TypeError"); + throws("Set([])", "TypeError"); + throws("new Map([1])", "TypeError"); + throws("new Set(5)", "TypeError"); + throws("new Map({})", "TypeError"); + throws("new WeakSet({})", "TypeError"); + truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3"); + // `from` reads each element of an array-like source just before mapping it (section 22.2.2.1). + truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'"); + truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'"); + truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'"); + throws("Map.prototype.get.call({}, 1)", "TypeError"); + throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError"); + // The constructor adds through the prototype's method, as section 23.1.1.1 says. + truth( + "var calls = 0; var set = Map.prototype.set; Map.prototype.set = function (k, v) { calls++; return set.call(this, k, v); }; \ + new Map([[1, 1], [2, 2]]); Map.prototype.set = set; calls === 2", + ); + truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'"); +} + +// ---- WeakMap and WeakSet ---- + +#[test] +fn weak_collections_take_object_keys_only() { + truth("var k = {}; var w = new WeakMap([[k, 1]]); w.get(k) === 1 && w.has(k) && w.delete(k) && !w.has(k)"); + truth("var w = new WeakMap(); w.get(1) === undefined && !w.has('a') && !w.delete(null)"); + truth("var s = new WeakSet(); var o = {}; s.add(o) === s && s.has(o) && !s.has(1) && !s.delete(1)"); + throws("new WeakMap().set(1, 2)", "TypeError"); + throws("new WeakSet().add('x')", "TypeError"); + throws("new WeakMap([[1, 2]])", "TypeError"); + truth("new WeakMap().size === undefined && typeof WeakMap.prototype.forEach === 'undefined'"); +} + +#[test] +fn a_weak_map_entry_does_not_keep_its_key_alive() { + let mut realm = realm(); + realm + .run( + "var wm = new WeakMap(), ws = new WeakSet(), kept = {}; + (function () { for (var i = 0; i < 50; i++) { var k = {}; wm.set(k, {back: k}); ws.add(k); } })(); + wm.set(kept, {back: kept}); ws.add(kept);", + ) + .unwrap(); + let wm = global_object(&mut realm, "wm"); + let ws = global_object(&mut realm, "ws"); + let before = realm.interp().heap.live_cells(); + realm.interp().collect_garbage(); + let after = realm.interp().heap.live_cells(); + let count = |realm: &mut Realm, o| match realm.interp().heap.object(o).map(|o| &o.class) { + Some(Class::WeakMap(w) | Class::WeakSet(w)) => w.entries.len(), + _ => panic!("not a weak collection"), + }; + assert_eq!(count(&mut realm, wm), 1); + assert_eq!(count(&mut realm, ws), 1); + // Each dropped key and its value were freed. + assert!(before - after >= 100, "{before} -> {after}"); + assert_eq!(realm.run("wm.get(kept).back === kept && ws.has(kept)").unwrap(), JsValue::Bool(true)); +} + +#[test] +fn a_weak_map_value_reachable_through_another_key_is_kept() { + let mut realm = realm(); + realm.run("var wm = new WeakMap(), a = {}; (function () { var b = {}; wm.set(a, b); wm.set(b, {n: 7}); })();").unwrap(); + realm.interp().collect_garbage(); + assert_eq!(realm.run("wm.get(wm.get(a)).n").unwrap(), JsValue::Number(7.0)); +} + +#[test] +fn weak_maps_of_dropped_keys_stay_within_the_heap() { + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let mut realm = Realm::with_options(es2015(), limits); + let r = realm.run("var wm = new WeakMap(); for (var i = 0; i < 100000; i++) wm.set({}, i); 'done'"); + assert_eq!(r.unwrap(), JsValue::String("done".into())); + assert!(realm.interp().heap.collections > 0); +} + +#[test] +fn collections_of_millions_end_at_the_limits() { + let heap = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap); + assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap); + let fuel = Limits { fuel: 100_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel); + let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });"; + assert_eq!(limit(&fuel, m), LimitKind::Fuel); +} + +#[test] +fn a_collection_removes_holes_and_moves_live_iterators() { + let mut realm = realm(); + realm + .run( + "var m = new Map(); for (var i = 0; i < 100; i++) m.set(i, i * 2); + var it = m.values(); it.next(); it.next(); + for (var j = 0; j < 90; j++) m.delete(j);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => assert_eq!((c.len(), c.slots()), (10, 10)), + _ => panic!("not a Map"), + } + let rest = realm.run("var out = []; for (var r = it.next(); !r.done; r = it.next()) out.push(r.value); out.join()").unwrap(); + assert_eq!(rest, JsValue::String("180,182,184,186,188,190,192,194,196,198".into())); +} + +// ---- ArrayBuffer ---- + +#[test] +fn array_buffers_are_zeroed_and_sliced() { + truth("var b = new ArrayBuffer(8); b.byteLength === 8 && new Uint8Array(b)[7] === 0"); + truth("var u = new Uint8Array([1, 2, 3, 4]); var s = u.buffer.slice(1, -1); s.byteLength === 2 && new Uint8Array(s).join() === '2,3'"); + truth("ArrayBuffer.isView(new DataView(new ArrayBuffer(1))) && ArrayBuffer.isView(new Int8Array(1)) && !ArrayBuffer.isView(new ArrayBuffer(1))"); + truth("new ArrayBuffer().byteLength === 0 && new ArrayBuffer(2.9).byteLength === 2"); + throws("ArrayBuffer(1)", "TypeError"); + throws("new ArrayBuffer(-1)", "RangeError"); +} + +#[test] +fn a_huge_array_buffer_is_refused_before_it_is_allocated() { + throws("new ArrayBuffer(1e15)", "RangeError"); + throws("new ArrayBuffer(Math.pow(2, 53))", "RangeError"); + throws("new Float64Array(Math.pow(2, 40))", "RangeError"); + truth("var caught; try { new Uint8Array(1e12); } catch (e) { caught = e instanceof RangeError; } caught"); + // Larger than the realm's heap limit: a catchable RangeError, not an allocation. + let mut small = Realm::with_options(es2015(), Limits { heap_bytes: 8 << 20, ..Limits::default() }); + assert_eq!(small.run("try { new ArrayBuffer(16 << 20); 'made' } catch (e) { e.name }").unwrap(), JsValue::String("RangeError".into())); + // Within the limit but not within what is left of it: the heap limit. + assert_eq!( + limit(&Limits { heap_bytes: 8 << 20, ..Limits::default() }, "var keep = []; for (;;) keep.push(new ArrayBuffer(1 << 20));"), + LimitKind::Heap + ); +} + +// ---- DataView ---- + +#[test] +fn data_views_read_and_write_both_byte_orders() { + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234); v.getUint8(0) === 0x12 && v.getUint8(1) === 0x34"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setUint16(0, 0x1234, true); v.getUint8(0) === 0x34 && v.getUint16(0, true) === 0x1234"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt32(0, -2); v.getInt32(0) === -2 && v.getUint32(0) === 4294967294"); + truth("var v = new DataView(new ArrayBuffer(8)); v.setFloat64(0, Math.PI); v.getFloat64(0) === Math.PI && v.getUint8(0) === 0x40"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setFloat32(0, 1.5, true); v.getFloat32(0, true) === 1.5 && v.getUint8(3) === 0x3f"); + truth("var v = new DataView(new ArrayBuffer(4)); v.setInt8(0, 200); v.getInt8(0) === -56 && v.getUint8(0) === 200"); + truth("var b = new ArrayBuffer(8); var v = new DataView(b, 2, 4); v.byteOffset === 2 && v.byteLength === 4 && v.buffer === b"); + throws("new DataView(new ArrayBuffer(4)).getUint32(1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4)).getInt8(-1)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 5)", "RangeError"); + throws("new DataView(new ArrayBuffer(4), 2, 3)", "RangeError"); + throws("new DataView({})", "TypeError"); + throws("DataView(new ArrayBuffer(1))", "TypeError"); +} + +// ---- typed arrays ---- + +#[test] +fn uint8_clamped_rounds_half_to_even() { + assert_eq!(string("new Uint8ClampedArray([300, -5, 1.5, 2.5, 0.5, NaN, 254.5, 254.6, Infinity]).join()"), "255,0,2,2,0,0,254,255,255"); + assert_eq!(string("var u = new Uint8ClampedArray(1); u[0] = 3.5; u[0] + ',' + new Uint8Array([300])[0]"), "4,44"); +} + +#[test] +fn element_types_convert_their_values() { + assert_eq!(string("new Int8Array([127, 128, -129, 1.9]).join()"), "127,-128,127,1"); + assert_eq!(string("new Uint16Array([-1, 65536]).join()"), "65535,0"); + assert_eq!(string("new Int32Array([4294967295]).join()"), "-1"); + assert_eq!(string("new Uint32Array([-1]).join()"), "4294967295"); + assert_eq!(string("new Float32Array([0.1])[0].toFixed(8)"), "0.10000000"); + assert_eq!(string("new Float64Array([0.1, NaN]).join()"), "0.1,NaN"); + truth("Int16Array.BYTES_PER_ELEMENT === 2 && new Float64Array(1).BYTES_PER_ELEMENT === 8"); + truth("Object.prototype.toString.call(new Uint8Array(1)) === '[object Uint8Array]'"); +} + +#[test] +fn views_share_their_buffer_little_endian() { + truth("var b = new ArrayBuffer(8); var u8 = new Uint8Array(b), u32 = new Uint32Array(b); u32[0] = 0x01020304; u8[0] === 4 && u8[3] === 1"); + truth("var a = new Uint8Array([1, 2, 3, 4]); var s = a.subarray(1, 3); s[0] = 9; a[1] === 9 && s.length === 2 && s.byteOffset === 1"); + truth("var b = new ArrayBuffer(8); var a = new Int16Array(b, 2, 2); a.length === 2 && a.byteOffset === 2 && a.byteLength === 4"); + throws("new Int32Array(new ArrayBuffer(8), 2)", "RangeError"); + throws("new Int32Array(new ArrayBuffer(6))", "RangeError"); + throws("new Int16Array(new ArrayBuffer(8), 4, 4)", "RangeError"); +} + +#[test] +fn numeric_names_are_elements_or_nothing() { + truth("var a = new Int8Array(2); a[5] = 1; a[5] === undefined && !('5' in a) && Object.keys(a).join() === '0,1'"); + truth( + "var a = new Int8Array(2); a['-0'] = 1; a[1.5] = 1; a['-0'] === undefined && a[1.5] === undefined && Object.getOwnPropertyNames(a).length === 2", + ); + truth("Int8Array.prototype[0] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[0]; r"); + truth("var a = new Int8Array(1); a.foo = 1; a['01'] = 2; a.foo === 1 && a['01'] === 2"); + // The value is converted before the index is checked (section 9.4.5.9), so an ignored write still converts it. + truth( + "var n = 0; var a = new Int8Array(1); a[5] = {valueOf: function () { n++; return 1; }}; a['-0'] = {valueOf: function () { n++; }}; n === 2", + ); + truth("var a = new Int8Array([200]); a[0] === -56 && delete a[1] && !delete a[0]"); + throws("'use strict'; var a = new Int8Array(1); delete a[0];", "TypeError"); + // An out-of-range write is ignored without an error in strict mode too, as later editions define [[Set]]. + truth("'use strict'; var a = new Uint8Array(1); a[2] = 7; a['-1'] = 7; a[0.5] = 7; a.length === 1 && a[2] === undefined"); + truth("var d = Object.getOwnPropertyDescriptor(new Uint8Array([7]), '0'); d.value === 7 && d.writable && d.enumerable && d.configurable"); + truth("var a = new Uint8Array(1); Object.defineProperty(a, '0', {value: 5}); a[0] === 5"); + throws("Object.defineProperty(new Uint8Array(1), '0', {value: 5, configurable: false})", "TypeError"); + throws("Object.defineProperty(new Uint8Array(1), '3', {value: 5})", "TypeError"); + throws("Object.freeze(new Uint8Array(1))", "TypeError"); + truth("var keys = []; for (var k in new Uint8Array(3)) keys.push(k); keys.join() === '0,1,2'"); + truth("JSON.stringify(new Uint8Array([1, 2])) === '{\"0\":1,\"1\":2}'"); +} + +#[test] +fn array_methods_visit_every_element_of_a_long_typed_array() { + truth("Array.prototype.join.call(new Uint8Array(5000)).length === 9999"); + truth("var a = new Uint8Array(10000); a[9999] = 1; Array.prototype.indexOf.call(a, 1) === 9999"); + // The element count, not a `length` property defined on the array, bounds the methods. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 0}); var n = 0; \ + a.forEach(function () { n++; }); n === 3 && a.join() === '1,2,3' && a.every(function (v) { return v > 0; }) && !a.every(function (v) { return v > 1; })", + ); + // A generic array method called on the typed array reads its `length` property. + truth( + "var a = new Uint8Array([1, 2, 3]); Object.defineProperty(a, 'length', {value: 1}); \ + Array.prototype.join.call(a) === '1' && a.join() === '1,2,3' && Array.prototype.join.call(new Uint8Array([4, 5])) === '4,5'", + ); +} + +#[test] +fn typed_array_methods() { + assert_eq!(string("new Float64Array([3, NaN, -0, 0, -1, 2]).sort().join()"), "-1,0,0,2,3,NaN"); + truth("var a = new Float64Array([0, -0]).sort(); 1 / a[0] === -Infinity && 1 / a[1] === Infinity"); + assert_eq!(string("new Int8Array([1, 2, 3]).sort(function (a, b) { return b - a; }).join()"), "3,2,1"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).map(function (v) { return v * 100; }).join()"), "100,-56,44,-112"); + assert_eq!(string("new Int8Array([1, 2, 3, 4]).filter(function (v) { return v % 2; }).join()"), "1,3"); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(0, 3), 2); a.join()"), "1,2,1,2,3"); + assert_eq!(string("var a = new Uint8Array(4); a.set([7, '8'], 1); a.join()"), "0,7,8,0"); + throws("new Uint8Array(2).set([1, 2, 3])", "RangeError"); + throws("new Uint8Array(2).set([1], -1)", "RangeError"); + assert_eq!(string("new Uint8Array([1, 2, 3, 4, 5]).copyWithin(0, 3).join()"), "4,5,3,4,5"); + assert_eq!(string("new Uint8Array(4).fill(7, 1, -1).join()"), "0,7,7,0"); + assert_eq!(string("new Int8Array([5, 6, 7]).slice(-2).join()"), "6,7"); + truth("var a = new Int8Array([5, 6, 7]); a.find(function (v) { return v > 5; }) === 6 && a.findIndex(function (v) { return v > 9; }) === -1"); + truth("new Int8Array([1, 2, 1]).indexOf(1, 1) === 2 && new Int8Array([1, 2, 1]).lastIndexOf(2) === 1"); + truth("new Int8Array([1, 2, 3]).reduce(function (s, v) { return s + v; }) === 6 && new Int8Array([1, 2]).reverse().join() === '2,1'"); + truth( + "var it = new Int8Array([4, 5]).entries(); var e = it.next().value; e[0] === 0 && e[1] === 4 && it.next().value[1] === 5 && it.next().done", + ); + truth("new Int8Array([9]).keys().next().value === 0 && new Int8Array([9]).values().next().value === 9"); + truth("Uint8Array.from({length: 2, 0: 1, 1: 2}, function (v, i) { return v * 10 + i; }).join() === '10,21'"); + truth("Int16Array.from('12').join() === '1,2' && Float32Array.of(1, 2.5).join() === '1,2.5'"); + truth("new Int8Array([1, 2]).toString === Array.prototype.toString && String(new Int8Array([1, 2])) === '1,2'"); + truth( + "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", + ); + throws("Object.getPrototypeOf(Int8Array)()", "TypeError"); + throws("Int8Array(1)", "TypeError"); + throws("Object.getPrototypeOf(Int8Array.prototype).fill.call([1], 0)", "TypeError"); + throws("Int8Array.from.call(Object, [1])", "TypeError"); + throws("Int8Array.from.call({}, [1])", "TypeError"); + // The source's length is read before the constructor is checked to be a typed array's. + throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); + truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); + // A copy to the same element type keeps every bit, a signaling NaN's included. + truth( + "var f = new Float32Array(2); new DataView(f.buffer).setUint32(4, 0x7f800001, true); \ + function bits(t) { return new DataView(t.buffer, t.byteOffset).getUint32(4, true); } \ + var g = new Float32Array(3); g.set(f, 1); var h = new Float32Array(2); h.set(f); \ + bits(f.slice()) === 0x7f800001 && bits(new Float32Array(f)) === 0x7f800001 && bits(h) === 0x7f800001 && \ + new DataView(g.buffer).getUint32(8, true) === 0x7f800001", + ); + assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(2), 1); a.join()"), "1,3,4,5,5"); +} + +#[test] +fn typed_array_work_takes_fuel() { + let fuel = Limits { fuel: 50_000, ..Limits::default() }; + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).fill(1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).copyWithin(0, 1)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array(1 << 20).slice()"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new ArrayBuffer(1 << 20).slice(0)"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Uint8Array({length: 1 << 20})"), LimitKind::Fuel); + assert_eq!(limit(&fuel, "new Float64Array(1 << 16).sort(function (a, b) { return a - b; })"), LimitKind::Fuel); +} diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f612b00138..4aed4b9c9b 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,231 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A `Map` (ECMA-262 6.0 section 23.1): its entries in the order they were added. + Map(Box), + /// A `Set` (section 23.2): its values in the order they were added, each with `undefined`. + Set(Box), + /// A `WeakMap` (section 23.3): values keyed by object. An entry does not keep its key + /// reachable, and its value is reachable only while its key is. + WeakMap(Box), + /// A `WeakSet` (section 23.4): objects that it does not keep reachable. + WeakSet(Box), + /// An iterator over a Map, a Set or a typed array (sections 23.1.5, 23.2.5 and 22.1.5). + Iter(Box), + /// An `ArrayBuffer` (section 24.1) and its bytes, which never change length. + ArrayBuffer(Box<[u8]>), + /// A `DataView` (section 24.2): a range of a buffer's bytes. + DataView(Box), + /// A typed array (section 22.2): elements of one type in a range of a buffer's bytes. + TypedArray(Box), +} + +/// A Map or Set key compared with SameValueZero (section 7.2.10): `NaN` equals `NaN`, `-0` +/// equals `+0`, strings compare by their code units and objects by identity. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) enum CollKey { + Undefined, + Null, + Bool(bool), + /// The bits of the number, with every `NaN` as one value and `-0` as `+0`. + Number(u64), + String(Rc<[u16]>), + Object(u32), +} + +impl CollKey { + /// The key of a number. + pub(crate) fn number(n: f64) -> Self { + CollKey::Number(if n.is_nan() { + f64::NAN.to_bits() + } else if n == 0.0 { + 0 + } else { + n.to_bits() + }) + } +} + +/// The entries of a Map or a Set in the order they were added. Deleting an entry leaves a hole, +/// so the position an iterator or a `forEach` loop has reached stays valid; a collection removes +/// the holes of a collection with more holes than entries and moves its live iterators with them. +#[derive(Clone, Default)] +pub(crate) struct Coll { + entries: Vec>, + index: HashMap, +} + +impl Coll { + /// The number of entries. + pub(crate) fn len(&self) -> usize { + self.index.len() + } + + /// The number of positions, holes included. + pub(crate) fn slots(&self) -> usize { + self.entries.len() + } + + pub(crate) fn get(&self, k: &CollKey) -> Option<&Value> { + let i = *self.index.get(k)?; + self.entries.get(i)?.as_ref().map(|(_, v)| v) + } + + pub(crate) fn has(&self, k: &CollKey) -> bool { + self.index.contains_key(k) + } + + /// Sets the value under `k`, keeping its position when it is there already. Returns whether + /// a new entry was added. + pub(crate) fn set(&mut self, k: CollKey, key: Value, value: Value) -> bool { + if let Some(&i) = self.index.get(&k) + && let Some(Some((_, v))) = self.entries.get_mut(i) + { + *v = value; + return false; + } + self.index.insert(k, self.entries.len()); + self.entries.push(Some((key, value))); + true + } + + /// Deletes the entry under `k`; returns whether there was one. + pub(crate) fn delete(&mut self, k: &CollKey) -> bool { + let Some(i) = self.index.remove(k) else { return false }; + if let Some(slot) = self.entries.get_mut(i) { + *slot = None; + } + true + } + + /// Deletes every entry, leaving the positions in place. + pub(crate) fn clear(&mut self) { + self.index.clear(); + self.entries.iter_mut().for_each(|e| *e = None); + } + + /// The entry at position `i`, or `None` for a hole or a position past the end. + pub(crate) fn entry(&self, i: usize) -> Option<&(Value, Value)> { + self.entries.get(i)?.as_ref() + } + + fn values(&self) -> impl Iterator { + self.entries.iter().flatten().flat_map(|(k, v)| [k, v]) + } + + fn should_compact(&self) -> bool { + let holes = self.entries.len() - self.index.len(); + holes > 16 && holes > self.index.len() + } + + /// Removes the holes. Returns, for each old position and the position past the end, the new + /// position of the first entry at or after it. + fn compact(&mut self) -> Vec { + let mut moved = Vec::with_capacity(self.entries.len() + 1); + let mut live = 0usize; + for e in &self.entries { + moved.push(live); + live += usize::from(e.is_some()); + } + moved.push(live); + self.entries.retain(Option::is_some); + for slot in self.index.values_mut() { + *slot = moved.get(*slot).copied().unwrap_or(*slot); + } + moved + } +} + +/// The entries of a WeakMap or a WeakSet, by the index of their key; a WeakSet's values are +/// `undefined`. +#[derive(Clone, Default)] +pub(crate) struct WeakColl { + pub(crate) entries: HashMap, +} + +/// What an iterator object goes through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterSource { + Map, + Set, + /// A typed array, by index. + Array, +} + +/// What each step of an iterator gives: the key, the value or a `[key, value]` array. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum IterKind { + Keys, + Values, + Entries, +} + +/// An iterator's state. `target` is `None` once the iterator has finished. +#[derive(Clone, Debug)] +pub(crate) struct IterState { + pub(crate) source: IterSource, + pub(crate) kind: IterKind, + pub(crate) target: Option, + pub(crate) pos: usize, +} + +/// The element type of a typed array (section 22.2, table 50). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Elem { + Int8, + Uint8, + Uint8Clamped, + Int16, + Uint16, + Int32, + Uint32, + Float32, + Float64, +} + +impl Elem { + pub(crate) const ALL: [Elem; 9] = + [Elem::Int8, Elem::Uint8, Elem::Uint8Clamped, Elem::Int16, Elem::Uint16, Elem::Int32, Elem::Uint32, Elem::Float32, Elem::Float64]; + + /// The bytes of one element. + pub(crate) fn size(self) -> usize { + match self { + Elem::Int8 | Elem::Uint8 | Elem::Uint8Clamped => 1, + Elem::Int16 | Elem::Uint16 => 2, + Elem::Int32 | Elem::Uint32 | Elem::Float32 => 4, + Elem::Float64 => 8, + } + } + + /// The name of the constructor. + pub(crate) fn name(self) -> &'static str { + match self { + Elem::Int8 => "Int8Array", + Elem::Uint8 => "Uint8Array", + Elem::Uint8Clamped => "Uint8ClampedArray", + Elem::Int16 => "Int16Array", + Elem::Uint16 => "Uint16Array", + Elem::Int32 => "Int32Array", + Elem::Uint32 => "Uint32Array", + Elem::Float32 => "Float32Array", + Elem::Float64 => "Float64Array", + } + } + + /// The position of the type in [`Elem::ALL`]. + pub(crate) fn index(self) -> usize { + Elem::ALL.iter().position(|e| *e == self).unwrap_or(0) + } +} + +/// A typed array or a `DataView`: `length` elements of `elem` (bytes, for a `DataView`) starting +/// `offset` bytes into `buffer`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct View { + pub(crate) buffer: ObjId, + pub(crate) offset: usize, + pub(crate) length: usize, + pub(crate) elem: Elem, } /// What an XML value is. @@ -322,6 +547,18 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + Class::Map(_) => "Map", + Class::Set(_) => "Set", + Class::WeakMap(_) => "WeakMap", + Class::WeakSet(_) => "WeakSet", + Class::Iter(state) => match state.source { + IterSource::Map => "Map Iterator", + IterSource::Set => "Set Iterator", + IterSource::Array => "Array Iterator", + }, + Class::ArrayBuffer(_) => "ArrayBuffer", + Class::DataView(_) => "DataView", + Class::TypedArray(view) => view.elem.name(), } } } @@ -397,6 +634,12 @@ pub(crate) const XML_REF_BYTES: usize = 8; pub(crate) const XML_NS_BYTES: usize = 48; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; +/// The estimated bytes of a Map or Set position, with its entry in the hash index. +pub(crate) const COLL_ENTRY_BYTES: usize = 96; +/// The estimated bytes of a WeakMap or WeakSet entry. +pub(crate) const WEAK_ENTRY_BYTES: usize = 64; +/// The estimated bytes of the state of an iterator, a typed array or a `DataView`. +pub(crate) const VIEW_BYTES: usize = 48; pub(crate) fn string_bytes(len: usize) -> usize { 32 + 2 * len @@ -476,11 +719,18 @@ impl Heap { /// Marks everything reachable from `roots` and frees the rest. Afterwards [`Heap::bytes`] is /// the estimated size of what is left, strings reachable from it included. + /// + /// A WeakMap's entry marks its value only once its key is marked by another path, and the + /// entries of WeakMaps and WeakSets whose keys stay unmarked are removed before the sweep, so + /// a value that refers back to its own key does not keep it alive. Values waiting for their + /// key are kept by key, so the marking stays linear in the number of entries. pub(crate) fn collect(&mut self, roots: &Roots<'_>) { let mut marks = vec![false; self.cells.len()]; let mut work: Vec = Vec::new(); let mut strings = StringSizes::default(); let mut live = 0usize; + let mut pending: HashMap> = HashMap::new(); + let mut weak: Vec = Vec::new(); for v in &roots.values { mark_value(v, &mut work, &mut strings); } @@ -495,21 +745,80 @@ impl Heap { continue; } *mark = true; + if let Some(values) = pending.remove(&i) { + for v in &values { + mark_value(v, &mut work, &mut strings); + } + } match self.cells.get(i as usize) { - Some(Cell::Object(o)) => live += trace_object(o, &mut work, &mut strings), + Some(Cell::Object(o)) => { + live += trace_object(o, &mut work, &mut strings); + match &o.class { + Class::WeakMap(w) => { + weak.push(i); + for (k, v) in &w.entries { + if marks.get(*k as usize).copied().unwrap_or(false) { + mark_value(v, &mut work, &mut strings); + } else if matches!(v, Value::Object(_) | Value::String(_)) { + pending.entry(*k).or_default().push(v.clone()); + } + } + } + Class::WeakSet(_) => weak.push(i), + _ => {} + } + } Some(Cell::Env(e)) => live += trace_env(e, &mut work, &mut strings), _ => {} } } + for i in weak { + if let Some(Cell::Object(o)) = self.cells.get_mut(i as usize) + && let Class::WeakMap(w) | Class::WeakSet(w) = &mut o.class + { + w.entries.retain(|k, _| marks.get(*k as usize).copied().unwrap_or(false)); + live += WEAK_ENTRY_BYTES * w.entries.len(); + } + } for (i, (cell, marked)) in self.cells.iter_mut().zip(&marks).enumerate() { if !marked && !matches!(cell, Cell::Free) { *cell = Cell::Free; self.free.push(u32::try_from(i).unwrap_or(u32::MAX)); } } + live = live.saturating_sub(self.compact_collections()); self.bytes = live + strings.bytes; self.collections += 1; } + + /// Removes the holes of the Maps and Sets that have more holes than entries, and moves the + /// positions of their iterators with them. Returns the bytes the holes held. + fn compact_collections(&mut self) -> usize { + let mut moved: HashMap> = HashMap::new(); + let mut freed = 0usize; + for (i, cell) in self.cells.iter_mut().enumerate() { + if let Cell::Object(o) = cell + && let Class::Map(c) | Class::Set(c) = &mut o.class + && c.should_compact() + { + freed += COLL_ENTRY_BYTES * (c.slots() - c.len()); + moved.insert(u32::try_from(i).unwrap_or(u32::MAX), c.compact()); + } + } + if moved.is_empty() { + return 0; + } + for cell in &mut self.cells { + if let Cell::Object(o) = cell + && let Class::Iter(state) = &mut o.class + && state.source != IterSource::Array + && let Some(map) = state.target.and_then(|t| moved.get(&t.0)) + { + state.pos = map.get(state.pos).or(map.last()).copied().unwrap_or(0); + } + } + freed + } } /// What the collector starts from. @@ -680,6 +989,23 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Map(c) | Class::Set(c) => { + for v in c.values() { + mark_value(v, work, strings); + } + extra = COLL_ENTRY_BYTES * c.slots(); + } + // Their entries are marked and counted by the collector's weak pass. + Class::WeakMap(_) | Class::WeakSet(_) => {} + Class::Iter(state) => { + work.extend(state.target.iter().map(|o| o.0)); + extra = VIEW_BYTES; + } + Class::ArrayBuffer(bytes) => extra = bytes.len(), + Class::DataView(view) | Class::TypedArray(view) => { + work.push(view.buffer.0); + extra = VIEW_BYTES; + } _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..b90c354347 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -103,6 +103,8 @@ pub(crate) struct Intrinsics { pub(crate) xml_list_proto: ObjId, pub(crate) namespace_proto: ObjId, pub(crate) qname_proto: ObjId, + /// The ECMAScript 2015 collections and binary data ([`crate::Options::es2015`]). + pub(crate) es2015: crate::builtins::collections::Es2015, } impl Intrinsics { @@ -125,6 +127,7 @@ impl Intrinsics { xml_list_proto: o, namespace_proto: o, qname_proto: o, + es2015: crate::builtins::collections::Es2015::placeholder(), } } @@ -160,6 +163,7 @@ impl Intrinsics { self.qname_proto, ]; v.extend(self.error_protos); + v.extend(self.es2015.all()); v } } @@ -251,6 +255,9 @@ pub(crate) struct Interp { pub(crate) held_bytes: usize, /// Why installing the built-ins failed; a realm with this set runs no script. pub(crate) install_error: Option, + /// The typed array whose element count the next array method reads as its length, set while a + /// `%TypedArray%.prototype` method runs the array method it shares and cleared once it is read. + pub(crate) typed_length: Option, /// `File` and `Folder`, once a host has added them ([`crate::Realm::define_file_classes`]). pub(crate) files: Option, /// The clock and time zone `Date` reads. @@ -517,6 +524,7 @@ impl Interp { join_stack: Vec::new(), held_bytes: 0, install_error: None, + typed_length: None, files: None, date_host: crate::date_builtins::DateHost::default(), held: Rc::default(), @@ -1380,6 +1388,12 @@ impl Interp { return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags })); } } + // A numeric name of a typed array is an element or nothing (section 9.4.5.1). + Class::TypedArray(view) => { + if let Some(n) = crate::builtins::binary::canonical_index(k) { + return Ok(crate::builtins::binary::element(self, view, n).map(|v| Prop::Data { value: Value::Number(v), flags: OPEN })); + } + } _ => {} } Ok(o.props.get(k).cloned()) @@ -1393,6 +1407,10 @@ impl Interp { if let Some(p) = self.get_own_property(o, k)? { return Ok(Some(p)); } + // A typed array's prototypes are not searched for a numeric name (section 9.4.5.4). + if crate::builtins::binary::typed_key(self, o, k).is_some() { + return Ok(None); + } cur = self.object(o)?.proto; steps += 1; if steps > 1_000_000 { @@ -1490,6 +1508,9 @@ impl Interp { } self.define_ordinary(id, k, desc, throw) } + Class::TypedArray(_) if crate::builtins::binary::canonical_index(&k).is_some() => { + crate::builtins::binary::define_element(self, id, &k, desc, throw) + } Class::Arguments(map) => { let mapped = array_index(&k).and_then(|i| map.names.get(i as usize)).and_then(Option::as_ref).cloned(); if !self.define_ordinary(id, k.clone(), desc, false)? { @@ -1642,7 +1663,12 @@ impl Interp { /// list is checked first. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult> { let o = self.object(id)?; - let string_len = if let Class::String(s) = &o.class { s.len() } else { 0 }; + // A typed array's indices come first, as a String object's do (section 9.4.5.6). + let string_len = match &o.class { + Class::String(s) => s.len(), + Class::TypedArray(view) => view.length, + _ => 0, + }; let is_string = matches!(o.class, Class::String(_)); let is_array = matches!(o.class, Class::Array { .. }); let count = o.props.len().saturating_add(string_len).saturating_add(usize::from(is_string || is_array)); @@ -1684,6 +1710,9 @@ impl Interp { /// [[Put]] (section 8.12.5). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { + if let Some(n) = crate::builtins::binary::typed_key(self, id, &k) { + return crate::builtins::binary::set_element(self, id, n, &v); + } match self.get_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -1759,6 +1788,18 @@ impl Interp { /// [[Delete]] (section 8.12.7). pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult { + // A typed array's element cannot be deleted, and a numeric name it has no element for + // is not a property it can hold (section 9.4.5.6 of later editions). + if crate::builtins::binary::typed_key(self, id, k).is_some() { + if self.get_own_property(id, k)?.is_none() { + return Ok(true); + } + if throw { + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot delete property '{key}' of a typed array"))); + } + return Ok(false); + } match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { @@ -2121,8 +2162,12 @@ impl Interp { let mut cur = Some(id); while let Some(o) = cur { let obj = self.object(o)?; - let string_len = if let Class::String(s) = &obj.class { Some(s.len()) } else { None }; - let is_array = matches!(obj.class, Class::Array { .. }); + let string_len = match &obj.class { + Class::String(s) => Some(s.len()), + Class::TypedArray(view) => Some(view.length), + _ => None, + }; + let is_array = matches!(obj.class, Class::Array { .. } | Class::String(_)); if let Some(len) = string_len { self.reserve_heap(index_keys_bytes(len))?; for i in 0..len { @@ -2132,7 +2177,6 @@ impl Interp { out.push(k); } } - seen.insert(key("length")); } if is_array { seen.insert(key("length")); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..34284a6fd9 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -46,6 +46,18 @@ //! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and //! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each //! node. +//! +//! With [`Options::es2015`], the realm also provides these ECMAScript 2015 built-ins +//! (): `Map` and `Set` (sections 23.1 and 23.2), whose +//! keys compare with SameValueZero and keep the order they were added in, with `forEach` visiting +//! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the +//! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine +//! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with +//! a `next` method. Until the language has iterators, the collection constructors and +//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by +//! index. A typed array constructor reads an array or an object with a `length` the same way, and +//! converts a first argument that is not an object to a length. A buffer longer than the heap +//! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated. #![forbid(unsafe_code)] pub mod ast; @@ -100,11 +112,15 @@ pub struct Options { pub max_source_units: usize, /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, + /// Give a realm the ECMAScript 2015 built-ins this engine has: `Map`, `Set`, `WeakMap`, + /// `WeakSet`, `ArrayBuffer`, `DataView` and the typed arrays. Off, a realm has the ES5.1 + /// built-ins only, as ExtendScript scripts expect. + pub es2015: bool, } impl Default for Options { fn default() -> Self { - Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false } + Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false } } } @@ -203,6 +219,8 @@ impl LineTable { #[cfg(test)] mod builtins_tests; #[cfg(test)] +mod collections_tests; +#[cfg(test)] mod extension_tests; #[cfg(test)] mod host_tests; diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 23337128bb..2b273d6359 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -28,6 +28,11 @@ //! `builtins-failures.txt`. The interpreter tests fail when the interpreter panics, when a harness //! or test file cannot be read, or when no ES5 test runs. //! +//! A fifth test runs the tests under the folders [`ES2015_BUILT_INS`] names (`Map`, `Set`, +//! `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView`, `TypedArray` and `TypedArrayConstructors`) in +//! realms with [`Options::es2015`], each test whose feature tags are all in [`ES2015_FEATURES`]; its +//! failures go to `es2015-failures.txt`. It fails when the interpreter panics. +//! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset //! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the @@ -444,7 +449,12 @@ fn runs_strings_as_code(tokens: &[Token]) -> bool { /// Runs one test in a new realm; `Err` describes a failure. fn run_one(script: &str, negative_type: Option<&str>) -> Result<(), String> { - let mut realm = Realm::with_options(Options::default(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + run_in(Options::default(), script, negative_type) +} + +/// Runs one test in a new realm with `options`; `Err` describes a failure. +fn run_in(options: Options, script: &str, negative_type: Option<&str>) -> Result<(), String> { + let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); match (realm.run(script), negative_type) { (Ok(_), None) => Ok(()), (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), @@ -590,6 +600,108 @@ fn run_text_builtins(dir: &Path) { assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); } +/// The directories under `test/built-ins/` that hold the tests of the ECMAScript 2015 collections +/// and binary data, which run in a realm with [`Options::es2015`]. +const ES2015_BUILT_INS: &[&str] = &["Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "DataView", "TypedArray", "TypedArrayConstructors"]; + +/// The names in [`MISSING_BUILTINS`] that a realm with [`Options::es2015`] provides. +const ES2015_BUILTINS: &str = "Map Set WeakMap WeakSet ArrayBuffer DataView Int8Array Uint8Array Float64Array"; + +/// The feature tags a test under [`ES2015_BUILT_INS`] may have and still run: the built-ins +/// themselves and the stable typed array sort. A tag starting `DataView.prototype.` names one of +/// the `DataView` methods. Tests with any other tag (symbols, `Reflect`, classes, resizable or +/// detached buffers, `BigInt` and later additions) are counted as skipped. +const ES2015_FEATURES: &[&str] = &[ + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "TypedArray", + "Int8Array", + "Uint8Array", + "Float64Array", + "stable-typedarray-sort", +]; + +#[test] +fn es2015_collections_and_binary_data_run() { + let Some(dir) = suite_dir() else { + println!("test262 ECMAScript 2015 built-ins: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_es2015_built_ins(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests under the folders [`ES2015_BUILT_INS`] names in realms with +/// [`Options::es2015`], prints each folder's counts and writes the failures to +/// `es2015-failures.txt` beside the suite. +fn run_es2015_built_ins(dir: &Path) { + let missing = missing_builtins(&[TEXT_BUILTINS, ES2015_BUILTINS]); + let mut report = String::new(); + let mut panicked = 0; + for name in ES2015_BUILT_INS { + let root = or_fail(inside(dir, &format!("test/built-ins/{name}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + let counts = run_es2015_tests(dir, &root, &missing); + println!("test262 built-ins/{name} in an ECMAScript 2015 realm: {}.", counts.summary()); + report.push_str(&format!("# built-ins/{name}\n{}\n", counts.failures)); + panicked += counts.panicked; + } + let path = dir.join("es2015-failures.txt"); + if let Err(e) = std::fs::write(&path, &report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 ECMAScript 2015 built-ins failures: {}", path.display()); + assert_eq!(panicked, 0, "the interpreter panicked; see {}", path.display()); +} + +/// Runs the tests under `root` whose feature tags are all in [`ES2015_FEATURES`], as +/// [`run_tests`] runs the ES5 tests, each in a new realm with [`Options::es2015`]. +fn run_es2015_tests(dir: &Path, root: &Path, missing: &HashSet<&str>) -> RunCounts { + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let mut counts = RunCounts::default(); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); + let meta = meta(&source); + if matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")) || meta.flags.iter().any(|f| f == "module") { + continue; + } + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + let known = meta.features.iter().all(|f| ES2015_FEATURES.contains(&f.as_str()) || f.starts_with("DataView.prototype.")); + if !known || meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { + counts.skipped += 1; + continue; + } + counts.tests += 1; + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") }; + let script = if strict { format!("\"use strict\";\n{body}") } else { body }; + let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime")); + match std::panic::catch_unwind(|| run_in(Options { es2015: true, ..Options::default() }, &script, negative_type.as_deref())) { + Ok(Ok(())) => counts.passed += 1, + Ok(Err(why)) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {why}\n")); + } + Err(_) => { + counts.failed += 1; + counts.panicked += 1; + counts.failures.push_str(&format!("{rel} ({mode}): PANIC\n")); + } + } + } + } + counts +} + /// Runs the tests under `root` that have no feature tag and are not module, asynchronous or /// negative parse tests, each in a new realm after the harness. Returns the counts for the tests /// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out). diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..58c4525d84 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -87,8 +87,9 @@ pub(crate) const APP_METHODS: &[&str] = &["executeMenuCommand", "doScript", "loa /// Text an action set written out at run time holds. pub(crate) const ACTION_TEXT: &str = "/actionCount"; -/// Constructors of the language (ECMA-262 3rd edition, section 15) and of E4X (ECMA-357 2nd edition, -/// section 13), and the platform's own: `new` of these is no document-model type. +/// Constructors of the language (ECMA-262 3rd edition, section 15, and the collections and binary +/// data of the 6th edition, sections 22.2 to 24.2) and of E4X (ECMA-357 2nd edition, section 13), and +/// the platform's own: `new` of these is no document-model type. pub(crate) const CONSTRUCTORS: &[&str] = &[ "Object", "Function", @@ -105,6 +106,21 @@ pub(crate) const CONSTRUCTORS: &[&str] = &[ "SyntaxError", "TypeError", "URIError", + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "DataView", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", "Namespace", "QName", "XML", diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b771cc6417..676232545f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1392,6 +1392,17 @@ fn type_names_compared_or_created_are_listed() { assert_eq!(r.needs, [Need::Dom]); } +#[test] +fn collections_and_typed_arrays_are_not_type_names() { + let r = report(concat!( + "var m = new Map(), s = new Set(), wm = new WeakMap(), ws = new WeakSet();\n", + "var b = new ArrayBuffer(8), v = new DataView(b), u = new Uint8Array(b), c = new Uint8ClampedArray(2);\n", + "var i = [new Int8Array(1), new Int16Array(1), new Uint16Array(1), new Int32Array(1), new Uint32Array(1)];\n", + "var f = [new Float32Array(1), new Float64Array(1)];\n", + )); + assert!(r.types.is_empty(), "{:?}", r.types.iter().map(|t| t.name.as_str()).collect::>()); +} + #[test] fn menu_commands_are_counted_with_their_lines() { let r = report(concat!( diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..7204bf97a9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2616,8 +2616,10 @@ https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-act describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and -`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. An ES5.1 script does not +have `Map`, `Set`, `WeakMap`, `WeakSet`, `ArrayBuffer`, `DataView` or the typed arrays; the JavaScript engine's +ECMAScript 2015 mode (`Options::es2015` in `vectorcraft-js`) adds them, as `docs/target-app-parity.md` describes. The +script reaches the app through the global object `vc`, and writes to the Script Console and runs other files through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..32a682ab00 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,6 +1082,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. Until the language has iterators, the collection constructors and `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by index, and a typed array constructor reads an array or an object with a `length` the same way and converts a first argument that is not an object to a length; these rules are VectorCraft's own. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From 99c4a82b3088efaebb181d065f2c2b9d090e99b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:43:40 -0800 Subject: [PATCH 019/160] Tabs: fallback glyphs in tab titles sit on the condensed face's baseline The tab family's copies of the semibold faces took the copy made for egui's empty Proportional family, which has no baseline shift, instead of the one made for the tab family. They now take the tab family's copy. egui's own faces stay under their own names, as in the semibold family: egui skips some of their characters (the Ubuntu logo, two symbols in its emoji face) only under those names. ui_fonts::baseline_copies measured a fallback face without its own FontTweak scale, while egui draws the face and its y_offset_factor at that scale. The shift now uses it, so a scaled fallback (Inter SemiBold at 0.92) sits on the row's baseline. Faces added before this change are at scale 1 and keep their shift. Without the condensed face the tab family is no longer bound, and tabs draw in theme::tab_title_font: the tab family when the context's fonts bind it, otherwise the semibold family as it is. Fonts an embedder adds to the semibold family then reach tab titles too, and an embedder's own definitions that bind only the other families keep working. The condensed face and the lookup of its catalog row move to build/condensed_ui_face.rs, which the crate's tests include. With CRAFT_FONTS_REQUIRED=1, an unreadable catalog, a malformed row for the face or a row whose file can't be embedded is a build error; a checkout without the catalog or the row still gives a warning. A checkout whose catalog names the condensed face without its file is watched through the file's folder inside the checkout, so the build runs again once the file appears. docs/development.md lists FONT_TAB among the families an embedder adds fonts to. ASSETS.md and NOTICE name the face, and the docs/ui-parity.md row says official builds wait for the craft-fonts pin to move. Tests: with the monospace face standing in for the condensed face, and without craft-fonts, one test checks the tab family's x-height, the baseline of a character only the semibold face has, and that the characters egui skips draw in a tab title as in semibold text. Two tab-strip tests check that titles are laid out in the tab family with a stand-in face and in the semibold family without one. The condensed-face test checks the x-height at 200 pt, the shortened-title test also runs in the tab font, the install_fonts test checks the tab family, and ui_fonts' no-craft-fonts test allows the condensed face, which a checkout can give alone. A text-crate test finds the face's row as craft-fonts' catalog has it and rejects malformed rows for it. Two comments use American spelling. --- ASSETS.md | 2 +- NOTICE | 2 + crates/text/build.rs | 52 +++++++----- crates/text/build/condensed_ui_face.rs | 45 ++++++++++ crates/text/src/lib.rs | 3 + crates/ui-egui/src/chrome/tabs.rs | 7 +- crates/ui-egui/src/chrome/tests.rs | 22 ++--- crates/ui-egui/src/i18n/tests.rs | 3 + crates/ui-egui/src/tests/tab_overflow.rs | 79 +++++++++++++++++- crates/ui-egui/src/theme.rs | 101 +++++++++++++++++++---- crates/ui-egui/src/ui_fonts.rs | 26 +++--- crates/ui-egui/tests/install_fonts.rs | 14 +++- docs/development.md | 8 +- docs/ui-parity.md | 2 +- 14 files changed, 299 insertions(+), 67 deletions(-) create mode 100644 crates/text/build/condensed_ui_face.rs diff --git a/ASSETS.md b/ASSETS.md index 2812067e00..b949197d4c 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -24,7 +24,7 @@ Generated-in-code art is original and has no file to list. This covers the defau **Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay. -**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. +**Optional build input: craft-fonts.** Builds made with `CRAFT_FONTS_DIR=` (all official releases) embed the Japanese fonts listed in its [`ATTRIBUTION.md`](https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md): BIZ UDPGothic Regular and Bold, Shippori Mincho Regular and BIZ UDMincho Regular (web builds: BIZ UDPGothic Regular only), all under the SIL Open Font License 1.1. They are not files in this repository; release packages carry each one's `OFL-.txt`. Builds without `CRAFT_FONTS_DIR` embed none of them. Desktop builds with a checkout whose opt-in `fonts/latin-manifest.txt` lists Noto Sans Condensed SemiBold (The Noto Project Authors, SIL Open Font License 1.1, from the [notofonts/latin-greek-cyrillic NotoSans-v2.015 release](https://github.com/notofonts/latin-greek-cyrillic/releases/tag/NotoSans-v2.015)) also embed that face, for document tab titles. | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| diff --git a/NOTICE b/NOTICE index 434cd3e524..99470afd8e 100644 --- a/NOTICE +++ b/NOTICE @@ -45,6 +45,8 @@ fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.m Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest; web builds BIZ UDPGothic Regular only) under the SIL Open Font License 1.1. Their license texts ship with the release packages as OFL-.txt. +Desktop builds with a craft-fonts checkout whose fonts/latin-manifest.txt lists Noto Sans Condensed +SemiBold (Copyright 2022 The Noto Project Authors, SIL Open Font License 1.1) also embed that face. PDF import decodes CJK text with Adobe's CMap resources (https://github.com/adobe-type-tools/cmap-resources), compiled into the app through the hayro-cmap crate under the BSD 3-Clause License: diff --git a/crates/text/build.rs b/crates/text/build.rs index 5979c6557c..2658094965 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -14,12 +14,16 @@ //! out with a warning, never an error, and never costs the desktop its fonts. //! //! On native targets it writes `CONDENSED_UI_FONT`: the condensed face document tab titles draw in -//! (`CONDENSED_UI_FACE`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. A -//! checkout without that row leaves it `None` with a warning, never an error. +//! (`build/condensed_ui_face.rs`), the one row it reads from the opt-in `fonts/latin-manifest.txt`. +//! A checkout without the catalog or that row leaves it `None` with a warning, never an error; an +//! unreadable catalog, a malformed row or a file that can't be embedded is an error with +//! `CRAFT_FONTS_REQUIRED=1`. use std::fmt::Write as _; use std::path::{Path, PathBuf}; +#[path = "build/condensed_ui_face.rs"] +mod condensed_ui_face; #[path = "build/web_fonts.rs"] mod web_fonts; @@ -28,6 +32,7 @@ fn main() { println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); println!("cargo::rerun-if-changed=web-fonts.txt"); println!("cargo::rerun-if-changed=build/web_fonts.rs"); + println!("cargo::rerun-if-changed=build/condensed_ui_face.rs"); let required = std::env::var_os("CRAFT_FONTS_REQUIRED").is_some(); let (mut fonts, mut web, mut condensed) = (String::new(), String::new(), String::from("None")); if let Some(dir) = std::env::var_os("CRAFT_FONTS_DIR").filter(|d| !d.is_empty()).map(PathBuf::from) { @@ -55,7 +60,8 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a != "wasm32") { match condensed_ui_font(&dir) { Ok(entry) => condensed = format!("Some({entry})"), - Err(e) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), + Err((e, true)) if required => println!("cargo::error=CRAFT_FONTS_DIR={}: {e}", dir.display()), + Err((e, _)) => println!("cargo::warning=document tabs draw in the interface face: CRAFT_FONTS_DIR={}: {e}", dir.display()), } } } @@ -108,7 +114,7 @@ fn craft_fonts(dir: &Path) -> Result { Ok(out) } -/// The `CraftFont { .. }` initialiser of one manifest row of the checkout `dir` (canonical `root`). +/// The `CraftFont { .. }` initializer of one manifest row of the checkout `dir` (canonical `root`). fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, scripts: &str) -> Result { let path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; // The manifest is supplier data: embed only regular files inside the checkout. @@ -124,29 +130,33 @@ fn craft_font(dir: &Path, root: &Path, family: &str, style: &str, file: &str, sc )) } -/// The condensed craft-fonts face (family, style) document tab titles draw in, from the opt-in -/// Latin catalog. -const CONDENSED_UI_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); - -/// The `CraftFont { .. }` initialiser of [`CONDENSED_UI_FACE`]'s row in `fonts/latin-manifest.txt`. -fn condensed_ui_font(dir: &Path) -> Result { +/// The `CraftFont { .. }` initializer of the condensed face's row in `fonts/latin-manifest.txt` +/// (`build/condensed_ui_face.rs`). The error says whether the checkout is broken: one without the +/// catalog or the row is an older craft-fonts, and an unreadable catalog, a malformed row or a row +/// whose file can't be embedded is broken. +fn condensed_ui_font(dir: &Path) -> Result { + let (family, style) = condensed_ui_face::FACE; let manifest = dir.join("fonts/latin-manifest.txt"); // A checkout without the catalog is watched through its folder, so the build runs again once // the catalog appears. let watched = if manifest.is_file() { manifest.clone() } else { dir.join("fonts") }; println!("cargo::rerun-if-changed={}", watched.display()); - let text = std::fs::read_to_string(&manifest).map_err(|e| format!("{}: {e} (an older craft-fonts?)", manifest.display()))?; - let root = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?; - let row = text - .lines() - .map(str::trim) - .filter(|l| !l.is_empty() && !l.starts_with('#')) - .map(|l| l.split(" | ").map(str::trim).collect::>()) - .find(|f| f.first() == Some(&CONDENSED_UI_FACE.0) && f.get(1) == Some(&CONDENSED_UI_FACE.1)); - let Some([family, style, file, scripts, ..]) = row.as_deref() else { - return Err(format!("{} {} not in {} (an older craft-fonts?)", CONDENSED_UI_FACE.0, CONDENSED_UI_FACE.1, manifest.display())); + let text = std::fs::read_to_string(&manifest).map_err(|e| { + let older = e.kind() == std::io::ErrorKind::NotFound; + (format!("{}: {e}{}", manifest.display(), if older { " (an older craft-fonts?)" } else { "" }), !older) + })?; + let row = condensed_ui_face::row(&text).map_err(|e| (format!("{}: {e}", manifest.display()), true))?; + let Some((file, scripts)) = row else { + return Err((format!("{family} {style} not in {} (an older craft-fonts?)", manifest.display()), false)); }; - craft_font(dir, &root, family, style, file, scripts) + let root = dir.canonicalize().map_err(|e| (format!("{}: {e}", dir.display()), true))?; + // A row whose file is missing is watched through the file's folder inside the checkout (or the + // checkout's `fonts/`), so the build runs again once the file appears. + craft_font(dir, &root, family, style, file, scripts).map_err(|e| { + let inside = dir.join(file).parent().and_then(|p| p.canonicalize().ok()).filter(|p| p.starts_with(&root) && p.is_dir()); + println!("cargo::rerun-if-changed={}", inside.unwrap_or_else(|| dir.join("fonts")).display()); + (e, true) + }) } /// One `WebFont { .. }` initialiser per `web-fonts.txt` line, from its craft-fonts manifest row, and diff --git a/crates/text/build/condensed_ui_face.rs b/crates/text/build/condensed_ui_face.rs new file mode 100644 index 0000000000..c70e2cb2a4 --- /dev/null +++ b/crates/text/build/condensed_ui_face.rs @@ -0,0 +1,45 @@ +//! The condensed craft-fonts face document tab titles draw in, and its row in the checkout's opt-in +//! Latin catalog (`fonts/latin-manifest.txt`). Shared by `build.rs` and the crate's tests +//! (`#[path]`-included by both, so it has no dependencies). + +/// The condensed face's family and style. +pub const FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold"); + +/// The file and scripts fields of [`FACE`]'s row in the catalog `text`: `None` when no row names +/// the face, and an error when the row that names it does not have the catalog's 8 fields or leaves +/// the file or scripts empty. +pub fn row(text: &str) -> Result, String> { + for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { + let fields: Vec<&str> = line.split(" | ").map(str::trim).collect(); + match fields.as_slice() { + [family, style, file, scripts, _, _, _, _] if (*family, *style) == FACE && !file.is_empty() && !scripts.is_empty() => { + return Ok(Some((*file, *scripts))); + } + [family, style, ..] if (*family, *style) == FACE => return Err(format!("malformed manifest line: {line}")), + _ => {} + } + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The face's row as storytold/craft-fonts#72 adds it to the catalog is found, rows for other + /// faces are not taken for it, and a row naming it without its file or scripts, or with one of + /// them empty, is an error. + #[test] + fn the_catalog_row_names_the_face() { + let catalog = "# Latin presentation fonts for the Crafting Apps (opt-in).\n\ + Inter | SemiBold | fonts/inter/Inter-SemiBold.ttf | Latn | OFL-1.1 | fonts/inter/OFL.txt | 78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3 | https://github.com/rsms/inter/releases/download/v4.1/Inter-4.1.zip#extras/ttf/Inter-SemiBold.ttf\n\ + Noto Sans | Condensed SemiBold | fonts/noto-sans-condensed/NotoSans-CondensedSemiBold.ttf | Latn | OFL-1.1 | fonts/noto-sans-condensed/OFL.txt | b41ecd0838ecd17b706432a01c0d63f8bf977d851cc2cf37242324233edb9294 | https://github.com/notofonts/latin-greek-cyrillic/releases/download/NotoSans-v2.015/NotoSans-v2.015.zip#NotoSans/unhinted/ttf/NotoSans-CondensedSemiBold.ttf\n"; + assert_eq!(row(catalog), Ok(Some(("fonts/noto-sans-condensed/NotoSans-CondensedSemiBold.ttf", "Latn")))); + let rest = "OFL-1.1 | fonts/a/OFL.txt | 00 | https://example.com/a.zip"; + assert_eq!(row(&format!("Noto Sans | SemiBold | fonts/a.ttf | Latn | {rest}\n")), Ok(None), "another style"); + assert_eq!(row(&format!("# Noto Sans | Condensed SemiBold | fonts/a.ttf | Latn | {rest}\n")), Ok(None), "a comment"); + assert_eq!(row("Inter | Bold\n"), Ok(None), "a short row for another face"); + assert!(row(&format!("Noto Sans | Condensed SemiBold | fonts/a.ttf | {rest}\n")).is_err(), "a row without its scripts"); + assert!(row(&format!("Noto Sans | Condensed SemiBold | fonts/a.ttf | | {rest}\n")).is_err(), "a row with empty scripts"); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 2028639af4..d1e82be440 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -1068,6 +1068,9 @@ pub fn x_height(data: &[u8], index: u32) -> Option { m.x_height.filter(|h| *h > 0.0).map(|h| h / f32::from(m.units_per_em.max(1))) } +#[cfg(test)] +#[path = "../build/condensed_ui_face.rs"] +mod condensed_ui_face_build; #[cfg(test)] mod tests; #[cfg(test)] diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 1aff4fe1a9..782309a3f0 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -56,7 +56,7 @@ pub(crate) fn window_tab(app: &VectorcraftApp, ui: &mut Ui, w: crate::doc_window ui.painter().rect_filled(strip, 0.0, t.tab_strip); ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); let title = document_window_title(app, w).unwrap_or_default(); - let galley = ui.painter().layout_no_wrap(title, theme::tab_font(title_size), t.text_strong); + let galley = ui.painter().layout_no_wrap(title, theme::tab_title_font(ui, title_size), t.text_strong); let r = egui::Rect::from_min_size(strip.min, vec2((galley.size().x + 28.0).min(strip.width()), strip.height() - 1.0)); ui.painter().rect_filled(r, 0.0, t.panel); ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.5, t.border)); @@ -213,6 +213,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. let shown = crate::doc_windows::tab_window(app).filter(|_| app.ui.home.is_none()); + let title_font = theme::tab_title_font(ui, title_size); // The windows under the tabs, with the text each tab shows, its whole title and the text laid // out; `active` is the position of the highlighted one. An inactive tab shows the name alone, // without the zoom and the mode in parentheses (color mode and view, or the opacity mask being @@ -225,7 +226,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { let title = window_tab_title(app, w, d); let (text, color) = if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; - let galley = ui.painter().layout_no_wrap(text.clone(), theme::tab_font(title_size), color); + let galley = ui.painter().layout_no_wrap(text.clone(), title_font.clone(), color); (w, text, title, galley) }) .collect(); @@ -259,7 +260,7 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { break; } let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; - let (galley, fits) = shortened_title(ui.ctx(), text, theme::tab_font(title_size), color, left - TAB_PADDING); + let (galley, fits) = shortened_title(ui.ctx(), text, title_font.clone(), color, left - TAB_PADDING); (galley, left.max(0.0), true, fits) } else { (galley.clone(), *w, false, true) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..b78968442e 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -29,27 +29,29 @@ fn the_tabs_after_the_leading_one_are_drawn_whole() { assert_eq!(super::tab_room(None, false, 120.0, 119.99), 119.99, "no leading tab"); } -/// A shortened title shows at every width that holds "…", fractional ones included (#8584). +/// A shortened title shows at every width that holds "…", fractional ones included (#8584), in the +/// semibold face and in the tab titles' face (the condensed one in a build with craft-fonts, #8583). #[test] fn a_shortened_title_fits_at_fractional_widths() { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); - let font = crate::theme::semibold(13.0); let title = "Untitled-12 @ 66.67 % (RGB/Preview)"; let mut too_wide = vec![]; let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); - let mut width = ellipsis.size().x.ceil() + 1.0; - while width < 200.0 { - let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); - if !fits { - too_wide.push((width, galley.size().x)); + for font in [crate::theme::semibold(13.0), crate::theme::tab_title_font(ui, 13.0)] { + let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); + let mut width = ellipsis.size().x.ceil() + 1.0; + while width < 200.0 { + let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); + if !fits { + too_wide.push((font.family.clone(), width, galley.size().x)); + } + width += 0.25; } - width += 0.25; } }); output.textures_delta.clear(); - assert!(too_wide.is_empty(), "shortened titles wider than their room (room, width): {too_wide:?}"); + assert!(too_wide.is_empty(), "shortened titles wider than their room (family, room, width): {too_wide:?}"); } /// Tabs 100 wide at 0, 100, 200…, for documents `docs` (a document listed twice has two views). diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 7954785e30..6136913184 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1501,6 +1501,9 @@ fn bundled_fonts_cover_the_catalogs() { egui::FontFamily::Name(crate::theme::FONT_TAB.into()), egui::FontFamily::Name(crate::theme::FONT_MONO.into()), ]; + // The tab family is bound only in builds with craft-fonts' condensed face. + let tab = egui::FontFamily::Name(crate::theme::FONT_TAB.into()); + let families: Vec = families.into_iter().filter(|f| *f != tab || fonts.definitions().families.contains_key(f)).collect(); for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { let (entries, _) = parse_entries(l.source); let cjk_checked = japanese_ui_font && l.code == "ja"; diff --git a/crates/ui-egui/src/tests/tab_overflow.rs b/crates/ui-egui/src/tests/tab_overflow.rs index c9f9edec0a..7b389001d5 100644 --- a/crates/ui-egui/src/tests/tab_overflow.rs +++ b/crates/ui-egui/src/tests/tab_overflow.rs @@ -145,12 +145,87 @@ fn tab_titles_in_the_condensed_face_fit_more_tabs() { let whole = texts.iter().filter(|(t, _)| t.starts_with("Poster draft") && !t.ends_with('…')).count(); // The height of an x, in the tab font and in semibold text. let x = |font: egui::FontId| ctx.fonts_mut(|f| f.layout_no_wrap("x".into(), font, egui::Color32::WHITE)).rows[0].glyphs[0].uv_rect.size.y; - (whole, x(crate::theme::tab_font(40.0)), x(crate::theme::semibold(40.0))) + let tab = if face.is_some() { crate::theme::tab_font(200.0) } else { crate::theme::semibold(200.0) }; + (whole, x(tab), x(crate::theme::semibold(200.0))) }; let (semibold, _, _) = whole_tabs(None); let (narrow, x_tab, x_semibold) = whole_tabs(Some(condensed)); assert!(narrow > semibold, "more tabs fit whole in the condensed face: {narrow} against {semibold}"); - assert!((x_tab - x_semibold).abs() <= 1.0, "an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); + // Two points at 200 pt: a pixel of rounding on each glyph. The faces' own x-heights differ by + // about 8 pt at this size. + assert!((x_tab - x_semibold).abs() <= 2.0, "at 200 pt an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); +} + +/// The tab strip lays its titles out in the tab family's own face when it has one: the monospace +/// face stands in for craft-fonts' condensed face, which CI's craft-fonts checkout does not have +/// (#8583). +#[test] +fn tab_titles_draw_in_the_tab_familys_face() { + let stand_in = vectorcraft_text::CraftFont { + family: "Stand-in", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"), + }; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "name": "Tab test"})).unwrap(); + app.sync_views(); + let ctx = egui::Context::default(); + ctx.set_fonts(crate::theme::interface_fonts_with(Some(&stand_in))); + let titles = title_fonts(&mut app, &ctx); + assert_eq!(titles.len(), 1, "{titles:?}"); + for (title, font) in titles { + assert_eq!(font.family, egui::FontFamily::Name(crate::theme::FONT_TAB.into()), "{title}"); + } +} + +/// The fonts the tab strip lays its "Tab test" titles out in. +fn title_fonts(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, egui::FontId)> { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, SIZE)), ..Default::default() }, |ui| { + egui::CentralPanel::default().show(ui, |ui| chrome::doc_tabs(app, ui)); + }); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::FontId)>) { + match s { + egui::Shape::Text(t) if t.galley.text().starts_with("Tab test") => { + v.extend(t.galley.job.sections.first().map(|s| (t.galley.text().to_owned(), s.format.font_id.clone()))); + } + egui::Shape::Vec(list) => list.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut fonts = vec![]; + for c in &out.shapes { + walk(&c.shape, &mut fonts); + } + fonts +} + +/// Without the condensed face the tab family is not bound, and tab titles draw in the semibold +/// family as it is, with a face added to it later (#8583). +#[test] +fn tab_titles_draw_in_semibold_where_the_tab_family_is_not_bound() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for i in 0..3 { + app.run("file.new", json!({"width": 100, "height": 100, "name": format!("Tab test {i}")})).unwrap(); + } + app.session.set_active(0); + app.sync_views(); + // A face put at the head of the semibold family after the interface's, as an embedder may. + let mut fonts = crate::theme::interface_fonts_with(None); + let added = "Added semibold".to_owned(); + fonts.font_data.insert( + added.clone(), + std::sync::Arc::new(egui::FontData::from_static(include_bytes!("../../../../assets/fonts/JetBrainsMono-Regular.ttf"))), + ); + fonts.families.entry(egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into())).or_default().insert(0, added); + let ctx = egui::Context::default(); + ctx.set_fonts(fonts); + let titles = title_fonts(&mut app, &ctx); + assert_eq!(titles.len(), 3, "{titles:?}"); + for (title, font) in titles { + assert_eq!(font.family, egui::FontFamily::Name(crate::theme::FONT_UI_SEMIBOLD.into()), "{title}"); + } } /// With the last document active, the tabs from it to the end leave room before the » button, and diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 11e8af8e22..2743922495 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -497,16 +497,23 @@ pub const FONT_MONO: &str = "mono"; /// The family document tab titles draw in. In a build with craft-fonts' condensed face /// ([`vectorcraft_text::CONDENSED_UI_FONT`]), that face heads it, at the x-height of the /// [`FONT_UI_SEMIBOLD`] face, followed by the faces of [`FONT_UI_SEMIBOLD`] on its baseline, so -/// more tabs fit in the strip (#8583). Without it the family is [`FONT_UI_SEMIBOLD`]'s. +/// more tabs fit in the strip (#8583). Without it the family is not bound, and tab titles draw in +/// [`FONT_UI_SEMIBOLD`] ([`tab_title_font`]). pub const FONT_TAB: &str = "tab"; pub fn semibold(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_UI_SEMIBOLD.into())) } -/// A document tab's title font ([`FONT_TAB`]). -pub fn tab_font(size: f32) -> FontId { +/// A font in [`FONT_TAB`], which is bound only with the condensed face: see [`tab_title_font`]. +pub(crate) fn tab_font(size: f32) -> FontId { FontId::new(size, FontFamily::Name(FONT_TAB.into())) } +/// The font document tab titles draw in on `ui`: the [`FONT_TAB`] family when `ui`'s fonts bind +/// it (with the condensed face), otherwise [`semibold`]. +pub fn tab_title_font(ui: &egui::Ui, size: f32) -> FontId { + let font = tab_font(size); + if ui.ctx().fonts(|f| f.definitions().families.contains_key(&font.family)) { font } else { semibold(size) } +} /// Whether `family` draws semibold text and takes the bold fallback faces. pub(crate) fn is_semibold(family: &FontFamily) -> bool { matches!(family, FontFamily::Name(name) if [FONT_UI_SEMIBOLD, FONT_TAB].contains(&&**name)) @@ -516,7 +523,7 @@ pub fn mono(size: f32) -> FontId { } /// Installs the interface's fonts and binds the families the panels and dialogs draw in -/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_TAB`], [`FONT_MONO`]). egui 0.37 only bundles its own faces when +/// ([`FONT_UI`], [`FONT_UI_SEMIBOLD`], [`FONT_MONO`], and [`FONT_TAB`] with the condensed face). egui 0.37 only bundles its own faces when /// its `default_fonts` feature is on (this crate enables it); without any face a family lays out /// tofu, and the `egui_kittest` harness alone panics on a missing glyph. Every context that shows /// these families needs this once: [`crate::VectorcraftApp::ui`] calls it on its first pass, and @@ -548,9 +555,10 @@ pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFon |faces: Vec<&str>, fallback: &[String]| -> Vec { faces.into_iter().map(str::to_owned).chain(fallback.iter().cloned()).collect() }; fonts.families.insert(FontFamily::Proportional, family(ui.clone(), &fallback)); let semi = family(semi, &fallback); - let tab = tab_faces(&mut fonts, &semi, condensed); + if let Some(tab) = tab_faces(&mut fonts, &semi, condensed) { + fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); + } fonts.families.insert(FontFamily::Name(FONT_UI_SEMIBOLD.into()), semi); - fonts.families.insert(FontFamily::Name(FONT_TAB.into()), tab); fonts.families.insert(FontFamily::Name(FONT_UI.into()), family(ui, &fallback)); fonts.families.insert(FontFamily::Name(FONT_MONO.into()), family(mono, &mono_fallback)); add_craft_fonts(&mut fonts); @@ -559,28 +567,38 @@ pub(crate) fn interface_fonts_with(condensed: Option<&vectorcraft_text::CraftFon /// The faces of [`FONT_TAB`], added to `fonts`: `condensed`, scaled to the x-height of the first /// face of `semi` (the [`FONT_UI_SEMIBOLD`] stack), then a copy of each face of `semi` on its -/// baseline. `semi` itself without `condensed`, or when either face's x-height can't be read. -fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Vec { +/// baseline. egui's own faces are listed under their own names, uncopied, as in the semibold +/// family: egui skips some of their characters (the Ubuntu logo, for one) only under those names. +/// `None` without `condensed`, or when either face's x-height can't be read. +fn tab_faces(fonts: &mut FontDefinitions, semi: &[String], condensed: Option<&vectorcraft_text::CraftFont>) -> Option> { let x_height = |data: &FontData| vectorcraft_text::x_height((*data.font).as_ref(), data.index).map(|h| h * data.tweak.scale); - let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data)); - let Some((f, reference)) = condensed.zip(reference) else { return semi.to_vec() }; - let Some(own) = vectorcraft_text::x_height(f.bytes, 0) else { return semi.to_vec() }; + let reference = semi.first().and_then(|head| fonts.font_data.get(head)).and_then(|data| x_height(data))?; + let f = condensed?; + let own = vectorcraft_text::x_height(f.bytes, 0)?; let name = craft_font_name(f); let head = FontData::from_static(f.bytes).tweak(egui::epaint::text::FontTweak { scale: reference / own, ..Default::default() }); - // `baseline_copies` reads the head of each family it is given: here only this one. + // `baseline_copies` reads the head of each family it is given. `row` also has egui's empty + // Proportional and Monospace families, whose copies are not this family's. + let tab = FontFamily::Name(FONT_TAB.into()); let mut row = FontDefinitions::empty(); row.font_data.insert(name.clone(), Arc::new(head.clone())); - row.families.insert(FontFamily::Name(FONT_TAB.into()), vec![name.clone()]); + row.families.insert(tab.clone(), vec![name.clone()]); let mut faces = vec![name.clone()]; for face in semi { + if FontDefinitions::builtin_font_names().contains(&face.as_str()) { + faces.push(face.clone()); + continue; + } let Some(data) = fonts.font_data.get(face).cloned() else { continue }; - for (copy, data, _) in crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data) { + for (copy, data, _) in + crate::ui_fonts::baseline_copies(&row, &format!("{face} / {name}"), &data).into_iter().filter(|(_, _, f)| f.contains(&tab)) + { fonts.font_data.insert(copy.clone(), Arc::new(data)); faces.push(copy); } } fonts.font_data.insert(name, Arc::new(head)); - faces + Some(faces) } /// The interface's own faces, added to `fonts`: the names of the regular, semibold and monospace @@ -831,4 +849,57 @@ mod tests { assert_eq!(ctx.global_style().interaction.tooltip_delay, f32::INFINITY); assert_eq!(ctx.global_style().visuals.window_fill, Tokens::for_brightness(Brightness::Light).panel); } + + /// The face heading the tab family draws an x as tall as the semibold face does, and a + /// character it lacks falls back to the semibold face (drawn at its own 0.92 scale) on its + /// baseline (#8583). The monospace face stands in for craft-fonts' condensed face, which CI's + /// craft-fonts checkout does not have. + #[cfg(feature = "interface-fonts")] + #[test] + fn the_tab_family_keeps_the_semibold_x_height_and_baseline() { + let stand_in = vectorcraft_text::CraftFont { + family: "Stand-in", + style: "Regular", + scripts: &["Latn"], + bytes: include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf"), + }; + let mut defs = interface_fonts_with(Some(&stand_in)); + assert_eq!(defs.families[&FontFamily::Name(FONT_TAB.into())][0], craft_font_name(&stand_in)); + // The semibold face alone, as it draws a character in its own family. + defs.families.insert(FontFamily::Name("probe".into()), vec!["Inter-SemiBold".to_owned()]); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + ctx.set_fonts(defs); + let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); + output.textures_delta.clear(); + let glyphs = |text: &str, font: FontId| ctx.fonts_mut(|f| f.layout_no_wrap(text.into(), font, Color32::WHITE)).rows[0].glyphs.clone(); + let x = |font: FontId| glyphs("x", font)[0].uv_rect.size.y; + let (x_tab, x_semibold) = (x(tab_font(200.0)), x(semibold(200.0))); + // Two points at 200 pt: a pixel of rounding on each glyph. The faces' own x-heights differ + // by about 10 pt at this size. + assert!((x_tab - x_semibold).abs() <= 2.0, "at 200 pt an x is {x_tab} pt tall in a tab title and {x_semibold} pt in semibold text"); + // egui skips some characters of its own faces (the Ubuntu logo, two symbols in its emoji + // face); a tab title draws them as semibold text does. + for c in ['\u{534D}', '\u{5350}', '\u{E0FF}', '\u{EFFD}', '\u{F0FF}', '\u{F200}'] { + let has = |font: FontId| ctx.fonts_mut(|f| f.has_glyph(&font, c)); + let name = format!("U+{:04X}", u32::from(c)); + assert_eq!(has(tab_font(13.0)), has(semibold(13.0)), "{name} has a glyph in a tab title as in semibold text"); + if has(semibold(13.0)) { + // Both families take it from the same fallback face, which draws it at one size. + let size = |font: FontId| glyphs(&c.to_string(), font).first().map(|g| g.uv_rect.size); + assert_eq!(size(tab_font(13.0)), size(semibold(13.0)), "{name} draws at the same size in a tab title as in semibold text"); + } + } + let bottom = |g: &egui::epaint::text::Glyph| g.pos.y + g.uv_rect.offset.y + g.uv_rect.size.y; + // U+0182, which Inter has and the monospace face lacks. + let c = 'Ƃ'; + for size in [13.0_f32, 24.0, 40.0, 100.0] { + let own = glyphs(&c.to_string(), FontId::new(size, FontFamily::Name("probe".into()))); + let row = glyphs(&format!("H{c}"), tab_font(size)); + assert_eq!((own.len(), row.len()), (1, 2), "{c} lays out as one glyph"); + // Half a point: one device pixel at 2 pixels per point, for each glyph's rounding. + let drift = (bottom(&row[1]) - row[0].pos.y) - (bottom(&own[0]) - own[0].pos.y); + assert!(drift.abs() <= 0.5, "at {size} pt, {c} ends {drift:.2} pt below the tab family's baseline"); + } + } } diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index cb419067e1..8e2d07ff5c 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -239,7 +239,7 @@ pub(crate) fn baseline_copies(defs: &FontDefinitions, name: &str, data: &FontDat let mut copies: Vec<(String, FontData, Vec)> = vec![]; for (family, stack) in &defs.families { let head = stack.first().and_then(|head| Some((head.as_str(), defs.font_data.get(head)?))); - let shift = head.and_then(|(_, data)| row_metrics(data)).map_or(0.0, |row| baseline_shift(row, (*data.font).as_ref(), data.index)); + let shift = head.and_then(|(_, data)| row_metrics(data)).map_or(0.0, |row| baseline_shift(row, data)); if let Some((_, _, families)) = copies.iter_mut().find(|(_, copy, _)| copy.tweak.y_offset_factor.to_bits() == shift.to_bits()) { families.push(family.clone()); continue; @@ -266,15 +266,19 @@ fn em_metrics(data: &[u8], index: u32) -> Option<(f32, f32)> { Some((ascent / upem, (ascent - descent + gap) / upem)) } -/// The `y_offset_factor` that puts the glyphs of the face at `index` of `face` on the baseline of -/// the row's first face, whose ascent, row height and offset in ems are `row`. egui draws a -/// fallback glyph's baseline at its face's ascent plus half the difference between the two row -/// heights, so a face with a taller ascent or descent sits off the baseline by the shift computed -/// here, in ems of the font size, limited to half an em either way. -fn baseline_shift(row: (f32, f32, f32), face: &[u8], index: u32) -> f32 { +/// The `y_offset_factor` that puts the glyphs of the fallback face `data` on the baseline of the +/// row's first face, whose ascent, row height and offset in ems are `row`. egui draws a fallback +/// glyph's baseline at its face's ascent plus half the difference between the two row heights, so a +/// face with a taller ascent or descent sits off the baseline by the shift computed here, in ems of +/// the font size, limited to half an em either way. egui scales the face's metrics and its +/// `y_offset_factor` by the face's own `FontTweak` scale, so both are measured at that scale. +fn baseline_shift(row: (f32, f32, f32), data: &FontData) -> f32 { let (row_ascent, row_height, row_offset) = row; - let shift = em_metrics(face, index).map_or(0.0, |(ascent, height)| row_ascent + row_offset - (ascent + 0.5 * (row_height - height))); - if shift.is_finite() { shift.clamp(-0.5, 0.5) } else { 0.0 } + let scale = data.tweak.scale; + let shift = em_metrics((*data.font).as_ref(), data.index) + .map_or(0.0, |(ascent, height)| row_ascent + row_offset - scale * ascent - 0.5 * (row_height - scale * height)); + let factor = if shift.is_finite() { shift.clamp(-0.5, 0.5) / scale } else { 0.0 }; + if factor.is_finite() { factor } else { 0.0 } } /// Call `f` with the text of `shape` and the shapes it holds. @@ -375,8 +379,10 @@ mod tests { fonts.finish(&ctx); frame(&ctx, &mut fonts, "日本語の文字 Layer 1"); if vectorcraft_text::CRAFT_FONTS.is_empty() { + // The condensed tab face is read from its own catalog, so a checkout can give it alone. + let condensed = vectorcraft_text::CONDENSED_UI_FONT.as_ref().map(crate::theme::craft_font_name); let names: Vec = ctx.fonts(|f| f.definitions().font_data.keys().cloned().collect()); - assert!(names.iter().all(|n| !n.starts_with("craft-fonts")), "{names:?}"); + assert!(names.iter().all(|n| !n.starts_with("craft-fonts") || Some(n) == condensed.as_ref()), "{names:?}"); } assert!(has_glyph(&ctx, 'L')); } diff --git a/crates/ui-egui/tests/install_fonts.rs b/crates/ui-egui/tests/install_fonts.rs index d7ebcaab27..56d49bc3bc 100644 --- a/crates/ui-egui/tests/install_fonts.rs +++ b/crates/ui-egui/tests/install_fonts.rs @@ -33,7 +33,8 @@ fn frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) { fn every_family_the_panels_draw_in_is_bound() { let ctx = context(); frame(&ctx, |ui| { - for font in [theme::semibold(12.0), theme::mono(12.0), FontId::new(12.0, FontFamily::Name(theme::FONT_UI.into()))] { + let tab = theme::tab_title_font(ui, 12.0); + for font in [theme::semibold(12.0), tab, theme::mono(12.0), FontId::new(12.0, FontFamily::Name(theme::FONT_UI.into()))] { ui.label(egui::RichText::new("Gaussian Blur").font(font)); } }); @@ -45,6 +46,17 @@ fn every_family_the_panels_draw_in_is_bound() { let installed: Vec<&str> = INTERFACE_FACES.into_iter().filter(|face| definitions.font_data.contains_key(*face)).collect(); let family = |family: FontFamily| definitions.families[&family].clone(); let named = |name: &str| family(FontFamily::Name(name.into())); + // The tab family is bound, headed by craft-fonts' condensed face and followed by the semibold + // faces, when the build has that face and both faces give an x-height to match. + let x_height = |name: &String| definitions.font_data.get(name).and_then(|d| vectorcraft_text::x_height((*d.font).as_ref(), d.index)); + let semibold_head = named(theme::FONT_UI_SEMIBOLD).first().and_then(x_height); + match vectorcraft_text::CONDENSED_UI_FONT.as_ref().filter(|f| vectorcraft_text::x_height(f.bytes, 0).is_some() && semibold_head.is_some()) { + None => assert!(!definitions.families.contains_key(&FontFamily::Name(theme::FONT_TAB.into()))), + Some(f) => { + assert_eq!(named(theme::FONT_TAB)[0], format!("craft-fonts {} {}", f.family, f.style)); + assert!(named(theme::FONT_TAB).len() > named(theme::FONT_UI_SEMIBOLD).len(), "the semibold faces follow the condensed one"); + } + } if cfg!(feature = "interface-fonts") { assert_eq!(installed, INTERFACE_FACES); assert_eq!(named(theme::FONT_UI)[0], "Inter"); diff --git a/docs/development.md b/docs/development.md index 66f925324e..950b996ed9 100644 --- a/docs/development.md +++ b/docs/development.md @@ -178,8 +178,9 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo xtask ci # also runs the Japanese- checkout's opt-in `fonts/latin-manifest.txt`, Noto Sans Condensed SemiBold, as `vectorcraft_text::CONDENSED_UI_FONT`. `theme::FONT_TAB` draws the titles in it at the x-height of the interface's semibold face, so more tabs fit in the strip. Without - `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), tab - titles draw in the semibold face. + `CRAFT_FONTS_DIR`, on the web, or with a checkout that lacks the row (a build warning), + `theme::FONT_TAB` is not bound and tab titles draw in the semibold family + (`theme::tab_title_font`). - Tests that need Japanese or Georgian glyphs skip with a message when built without craft-fonts. The FreeBSD CI job and every release job (`release.yml`) check craft-fonts out at a pinned commit; release packages carry each embedded font's `OFL-.txt`. @@ -205,7 +206,8 @@ font that has them to each of the families below (`ctx.add_font` with an `Insert family). The panels and dialogs draw in their own egui families (`theme::FONT_UI`, `FONT_UI_SEMIBOLD`, -`FONT_MONO`), and egui panics drawing text in a family no font is bound to. `VectorcraftApp::logic` +`FONT_MONO`, and `FONT_TAB` for document tab titles in builds with the condensed face), and egui +panics drawing text in a family no font is bound to. `VectorcraftApp::logic` binds them on its first frame; an embedder that draws the panels or dialogs without it calls `theme::install_fonts` once on its context, with or without `interface-fonts`. It replaces the context's font definitions, so the embedder's own fonts are added after it. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 8b5a9f315a..b6fa3393c1 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -443,7 +443,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored | | When the document tabs don't all fit, the first tab that doesn't fit whole fills the room before the » button with its title shortened and ending in "…", once that room leaves at least 40 pt for the title; with the active tab among the last ones, the tab before the ones shown fills the room left at the start instead; an active tab wider than the strip is shortened to it, and a tab narrower than 25 pt shows no ×; the tooltip of a shortened tab shows the whole title, wrapped to the window (VectorCraft's own rule) | done | #8584; `tests::tab_overflow`; not scored | | An inactive document tab shows the document's name, the view number and the unsaved-changes mark, without the zoom and the mode in parentheses (the color mode and view, or the opacity mask being edited); the active tab keeps its whole title, and an inactive tab's tooltip shows the whole title (VectorCraft's own rule) | done | #8582; `tests::tab_overflow::inactive_tabs_show_the_name_alone_so_more_tabs_fit`; not scored | -| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`; not scored | +| Document tab titles draw in a condensed face (craft-fonts' Noto Sans Condensed SemiBold) at the x-height of the interface's semibold face, so more tabs fit; builds without that face draw them in the semibold face (VectorCraft's own rule) | done; release builds pending | #8583; `tests::tab_overflow::tab_titles_in_the_condensed_face_fit_more_tabs`, `theme::tests::the_tab_family_keeps_the_semibold_x_height_and_baseline`; the release and FreeBSD workflows pin a craft-fonts commit without the face, so official builds draw tab titles in the semibold face until that pin moves past storytold/craft-fonts#72; not scored | | Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it | | Behaviour | Status | Notes | From f3916773e8c35740eab0d674816a5313294d23cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:32:17 -0800 Subject: [PATCH 020/160] JavaScript: release pruned collection storage and follow ES2015 in typed array methods - A collection that removes the holes of a Map or Set releases the room its entries and index held, and a WeakMap or WeakSet whose table has far more room than entries after pruning releases the extra room, so the heap estimate covers what the tables still hold. - %TypedArray%.from throws a TypeError for a receiver that is not a constructor before it reads the source (section 22.2.2.1 step 2). - %TypedArray%.from and of make their result with any constructor they are called on (TypedArrayCreate, section 22.2.4.6): the result must be a typed array with room for every element, or the call is a TypeError. - %TypedArray%.prototype.toLocaleString calls each element's method on the number itself (section 22.2.3.27); Array.prototype.toLocaleString still calls it on the element's object. - ArrayBuffer.prototype.slice and the typed array map, filter, slice and subarray read the receiver's constructor where SpeciesConstructor does (section 7.3.20): a getter's error propagates, and a value that is neither undefined nor an object is a TypeError. filter reads it before its callback runs. - sort charges a unit of fuel for each element it reads and each it writes back, before it starts. - set between typed arrays on different buffers writes each element as it reads it, without holding a copy of the source. - The binary data module comment says a constructor reads a primitive string as a length and from reads it by code point, and a prototype test puts its value at the index it checks. --- crates/js/src/builtins/array.rs | 23 +++++++- crates/js/src/builtins/binary.rs | 94 +++++++++++++++++++++--------- crates/js/src/collections_tests.rs | 90 +++++++++++++++++++++++++++- crates/js/src/heap.rs | 14 +++++ crates/js/src/interp.rs | 61 +++++++++++++++++++ 5 files changed, 251 insertions(+), 31 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 1c91d602b0..f4f2a161bc 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -331,13 +331,26 @@ fn join_item(interp: &mut Interp, v: Value) -> JsResult> { /// An element as `toLocaleString` writes it (section 15.4.4.3). fn locale_item(interp: &mut Interp, v: Value) -> JsResult> { + locale_call(interp, v, false) +} + +/// An element as `%TypedArray%.prototype.toLocaleString` writes it (ECMA-262 6.0 section +/// 22.2.3.27): the method is called on the element's value, not on its object. +fn typed_locale_item(interp: &mut Interp, v: Value) -> JsResult> { + locale_call(interp, v, true) +} + +/// Calls the element's `toLocaleString`, looked up on its object, with the value itself as `this` +/// when `on_value` is true and with the object otherwise. +fn locale_call(interp: &mut Interp, v: Value, on_value: bool) -> JsResult> { if v.is_nullish() { return Ok(None); } let e = interp.to_object(&v)?; let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &Value::Object(e))?; require_callable(interp, &f, "an element's toLocaleString")?; - let s = interp.call(&f, &Value::Object(e), &[])?; + let this = if on_value { v } else { Value::Object(e) }; + let s = interp.call(&f, &this, &[])?; interp.to_str(&s).map(Some) } @@ -348,10 +361,16 @@ pub(super) fn join(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> } /// `Array.prototype.toLocaleString` (section 15.4.4.3). -pub(super) fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { +fn to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, locale_item)) } +/// `%TypedArray%.prototype.toLocaleString` (ECMA-262 6.0 section 22.2.3.27), the array method +/// with each element's method called on the element's value. +pub(super) fn typed_to_locale_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + with_this(interp, &this, |interp, o| join_with(interp, o, &Value::Undefined, typed_locale_item)) +} + // ---- methods that change the object ---- /// `Array.prototype.concat` (section 15.4.4.4). diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 8c10723a74..be2fe8258d 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -15,8 +15,9 @@ //! every buffer's bytes are checked against the heap before they are allocated. Every element //! a method visits takes a unit of fuel, and a sort's comparisons take one each. //! -//! The language has no iterators yet, so constructing from an object and `%TypedArray%.from` -//! read an array, a string (by code point) or an object with a `length`, by index. +//! The language has no iterators yet, so constructing from an object reads an array or an object +//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A +//! constructor given a primitive string reads it as a length. use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; use super::{arg, array, data, method, native, require_callable, to_integer}; @@ -462,12 +463,24 @@ fn relative(interp: &mut Interp, v: &Value, len: usize, default: usize) -> JsRes Ok(r as usize) } +/// The `constructor` steps of SpeciesConstructor (section 7.3.20): reads `o.constructor` and +/// throws a `TypeError` when it is neither `undefined` nor an object. The language has no +/// `@@species`, so the result is always made with the intrinsic constructor. +fn species_check(interp: &mut Interp, o: ObjId, name: &str) -> JsResult<()> { + let c = interp.get_from(o, &key("constructor"), &Value::Object(o))?; + if matches!(c, Value::Undefined | Value::Object(_)) { + return Ok(()); + } + Err(interp.type_error(&format!("{name}: the constructor property is not an object"))) +} + /// `ArrayBuffer.prototype.slice` (section 24.1.4.3). fn buffer_slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let o = this_buffer(interp, &this, "slice")?; let len = buffer_len(interp, o); let first = relative(interp, &arg(args, 0), len, 0)?; let last = relative(interp, &arg(args, 1), len, len)?; + species_check(interp, o, "ArrayBuffer.prototype.slice")?; let count = last.saturating_sub(first); // Each copied byte takes a unit of fuel, charged before the copy is made. for _ in 0..count { @@ -705,21 +718,31 @@ typed_ctors! { float64_ctor, Float64; } -/// The element type of the typed array constructor `this`, as `from` and `of` need. -fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { +/// TypedArrayCreate (section 22.2.4.6), as `from` and `of` need: a new typed array of `len` +/// elements made by the constructor `c`. One of the nine typed array constructors makes it +/// directly; any other constructor is called, and its result must be a typed array with at +/// least `len` elements. +fn typed_create(interp: &mut Interp, c: &Value, len: u64, name: &str) -> JsResult<(ObjId, View)> { let ctors = interp.intrinsics.es2015.typed_ctors; - if let Some(o) = this.as_object() - && let Some(i) = ctors.iter().position(|c| *c == o) - && let Some(elem) = Elem::ALL.get(i) - { - return Ok(*elem); - } - Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) + let elem = c.as_object().and_then(|o| ctors.iter().position(|t| *t == o)).and_then(|i| Elem::ALL.get(i).copied()); + let ta = match elem { + Some(elem) => new_typed(interp, elem, len)?, + None => { + #[allow(clippy::cast_precision_loss)] + let made = interp.construct(c, &[Value::Number(len as f64)])?; + match made.as_object() { + Some(o) if view_of(interp, o).is_some_and(|v| v.length as u64 >= len) => o, + _ => return Err(interp.type_error(&format!("TypedArray.{name}: the constructor did not make a typed array long enough"))), + } + } + }; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + Ok((ta, view)) } /// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - if !interp.is_callable(&this) { + if !interp.is_constructor(&this) { return Err(interp.type_error("TypedArray.from must be called on a typed array constructor")); } let map_fn = arg(args, 1); @@ -734,9 +757,7 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe let src = interp.to_object(&source)?; let src_value = Value::Object(src); let len = length_of(interp, src)?; - let elem = ctor_elem(interp, &this, "from")?; - let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + let (ta, view) = interp.rooted(std::slice::from_ref(&src_value), |interp| typed_create(interp, &this, len, "from"))?; return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { for i in 0..len { interp.use_fuel()?; @@ -760,10 +781,8 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe }); let result = gathered.and_then(|()| { let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); - let elem = ctor_elem(interp, &this, "from")?; - let ta = new_typed(interp, elem, items.len() as u64)?; + let (ta, view) = typed_create(interp, &this, items.len() as u64, "from")?; interp.temp_roots.push(Value::Object(ta)); - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; for (i, item) in items.into_iter().enumerate() { interp.use_fuel()?; #[allow(clippy::cast_precision_loss)] @@ -780,9 +799,10 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe /// `%TypedArray%.of(...items)` (section 22.2.2.2). fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let elem = ctor_elem(interp, &this, "of")?; - let ta = new_typed(interp, elem, args.len() as u64)?; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + if !interp.is_constructor(&this) { + return Err(interp.type_error("TypedArray.of must be called on a typed array constructor")); + } + let (ta, view) = typed_create(interp, &this, args.len() as u64, "of")?; interp.rooted(&[Value::Object(ta)], |interp| { for (i, v) in args.iter().enumerate() { interp.use_fuel()?; @@ -862,7 +882,7 @@ generic_methods! { ta_reduce, "reduce", array::reduce; ta_reduce_right, "reduceRight", array::reduce_right; ta_reverse, "reverse", array::reverse; - ta_to_locale_string, "toLocaleString", array::to_locale_string; + ta_to_locale_string, "toLocaleString", array::typed_to_locale_string; } fn iter_of(interp: &mut Interp, this: &Value, kind: IterKind, name: &str) -> JsResult { @@ -927,10 +947,11 @@ fn find_index(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe /// `map` (section 22.2.3.18): a new typed array of the same type holding each callback result. fn map(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (_, view) = this_typed(interp, &this, "map")?; + let (o, view) = this_typed(interp, &this, "map")?; let f = arg(args, 0); require_callable(interp, &f, "the callback")?; let this_arg = arg(args, 1); + species_check(interp, o, "TypedArray.prototype.map")?; let out = new_typed(interp, view.elem, view.length as u64)?; let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; interp.rooted(&[Value::Object(out)], |interp| { @@ -958,10 +979,11 @@ fn typed_from_values(interp: &mut Interp, elem: Elem, values: &[f64]) -> JsResul /// `filter` (section 22.2.3.9). fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (_, view) = this_typed(interp, &this, "filter")?; + let (o, view) = this_typed(interp, &this, "filter")?; let f = arg(args, 0); require_callable(interp, &f, "the callback")?; let this_arg = arg(args, 1); + species_check(interp, o, "TypedArray.prototype.filter")?; let mut held = crate::interp::HeldBytes::new(interp); let mut kept = Vec::new(); for i in 0..view.length { @@ -981,10 +1003,11 @@ fn filter(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult /// `slice(start, end)` (section 22.2.3.23): a copy of the range in a new buffer. fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (_, view) = this_typed(interp, &this, "slice")?; + let (o, view) = this_typed(interp, &this, "slice")?; let start = relative(interp, &arg(args, 0), view.length, 0)?; let end = relative(interp, &arg(args, 1), view.length, view.length)?; let count = end.saturating_sub(start); + species_check(interp, o, "TypedArray.prototype.slice")?; let out = new_typed(interp, view.elem, count as u64)?; let dst = view_of(interp, out).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; copy_elements(interp, &view, start, &dst, 0, count)?; @@ -993,9 +1016,10 @@ fn slice(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult< /// `subarray(begin, end)` (section 22.2.3.26): a new view on the same buffer. fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (_, view) = this_typed(interp, &this, "subarray")?; + let (o, view) = this_typed(interp, &this, "subarray")?; let begin = relative(interp, &arg(args, 0), view.length, 0)?; let end = relative(interp, &arg(args, 1), view.length, view.length)?; + species_check(interp, o, "TypedArray.prototype.subarray")?; interp.rooted(std::slice::from_ref(&this), |i| i.reserve_heap(OBJECT_BYTES + VIEW_BYTES))?; let sub = View { buffer: view.buffer, offset: view.offset + begin * view.elem.size(), length: end.saturating_sub(begin), elem: view.elem }; let proto = typed_proto(interp, view.elem); @@ -1004,8 +1028,8 @@ fn subarray(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResu /// `set(source, offset)` (section 22.2.3.22): writes a typed array's elements, or an array-like /// object's elements converted with ToNumber, starting at `offset`. A source that does not fit -/// is a `RangeError`. A typed array source is read in full before anything is written, so a -/// source on the same buffer copies correctly. +/// is a `RangeError`. A typed array source on the same buffer is read in full before anything is +/// written, so it copies correctly. fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (_, view) = this_typed(interp, &this, "set")?; let offset = to_integer(interp, &arg(args, 1))?; @@ -1033,6 +1057,16 @@ fn set(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult = (0..view.length).map(|i| at(interp, &view, i)).collect(); merge_sort(interp, &mut values, &compare)?; for (i, n) in values.into_iter().enumerate() { diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index 7c00b29532..a5180291e6 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -236,6 +236,36 @@ fn a_collection_removes_holes_and_moves_live_iterators() { assert_eq!(rest, JsValue::String("180,182,184,186,188,190,192,194,196,198".into())); } +#[test] +fn a_collection_releases_the_storage_of_removed_entries() { + let mut realm = realm(); + realm + .run( + "var m = new Map(), wm = new WeakMap(), kept = {}; + for (var i = 0; i < 1000; i++) m.set(i, i); + m.clear(); m.set('a', 1); + (function () { for (var i = 0; i < 1000; i++) wm.set({}, i); })(); + wm.set(kept, 1);", + ) + .unwrap(); + let m = global_object(&mut realm, "m"); + let wm = global_object(&mut realm, "wm"); + realm.interp().collect_garbage(); + match realm.interp().heap.object(m).map(|o| &o.class) { + Some(Class::Map(c)) => { + let (entries, index) = c.capacity(); + assert_eq!(c.slots(), 1); + assert!(entries < 64 && index < 64, "{entries} {index}"); + } + _ => panic!("not a Map"), + } + match realm.interp().heap.object(wm).map(|o| &o.class) { + Some(Class::WeakMap(w)) => assert!(w.entries.len() == 1 && w.entries.capacity() < 64, "{}", w.entries.capacity()), + _ => panic!("not a WeakMap"), + } + assert_eq!(realm.run("m.get('a') + wm.get(kept)").unwrap(), JsValue::Number(2.0)); +} + // ---- ArrayBuffer ---- #[test] @@ -319,7 +349,7 @@ fn numeric_names_are_elements_or_nothing() { truth( "var a = new Int8Array(2); a['-0'] = 1; a[1.5] = 1; a['-0'] === undefined && a[1.5] === undefined && Object.getOwnPropertyNames(a).length === 2", ); - truth("Int8Array.prototype[0] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[0]; r"); + truth("Int8Array.prototype[3] = 'p'; var a = new Int8Array(1); var r = a[3] === undefined && a[0] === 0; delete Int8Array.prototype[3]; r"); truth("var a = new Int8Array(1); a.foo = 1; a['01'] = 2; a.foo === 1 && a['01'] === 2"); // The value is converted before the index is checked (section 9.4.5.9), so an ignored write still converts it. truth( @@ -378,6 +408,14 @@ fn typed_array_methods() { truth("Uint8Array.from({length: 2, 0: 1, 1: 2}, function (v, i) { return v * 10 + i; }).join() === '10,21'"); truth("Int16Array.from('12').join() === '1,2' && Float32Array.of(1, 2.5).join() === '1,2.5'"); truth("new Int8Array([1, 2]).toString === Array.prototype.toString && String(new Int8Array([1, 2])) === '1,2'"); + // A typed array calls each element's toLocaleString on the number (section 22.2.3.27); an array + // calls it on the element's object (section 15.4.4.3). + assert_eq!( + string( + "Number.prototype.toLocaleString = function () { 'use strict'; return typeof this; }; new Uint8Array([7, 8]).toLocaleString() + ';' + [7].toLocaleString()" + ), + "number,number;object" + ); truth( "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", ); @@ -388,6 +426,19 @@ fn typed_array_methods() { throws("Int8Array.from.call({}, [1])", "TypeError"); // The source's length is read before the constructor is checked to be a typed array's. throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); + // A receiver that is not a constructor is refused before the source is read (section 22.2.2.1 step 2). + throws("Int8Array.from.call(ArrayBuffer.isView, {get length() { throw new RangeError('first'); }})", "TypeError"); + // Any other constructor makes the result (TypedArrayCreate, section 22.2.4.6), which must be a + // typed array with room for every element. + truth( + "var lens = []; function C(n) { lens.push(n); return new Int16Array(n + 1); } \ + var a = Uint8Array.from.call(C, [300, 2]), b = Int8Array.of.call(C, 7), c = Int8Array.from.call(C, 'xy', function (v) { return v.length; }); \ + a instanceof Int16Array && a.join() === '300,2,0' && b.join() === '7,0' && c.join() === '1,1,0' && lens.join() === '2,1,2'", + ); + truth("var B = Int8Array.bind(null); Int8Array.of.call(B, 1, 2).join() === '1,2'"); + throws("Int8Array.from.call(function () { return new Int8Array(1); }, [1, 2])", "TypeError"); + throws("Int8Array.of.call(function () {}, 1)", "TypeError"); + throws("Int8Array.of.call(Math.max, 1)", "TypeError"); truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); // A copy to the same element type keeps every bit, a signaling NaN's included. truth( @@ -398,6 +449,30 @@ fn typed_array_methods() { new DataView(g.buffer).getUint32(8, true) === 0x7f800001", ); assert_eq!(string("var a = new Uint8Array([1, 2, 3, 4, 5]); a.set(a.subarray(2), 1); a.join()"), "1,3,4,5,5"); + assert_eq!( + string("var b = new ArrayBuffer(4); var a = new Int8Array(b); a.set([1, 2]); new Uint16Array(b).set(a.subarray(0, 2)); a.join()"), + "1,0,2,0" + ); + assert_eq!(string("var a = new Int8Array(3); a.set(new Uint8Array([200, 1]), 1); a.join()"), "0,-56,1"); +} + +#[test] +fn derived_buffers_and_typed_arrays_read_the_constructor_first() { + // SpeciesConstructor (section 7.3.20) reads `constructor` before the result is made, and + // before filter's callback runs. + for call in ["a.slice()", "a.subarray(0)", "a.map(function (v) { return v; })", "a.filter(function () { n++; })", "a.buffer.slice(0)"] { + let getter = format!( + "var n = 0; var a = new Int8Array([1, 2]); var g = {{get: function () {{ throw new RangeError('c'); }}}}; \ + Object.defineProperty(a, 'constructor', g); Object.defineProperty(a.buffer, 'constructor', g); {call}" + ); + throws(&getter, "RangeError"); + throws(&format!("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; a.buffer.constructor = null; {call}"), "TypeError"); + } + truth("var n = 0; var a = new Int8Array([1, 2]); a.constructor = 1; try { a.filter(function () { n++; }); } catch (e) {} n === 0"); + truth( + "var a = new Int8Array([1, 2]); a.constructor = undefined; a.buffer.constructor = undefined; a.slice().join() === '1,2' && a.subarray(1)[0] === 2 && a.buffer.slice(1).byteLength === 1", + ); + truth("var a = new Int8Array([1, 2]); a.constructor = Array; a.map(function (v) { return v; }) instanceof Int8Array"); } #[test] @@ -409,4 +484,17 @@ fn typed_array_work_takes_fuel() { assert_eq!(limit(&fuel, "new ArrayBuffer(1 << 20).slice(0)"), LimitKind::Fuel); assert_eq!(limit(&fuel, "new Uint8Array({length: 1 << 20})"), LimitKind::Fuel); assert_eq!(limit(&fuel, "new Float64Array(1 << 16).sort(function (a, b) { return a - b; })"), LimitKind::Fuel); + // A sort of 2^16 equal elements makes 2^19 comparisons, and reading and writing back its + // elements takes 2^17 units more. + let sort = "new Uint8Array(1 << 16).sort(); 'sorted'"; + assert_eq!(limit(&Limits { fuel: 600_000, ..Limits::default() }, sort), LimitKind::Fuel); + let mut enough = Realm::with_options(es2015(), Limits { fuel: 700_000, ..Limits::default() }); + assert_eq!(enough.run(sort).unwrap(), JsValue::String("sorted".into())); +} + +#[test] +fn a_copy_between_buffers_holds_no_snapshot() { + let mut realm = Realm::with_options(es2015(), Limits { heap_bytes: 6 << 20, ..Limits::default() }); + let r = realm.run("var a = new Uint8Array(1 << 20), b = new Int8Array(1 << 20); a[5] = 200; b.set(a); b[5]"); + assert_eq!(r.unwrap(), JsValue::Number(-56.0)); } diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 4aed4b9c9b..e3aa6a6240 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -374,11 +374,20 @@ impl Coll { } moved.push(live); self.entries.retain(Option::is_some); + // The storage the holes held is released along with their charge. + self.entries.shrink_to_fit(); + self.index.shrink_to_fit(); for slot in self.index.values_mut() { *slot = moved.get(*slot).copied().unwrap_or(*slot); } moved } + + /// The positions the entries and the index have room for, for tests. + #[cfg(test)] + pub(crate) fn capacity(&self) -> (usize, usize) { + (self.entries.capacity(), self.index.capacity()) + } } /// The entries of a WeakMap or a WeakSet, by the index of their key; a WeakSet's values are @@ -777,6 +786,11 @@ impl Heap { && let Class::WeakMap(w) | Class::WeakSet(w) = &mut o.class { w.entries.retain(|k, _| marks.get(*k as usize).copied().unwrap_or(false)); + // Only the entries left are charged, and a table with far more room than entries + // releases the extra room. + if w.entries.capacity() > 2 * w.entries.len() + 16 { + w.entries.shrink_to_fit(); + } live += WEAK_ENTRY_BYTES * w.entries.len(); } } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b90c354347..3f15d6adda 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2239,6 +2239,20 @@ impl Interp { v.as_object().and_then(|o| self.heap.object(o)).is_some_and(|o| matches!(o.class, Class::Function(_))) } + /// Whether `new` can construct with `v` (section 7.2.4): a function written in JavaScript, a + /// built-in constructor, or a bound function whose target is one, as `op_new` accepts. + pub(crate) fn is_constructor(&self, v: &Value) -> bool { + let mut f = v.as_object(); + while let Some(o) = f { + match self.heap.object(o).map(|o| &o.class) { + Some(Class::Function(Func::Closure { .. } | Func::Native { constructor: true, .. })) => return true, + Some(Class::Function(Func::Bound { target, .. })) => f = Some(*target), + _ => return false, + } + } + false + } + fn func_of(&self, v: &Value) -> Option { match &self.heap.object(v.as_object()?)?.class { Class::Function(f) => Some(f.clone()), @@ -2580,6 +2594,53 @@ impl Interp { r } + /// Constructs with `f` as `new f(...args)` does (`[[Construct]]`, sections 13.2.2 and + /// 15.3.4.5.2), for a built-in that constructs with a value it is given. + pub(crate) fn construct(&mut self, f: &Value, args: &[Value]) -> JsResult { + if self.reentry >= self.limits.reentry { + return Err(Abrupt::Limit(LimitKind::Reentry)); + } + let saved = self.stack.len(); + self.stack.push(f.clone()); + self.stack.extend(args.iter().cloned()); + self.reentry += 1; + let r = self.construct_rooted(f.clone(), args.to_vec(), saved); + self.reentry -= 1; + self.stack.truncate(saved); + r + } + + fn construct_rooted(&mut self, mut f: Value, mut args: Vec, saved: usize) -> JsResult { + // The bound function on the stack keeps its arguments reachable. + while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { + self.use_fuel()?; + let mut all = bound_args.to_vec(); + all.append(&mut args); + args = all; + f = Value::Object(target); + } + match self.func_of(&f) { + Some(Func::Closure { code, env }) => { + let Some(callee) = f.as_object() else { return internal("callee is not an object") }; + let proto = match self.get_from(callee, &key("prototype"), &f)? { + Value::Object(p) => p, + _ => self.intrinsics.object_proto, + }; + let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + self.stack.truncate(saved); + self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args }, Some(obj), true)?; + self.execute() + } + Some(Func::Native { f: native, constructor: true, .. }) => { + let held = self.held_bytes; + let r = native(self, Value::Undefined, &args, true); + self.held_bytes = held; + r + } + _ => Err(self.type_error("the value is not a constructor")), + } + } + fn call_rooted(&mut self, f: Value, this: Value, args: Vec, saved: usize) -> JsResult { match self.prepare_call(f, this, args)? { Prepared::Done(v) => Ok(v), From 287dd7230929f5b04f98b4fcd572602283b3a401 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:51:57 -0800 Subject: [PATCH 021/160] JavaScript: typed array from and of take only the typed array constructors %TypedArray%.from and of make their result with AllocateTypedArray in the 6th edition (sections 22.2.2.1.1, 22.2.2.2 and 22.2.1.2.1), which looks for a typed array constructor on the receiver's prototype chain and throws a TypeError when it finds none. A function that returns a typed array, or a bound typed array constructor, is refused again instead of being called. Later editions call the receiver through TypedArrayCreate. --- crates/js/src/builtins/binary.rs | 43 ++++++++++++--------------- crates/js/src/collections_tests.rs | 15 +++------- crates/js/src/interp.rs | 47 ------------------------------ 3 files changed, 22 insertions(+), 83 deletions(-) diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index be2fe8258d..2e87c889c8 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -718,26 +718,16 @@ typed_ctors! { float64_ctor, Float64; } -/// TypedArrayCreate (section 22.2.4.6), as `from` and `of` need: a new typed array of `len` -/// elements made by the constructor `c`. One of the nine typed array constructors makes it -/// directly; any other constructor is called, and its result must be a typed array with at -/// least `len` elements. -fn typed_create(interp: &mut Interp, c: &Value, len: u64, name: &str) -> JsResult<(ObjId, View)> { +/// The element type of the typed array constructor `this`, as `from` and `of` need. +fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { let ctors = interp.intrinsics.es2015.typed_ctors; - let elem = c.as_object().and_then(|o| ctors.iter().position(|t| *t == o)).and_then(|i| Elem::ALL.get(i).copied()); - let ta = match elem { - Some(elem) => new_typed(interp, elem, len)?, - None => { - #[allow(clippy::cast_precision_loss)] - let made = interp.construct(c, &[Value::Number(len as f64)])?; - match made.as_object() { - Some(o) if view_of(interp, o).is_some_and(|v| v.length as u64 >= len) => o, - _ => return Err(interp.type_error(&format!("TypedArray.{name}: the constructor did not make a typed array long enough"))), - } - } - }; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; - Ok((ta, view)) + if let Some(o) = this.as_object() + && let Some(i) = ctors.iter().position(|c| *c == o) + && let Some(elem) = Elem::ALL.get(i) + { + return Ok(*elem); + } + Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) } /// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). @@ -757,7 +747,9 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe let src = interp.to_object(&source)?; let src_value = Value::Object(src); let len = length_of(interp, src)?; - let (ta, view) = interp.rooted(std::slice::from_ref(&src_value), |interp| typed_create(interp, &this, len, "from"))?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { for i in 0..len { interp.use_fuel()?; @@ -781,8 +773,10 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe }); let result = gathered.and_then(|()| { let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); - let (ta, view) = typed_create(interp, &this, items.len() as u64, "from")?; + let elem = ctor_elem(interp, &this, "from")?; + let ta = new_typed(interp, elem, items.len() as u64)?; interp.temp_roots.push(Value::Object(ta)); + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; for (i, item) in items.into_iter().enumerate() { interp.use_fuel()?; #[allow(clippy::cast_precision_loss)] @@ -799,10 +793,9 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe /// `%TypedArray%.of(...items)` (section 22.2.2.2). fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - if !interp.is_constructor(&this) { - return Err(interp.type_error("TypedArray.of must be called on a typed array constructor")); - } - let (ta, view) = typed_create(interp, &this, args.len() as u64, "of")?; + let elem = ctor_elem(interp, &this, "of")?; + let ta = new_typed(interp, elem, args.len() as u64)?; + let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; interp.rooted(&[Value::Object(ta)], |interp| { for (i, v) in args.iter().enumerate() { interp.use_fuel()?; diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index a5180291e6..3fe01a3327 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -428,17 +428,10 @@ fn typed_array_methods() { throws("Object.getPrototypeOf(Int8Array).from({get length() { throw new RangeError('first'); }})", "RangeError"); // A receiver that is not a constructor is refused before the source is read (section 22.2.2.1 step 2). throws("Int8Array.from.call(ArrayBuffer.isView, {get length() { throw new RangeError('first'); }})", "TypeError"); - // Any other constructor makes the result (TypedArrayCreate, section 22.2.4.6), which must be a - // typed array with room for every element. - truth( - "var lens = []; function C(n) { lens.push(n); return new Int16Array(n + 1); } \ - var a = Uint8Array.from.call(C, [300, 2]), b = Int8Array.of.call(C, 7), c = Int8Array.from.call(C, 'xy', function (v) { return v.length; }); \ - a instanceof Int16Array && a.join() === '300,2,0' && b.join() === '7,0' && c.join() === '1,1,0' && lens.join() === '2,1,2'", - ); - truth("var B = Int8Array.bind(null); Int8Array.of.call(B, 1, 2).join() === '1,2'"); - throws("Int8Array.from.call(function () { return new Int8Array(1); }, [1, 2])", "TypeError"); - throws("Int8Array.of.call(function () {}, 1)", "TypeError"); - throws("Int8Array.of.call(Math.max, 1)", "TypeError"); + // A constructor that is not a typed array's is refused (AllocateTypedArray, section 22.2.1.2.1), + // a function that returns a typed array and a bound typed array constructor included. + throws("Int8Array.from.call(function () { return new Int8Array(2); }, [1, 2])", "TypeError"); + throws("Int8Array.of.call(Int8Array.bind(null), 1)", "TypeError"); truth("var a = new Int8Array([1, 2]); var b = new Uint8Array(a); b[0] = 9; a[0] === 1 && b.join() === '9,2'"); // A copy to the same element type keeps every bit, a signaling NaN's included. truth( diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 3f15d6adda..b5cf225517 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2594,53 +2594,6 @@ impl Interp { r } - /// Constructs with `f` as `new f(...args)` does (`[[Construct]]`, sections 13.2.2 and - /// 15.3.4.5.2), for a built-in that constructs with a value it is given. - pub(crate) fn construct(&mut self, f: &Value, args: &[Value]) -> JsResult { - if self.reentry >= self.limits.reentry { - return Err(Abrupt::Limit(LimitKind::Reentry)); - } - let saved = self.stack.len(); - self.stack.push(f.clone()); - self.stack.extend(args.iter().cloned()); - self.reentry += 1; - let r = self.construct_rooted(f.clone(), args.to_vec(), saved); - self.reentry -= 1; - self.stack.truncate(saved); - r - } - - fn construct_rooted(&mut self, mut f: Value, mut args: Vec, saved: usize) -> JsResult { - // The bound function on the stack keeps its arguments reachable. - while let Some(Func::Bound { target, args: bound_args, .. }) = self.func_of(&f) { - self.use_fuel()?; - let mut all = bound_args.to_vec(); - all.append(&mut args); - args = all; - f = Value::Object(target); - } - match self.func_of(&f) { - Some(Func::Closure { code, env }) => { - let Some(callee) = f.as_object() else { return internal("callee is not an object") }; - let proto = match self.get_from(callee, &key("prototype"), &f)? { - Value::Object(p) => p, - _ => self.intrinsics.object_proto, - }; - let obj = self.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); - self.stack.truncate(saved); - self.enter_function(Entry { callee, code, env, this: Value::Object(obj), args }, Some(obj), true)?; - self.execute() - } - Some(Func::Native { f: native, constructor: true, .. }) => { - let held = self.held_bytes; - let r = native(self, Value::Undefined, &args, true); - self.held_bytes = held; - r - } - _ => Err(self.type_error("the value is not a constructor")), - } - } - fn call_rooted(&mut self, f: Value, this: Value, args: Vec, saved: usize) -> JsResult { match self.prepare_call(f, this, args)? { Prepared::Done(v) => Ok(v), From abb1fa5f5765caaaf93308175fea5f4b178ddcad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:02:26 -0800 Subject: [PATCH 022/160] JavaScript: typed array toLocaleString looks its method up with the number as receiver %TypedArray%.prototype.toLocaleString invokes each element's method (Invoke, section 7.3.18), so a getter for toLocaleString on Number.prototype now gets the number as this, as the call already does. Array.prototype.toLocaleString keeps the element's object for both. --- crates/js/src/builtins/array.rs | 9 +++++---- crates/js/src/collections_tests.rs | 8 ++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index f4f2a161bc..9b7ca4bfa5 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -340,16 +340,17 @@ fn typed_locale_item(interp: &mut Interp, v: Value) -> JsResult> { locale_call(interp, v, true) } -/// Calls the element's `toLocaleString`, looked up on its object, with the value itself as `this` -/// when `on_value` is true and with the object otherwise. +/// Calls the element's `toLocaleString`, looked up on its object. With `on_value`, the value +/// itself is `this` for the lookup's getter and for the call (Invoke, section 7.3.18); otherwise +/// the object is. fn locale_call(interp: &mut Interp, v: Value, on_value: bool) -> JsResult> { if v.is_nullish() { return Ok(None); } let e = interp.to_object(&v)?; - let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &Value::Object(e))?; - require_callable(interp, &f, "an element's toLocaleString")?; let this = if on_value { v } else { Value::Object(e) }; + let f = interp.get_from(e, &crate::heap::key("toLocaleString"), &this)?; + require_callable(interp, &f, "an element's toLocaleString")?; let s = interp.call(&f, &this, &[])?; interp.to_str(&s).map(Some) } diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index 3fe01a3327..62bf45e03b 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -416,6 +416,14 @@ fn typed_array_methods() { ), "number,number;object" ); + // A getter for the method gets the number as `this` too (Invoke, section 7.3.18). + assert_eq!( + string( + "Object.defineProperty(Number.prototype, 'toLocaleString', {get: function () { 'use strict'; var t = typeof this; \ + return function () { return t; }; }}); new Uint8Array([7]).toLocaleString() + ';' + [7].toLocaleString()" + ), + "number;object" + ); truth( "Object.getPrototypeOf(Int8Array) === Object.getPrototypeOf(Float64Array) && Object.getPrototypeOf(Int8Array.prototype) !== Object.prototype", ); From add7c0f48bf5f4202e58a12c3e1dfe928008202b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:42:05 -0800 Subject: [PATCH 023/160] Toolbars: a toolbar made with New Toolbar holds menu command buttons A toolbar made with Window > Toolbars > New Toolbar held tools only. Its Add Tool... menu now ends in an Add Command submenu that searches every Command Palette result other than a tool (menu commands, plug-in commands, effects and panels); a pick adds a button after the tools, and Remove Command in the same menu lists the buttons by their full names and takes one off. - A button shows its command's label without the ellipsis, on up to two lines, and its full name and shortcut on hover. A click runs what the command's menu item runs, so a command whose item ends in an ellipsis opens its dialog; while the item is dimmed, the button is dimmed and a click runs nothing and the status line says why. - Each command is asked whether it can run once per app state, at most 12 in a frame, and again on a click or a key press. - The button's context menu has Move Up, Move Down and Remove from Toolbar. - The buttons are saved with the toolbar (`commands`, left out when empty, so older layouts load unchanged), and Manage Toolbars' copy keeps them. A command that is gone, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it comes back or is removed. - `toolbar.addCommand {command, toolbar, at?}` adds or moves a button, `toolbar.removeCommand {command, toolbar}` takes one off, and `window.toolbar.list` reports `commands`. `toolbar.reset` with `toolbar` clears them along with the tools. A UI command that fails without params, such as `toolbar.addTool`, is not listed and cannot be added. Not done: dragging a menu item or a Command Palette result onto a toolbar, an Add to Toolbar item in the palette, dragging command buttons to reorder or remove them, and command icons. Command buttons are VectorCraft's own. Docs: docs/control-protocol.md, docs/mcp.md, docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 14 +- crates/ui-egui/src/custom_toolbars.rs | 363 ++++++++++++++++++++++- crates/ui-egui/src/edit_toolbar.rs | 6 +- crates/ui-egui/src/edit_toolbar/tests.rs | 240 ++++++++++++++- crates/ui-egui/src/menus/ui_commands.rs | 14 +- crates/ui-egui/src/palette.rs | 72 ++++- crates/ui-egui/src/palette/search.rs | 11 +- crates/ui-egui/src/shortcut_editor.rs | 10 + crates/ui-egui/src/state.rs | 5 + docs/control-protocol.md | 13 +- docs/mcp.md | 20 ++ docs/target-app-parity.md | 1 + 12 files changed, 748 insertions(+), 21 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..d3fce19fda 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -613,6 +613,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots", ), + ( + "toolbar.addCommand", + "Toolbar: Add Command", + "", + "{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:`, `effect:` or `panel:`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands", + ), + ( + "toolbar.removeCommand", + "Toolbar: Remove Command", + "", + "{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands", + ), ( "toolbar.reset", "Toolbar: Reset", @@ -671,7 +683,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index 2b70748c9c..72edd613ae 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -3,9 +3,12 @@ //! All Tools drawer beside it, and tools dragged from the drawer fill it (`edit_toolbar`, with the //! `toolbar` param of its commands). The + button above it opens Add Tool…, a menu of every tool //! where a click adds the tool at the end, and whose Remove Tool items take tools out: VectorCraft's -//! own way to fill a toolbar without a drag. Its title bar moves it, its × hides it and its double -//! arrow shows its tools in one column or two. Each toolbar is listed under Window › Toolbars, where its -//! item shows or hides it, and is kept with the workspace it was made in (`Workspace::toolbars`). +//! own way to fill a toolbar without a drag. The same menu's Add Command submenu searches the Command +//! Palette's results and adds a command button after the tools, which runs what the command's menu +//! item runs (`toolbar.addCommand`, `toolbar.removeCommand`); command buttons are VectorCraft's own. +//! Its title bar moves it, its × hides it and its double arrow shows its tools in one column or +//! two. Each toolbar is listed under Window › Toolbars, where its item shows or hides it, and is +//! kept with the workspace it was made in (`Workspace::toolbars`). //! Window › Toolbars › Manage Toolbars (also in the drawer's menu) renames, copies and deletes them. //! //! A toolbar docks in a lane along the window's left or right edge (on the left, right of the Tools @@ -42,6 +45,8 @@ use crate::{VectorcraftApp, icons, widgets}; pub(crate) const MAX: usize = 64; /// The most characters a toolbar's name has. const MAX_NAME: usize = 200; +/// The most command buttons a toolbar holds. +const MAX_COMMANDS: usize = 200; /// Width of a toolbar of one column of tool buttons, inside its border. const WIDTH: f32 = 44.0; /// Width a second column of tool buttons adds. @@ -129,6 +134,7 @@ pub(crate) fn create(ui: &mut UiState, name: &str) -> Result { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], }); show_alone_after_tab(ui, name); Ok(name.to_string()) @@ -333,8 +339,10 @@ pub(crate) fn delete(ui: &mut UiState, ctx: Option<&egui::Context>, name: &str) /// Keep named toolbars, each name once whatever its case and at most [`MAX_NAME`] characters, of /// known tools, each once in its toolbar, at a position that is a number, with one strip per group -/// torn off them, each group's tool chosen last only when the group holds it, and the docked ones -/// numbered 0, 1, 2… at each edge (a hand-edited preferences file or workspace). +/// torn off them, each group's tool chosen last only when the group holds it, at most +/// [`MAX_COMMANDS`] command buttons, each command once and none for a tool, and the docked ones +/// numbered 0, 1, 2… at each edge (a hand-edited preferences file or workspace). A command that is +/// not known now stays: it may be an uninstalled plug-in's. pub(crate) fn sanitize(bars: &mut Vec) { let mut names = std::collections::BTreeSet::new(); bars.retain_mut(|b| { @@ -344,6 +352,9 @@ pub(crate) fn sanitize(bars: &mut Vec) { s.retain(|id| tool_info(id).is_some() && seen.insert(id.clone())); } b.slots.retain(|s| !s.is_empty()); + let mut commands = std::collections::BTreeSet::new(); + b.commands.retain(|id| !id.trim().is_empty() && !id.starts_with("tool:") && commands.insert(id.clone())); + b.commands.truncate(MAX_COMMANDS); let slots = &b.slots; b.slot_tool.retain(|first, id| slots.iter().any(|s| s.first() == Some(first) && s.contains(id))); crate::state::FloatingFlyout::sanitize(&mut b.floating); @@ -371,6 +382,41 @@ pub(crate) fn keep_strips(bar: &mut CustomToolbar) { }); } +/// The toolbar the `toolbar` param of `toolbar.addCommand` and `toolbar.removeCommand` names, +/// which must be one made with New Toolbar: the Tools panel's toolbar holds tools only. +fn command_target(ui: &UiState, p: &Value) -> Result { + let name = target(ui, p)?.ok_or("toolbar (a toolbar's name) is required: only toolbars made with New Toolbar hold commands")?; + index(ui, &name) +} + +/// Put the command button for the Command Palette result `id` in `bar`, moving it if it is there +/// already: at place `at` among its command buttons (0 = the first; none: at the end). A command +/// that is gone (an uninstalled plug-in's) can still move, but not be added. A tool, and a UI +/// command that fails without params, can't be added. +pub(crate) fn add_command(bar: &mut CustomToolbar, id: &str, at: Option) -> Result<(), String> { + if id.starts_with("tool:") { + return Err(format!("`{id}` is a tool: toolbar.addTool adds tools")); + } + if crate::shortcut_editor::ui_command_needs_params(id) { + return Err(format!("`{id}` needs params, which a click on a button does not give")); + } + if !bar.commands.iter().any(|c| c == id) && !crate::palette::is_command(id) { + return Err(format!("unknown command `{id}`")); + } + let mut list: Vec = bar.commands.iter().filter(|c| *c != id).cloned().collect(); + if list.len() >= MAX_COMMANDS { + return Err(format!("a toolbar holds at most {MAX_COMMANDS} commands")); + } + let at = match at { + None => list.len(), + Some(n) if n <= list.len() => n, + Some(n) => return Err(format!("`at` must be a whole number from 0 to {} (got {n})", list.len())), + }; + list.insert(at, id.to_string()); + bar.commands = list; + Ok(()) +} + /// The commands of the toolbars made with New Toolbar; `None` for other ids. pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { Some(match id { @@ -464,13 +510,30 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option (|| { + let k = command_target(&app.ui, p)?; + let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?; + let at = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| format!("`at` must be 0 or a larger whole number (got {v})"))?), + }; + let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?; + add_command(bar, id, at).map(|_| json!(bar.commands)) + })(), + "toolbar.removeCommand" => (|| { + let k = command_target(&app.ui, p)?; + let id = p.get("command").and_then(Value::as_str).ok_or("command (a command's id) is required")?; + let bar = app.ui.custom_toolbars.get_mut(k).ok_or("no such toolbar")?; + bar.commands.retain(|c| c != id); + Ok(json!(bar.commands)) + })(), "window.toolbar.list" => Ok(json!( app.ui .custom_toolbars .iter() .map(|b| { let side = if b.dock_right { "right" } else { "left" }; - json!({"name": b.name, "shown": b.shown, "double": b.double, "slots": b.slots, "floating": b.dock.is_none(), "side": side, "order": b.dock}) + json!({"name": b.name, "shown": b.shown, "double": b.double, "slots": b.slots, "commands": b.commands, "floating": b.dock.is_none(), "side": side, "order": b.dock}) }) .collect::>() )), @@ -730,6 +793,130 @@ enum Action { Dock(String, bool), /// Float Toolbar in the title bar's context menu. Float(String), + /// A click on a command button: the Command Palette result it runs. + RunCommand(String), + /// A command picked in the Add Command submenu of Add Tool…'s menu, added at the end of the + /// toolbar named. + AddCommand(String, String), + /// A command button moved to another place among the toolbar's command buttons (Move Up and + /// Move Down in its context menu). + MoveCommand(String, String, usize), + /// A command taken out of the toolbar named: Remove Command in Add Tool…'s menu, or Remove + /// from Toolbar in the button's context menu. + RemoveCommand(String, String), +} + +/// What a command button shows, worked out before its toolbar is drawn. +#[derive(Clone, Debug)] +struct CommandLook { + /// The Command Palette result it runs. + id: String, + /// Its label, name and shortcut; none while the palette lists no result with its id (an + /// uninstalled plug-in's command). + text: Option, + /// Why it can't run now, in English; none while it can. + why: Option, +} + +impl CommandLook { + /// The label the button shows: the command's, or its id while the command is gone. + fn label(&self) -> &str { + self.text.as_ref().map_or(self.id.as_str(), |t| t.label.as_str()) + } + + /// Its full name, with the menu path that tells it apart from a command of the same label, or + /// its id while the command is gone. + fn name(&self) -> &str { + self.text.as_ref().map_or(self.id.as_str(), |t| t.name.as_str()) + } +} + +/// The most commands the toolbars ask in one frame whether they can run. An engine check can take +/// tens of milliseconds on a large selection, and during a drag the state changes on every frame. +const ASKS_PER_FRAME: usize = 12; + +/// The command buttons' [`crate::palette::unavailable`] answers for the state `key` they were read +/// in ([`crate::palette::availability_key`]): each command is asked once per state, and at most +/// [`ASKS_PER_FRAME`] are asked in a frame. A command not asked yet in this state shows its answer +/// from an earlier state (`stale`), or is dimmed when it has none, and is asked in a later frame. +#[derive(Clone, Default)] +struct Known { + key: u64, + why: std::collections::HashMap>, + stale: std::collections::HashMap>, + /// How many more commands this frame may ask. + budget: usize, + /// Is a command still waiting to be asked in this state? + pending: bool, +} + +impl Known { + /// The answers for the state now. The state leaves out a panel shown and a tool chosen, so a + /// frame with a pointer button release or a key press asks every command again, as the Command + /// Palette asks its results again on a click. + fn load(app: &VectorcraftApp, ctx: &egui::Context) -> Known { + let key = crate::palette::availability_key(app); + let mut known = ctx.data(|d| d.get_temp::(known_id())).unwrap_or_default(); + let again = ctx.input(|i| { + i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: true, .. })) + }); + if known.key != key || again { + let old = std::mem::take(&mut known.why); + known.stale.extend(old); + known.key = key; + } + known.budget = ASKS_PER_FRAME; + known.pending = false; + known + } + + /// Why the result `id`, shown as `name`, can't run now, in English, or `None` while it can. + fn why(&mut self, app: &VectorcraftApp, id: &str, name: &str) -> Option { + if let Some(why) = self.why.get(id) { + return why.clone(); + } + if self.budget == 0 { + // Dimmed until it is asked, unless an earlier state's answer is known. + self.pending = true; + return self.stale.get(id).cloned().unwrap_or_else(|| Some(format!("checking whether `{id}` can run"))); + } + self.budget -= 1; + let why = crate::palette::unavailable(app, id, name); + self.stale.remove(id); + self.why.insert(id.to_string(), why.clone()); + why + } +} + +fn known_id() -> egui::Id { + egui::Id::unique("custom-toolbar-command-availability") +} + +/// How many commands have their answer for the state now, and is one still waiting to be asked? +#[cfg(test)] +pub(crate) fn asked(ctx: &egui::Context) -> (usize, bool) { + ctx.data(|d| d.get_temp::(known_id())).map_or((0, false), |k| (k.why.len(), k.pending)) +} + +/// How each command button of `bar` looks now, its answers kept in `known` (read for the current +/// state the first time a toolbar with command buttons is drawn in a frame). +fn command_looks(app: &VectorcraftApp, ctx: &egui::Context, bar: &CustomToolbar, known: &mut Option) -> Vec { + if bar.commands.is_empty() { + return vec![]; + } + let known = known.get_or_insert_with(|| Known::load(app, ctx)); + let native = app.services.native_menu.is_some(); + bar.commands + .iter() + .map(|id| { + let text = crate::palette::is_command(id).then(|| crate::palette::button_text(ctx, native, id)).flatten(); + let why = match &text { + None => Some(format!("command `{id}` is not available right now")), + Some(t) => known.why(app, id, &t.name), + }; + CommandLook { id: id.clone(), text, why } + }) + .collect() } /// The lane along the window's right edge (true) or left edge where docked toolbars show, as last @@ -1001,9 +1188,14 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // Where the drawer opens (the toolbar's bounds and its ••• button): beside the toolbar it // edits, or beside the one whose ••• button was just clicked. let (mut anchor, mut clicked_anchor) = (None, None); + let mut known = None; + let native = app.services.native_menu.is_some(); for k in 0..app.ui.custom_toolbars.len() { let Some(bar) = app.ui.custom_toolbars.get(k).filter(|b| b.shown).cloned() else { continue }; let id = area_id(&bar.name); + let looks = command_looks(app, ctx, &bar, &mut known); + // Add Tool…'s menu lists them under Remove Command and searches the commands it can add. + ctx.data_mut(|d| d.insert_temp(add_menu_id(&bar.name).with("commands"), (native, looks.clone()))); let cols = if bar.double { 2 } else { 1 }; let width = WIDTH + BUTTON * (cols - 1) as f32; // Docked: where its lane puts it, its tools scrolling in its share of the lane, or only its @@ -1137,6 +1329,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); } + // The command buttons, after its tools. + command_buttons(ui, &t, width - 6.0, middle, &bar.name, &looks, &mut actions); ui.add_space(4.0); // Add Tool…: a menu of the tools, which adds one to this toolbar or takes one out. let add = ui.vertical_centered(|ui| widgets::icon_button(ui, "plus", "Add Tool…", false, 26.0)).inner; @@ -1182,6 +1376,13 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } } } + if let Some(known) = known { + // The commands not asked yet are asked in the next frames. + if known.pending { + ctx.request_repaint(); + } + ctx.data_mut(|d| d.insert_temp(known_id(), known)); + } if let Some((bounds, button)) = clicked_anchor.or(anchor) { ctx.data_mut(|d| { d.insert_temp(crate::edit_toolbar::toolbar_id(), bounds); @@ -1245,6 +1446,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { app.status(e); } } + a @ (Action::RunCommand(_) | Action::AddCommand(..) | Action::MoveCommand(..) | Action::RemoveCommand(..)) => command_action(app, a), } } end_move(); @@ -1369,6 +1571,143 @@ pub(crate) fn shown_tool(bar: &CustomToolbar, active: &'static str, tools: &[&'s Some(bar.slot_tool.get(first).and_then(|id| tools.iter().copied().find(|t| t == id)).unwrap_or(first)) } +/// What a press on a command button, its context menu or Add Tool…'s command rows did. +fn command_action(app: &mut VectorcraftApp, a: Action) { + let done = match a { + // It runs what the command's menu item runs, as a pick in the Command Palette does: a + // command whose item ends in … opens its dialog, and a dimmed one runs nothing and the + // status line says why. + Action::RunCommand(id) if crate::palette::is_command(&id) => { + crate::palette::run_pick(app, &id); + Ok(Value::Null) + } + Action::RunCommand(id) => Err(format!("command `{id}` is not available right now")), + Action::AddCommand(name, id) => app.run("toolbar.addCommand", json!({ "command": id, "toolbar": name })), + Action::MoveCommand(name, id, at) => app.run("toolbar.addCommand", json!({ "command": id, "toolbar": name, "at": at })), + Action::RemoveCommand(name, id) => app.run("toolbar.removeCommand", json!({ "command": id, "toolbar": name })), + _ => Ok(Value::Null), + }; + if let Err(e) = done { + app.status(e); + } +} + +/// The command buttons of the toolbar named `bar` (`looks`), one per row across its `width`, with +/// `middle` the toolbar's middle: [`command_button`]. +fn command_buttons(ui: &mut egui::Ui, t: &Tokens, width: f32, middle: f32, bar: &str, looks: &[CommandLook], actions: &mut Vec) { + if looks.is_empty() { + return; + } + ui.add_space(4.0); + for (i, look) in looks.iter().enumerate() { + ui.horizontal(|ui| { + ui.add_space((middle - width / 2.0 - ui.cursor().min.x).max(0.0)); + command_button(ui, t, width, bar, look, (i, looks.len()), actions); + }); + } +} + +/// Height of a command button. +const COMMAND_HEIGHT: f32 = 30.0; + +/// A command button `width` points wide on the toolbar named `bar`: the command's label, on up to +/// two lines and cut short with … when it is longer; its name and shortcut on hover. A click runs +/// the command. While the command can't run now, the button is dimmed and its hover says why. Its +/// context menu moves it up or down among the toolbar's command buttons (`place`: its place and +/// how many there are) and takes it out. +fn command_button(ui: &mut egui::Ui, t: &Tokens, width: f32, bar: &str, look: &CommandLook, place: (usize, usize), actions: &mut Vec) { + let (rect, resp) = ui.allocate_exact_size(vec2(width, COMMAND_HEIGHT), Sense::click()); + let on = look.why.is_none(); + if resp.hovered() || resp.has_focus() { + ui.painter().rect_filled(rect.shrink(1.0), CornerRadius::same(4), t.hover); + } + let color = if on { t.text } else { t.text_disabled }; + let font = egui::FontId::proportional(10.0); + let mut job = egui::text::LayoutJob::simple(look.label().to_owned(), font, color, rect.width() - 4.0); + job.wrap = egui::text::TextWrapping { max_width: rect.width() - 4.0, max_rows: 2, break_anywhere: false, overflow_character: Some('…') }; + job.halign = egui::Align::Center; + let galley = ui.painter().layout_job(job); + ui.painter().galley(pos2(rect.center().x, rect.center().y - galley.size().y / 2.0), galley, color); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, on, look.label())); + let mut tip = look.text.as_ref().map_or(look.id.clone(), |t| t.name.clone()); + if let Some(shortcut) = look.text.as_ref().map(|t| t.shortcut.as_str()).filter(|s| !s.is_empty()) { + tip = format!("{tip} {shortcut}"); + } + if let Some(why) = &look.why { + tip = format!("{tip}\n{}", crate::i18n::msg(why)); + } + let resp = resp.on_hover_text(tip); + if resp.clicked() { + actions.push(Action::RunCommand(look.id.clone())); + } + let (i, n) = place; + resp.context_menu(|ui| { + if widgets::menu_item(ui, tl!("Move Up"), i > 0, false) { + actions.push(Action::MoveCommand(bar.to_string(), look.id.clone(), i.saturating_sub(1))); + ui.close(); + } + if widgets::menu_item(ui, tl!("Move Down"), i + 1 < n, false) { + actions.push(Action::MoveCommand(bar.to_string(), look.id.clone(), i + 1)); + ui.close(); + } + if widgets::menu_item(ui, tl!("Remove from Toolbar"), true, false) { + actions.push(Action::RemoveCommand(bar.to_string(), look.id.clone())); + ui.close(); + } + }); +} + +/// The most commands Add Tool…'s menu lists for a search. +const COMMAND_RESULTS: usize = 30; + +/// Add Tool…'s command rows, for the toolbar named `bar`: under Remove Command the toolbar's +/// command buttons by their full names, which a click takes out, then the Add Command submenu +/// ([`command_search`]). +fn command_section(ui: &mut egui::Ui, t: &Tokens, bar: &str, actions: &mut Vec) { + let Some((native, looks)) = ui.data(|d| d.get_temp::<(bool, Vec)>(add_menu_id(bar).with("commands"))) else { return }; + ui.separator(); + if !looks.is_empty() { + ui.label(egui::RichText::new(crate::i18n::colon(tl!("Remove Command"))).size(12.0).color(t.text_strong)); + for look in &looks { + if widgets::menu_item_name(ui, look.name(), true, false) { + actions.push(Action::RemoveCommand(bar.to_string(), look.id.clone())); + } + } + ui.separator(); + } + // A click in the search field leaves the submenu open; a pick closes the whole menu. + let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + egui::containers::menu::SubMenuButton::new(tl!("Add Command")).config(config).ui(ui, |ui| command_search(ui, t, bar, native, &looks, actions)); +} + +/// The Add Command submenu: a search field over the Command Palette's results other than tools +/// (`native`: with the native menu bar), whose first [`COMMAND_RESULTS`] matches a click adds at +/// the end of the toolbar named `bar` (dimmed: one of its command buttons, `looks`, already). +fn command_search(ui: &mut egui::Ui, t: &Tokens, bar: &str, native: bool, looks: &[CommandLook], actions: &mut Vec) { + widgets::menu_min_width(ui, 260.0); + let q = widgets::search_field(ui, command_query_id(bar), tl!("Search Commands")); + if q.trim().is_empty() { + ui.label(egui::RichText::new(tl!("Type to find a command")).color(t.text_dim)); + return; + } + let found = crate::palette::command_matches(ui.ctx(), native, &q, COMMAND_RESULTS); + if found.is_empty() { + ui.label(egui::RichText::new(tl!("No matching commands")).color(t.text_dim)); + } + for (id, name) in found { + let held = looks.iter().any(|l| l.id == id); + if widgets::menu_item_name(ui, &name, !held, false) { + actions.push(Action::AddCommand(bar.to_string(), id)); + ui.close(); + } + } +} + +/// Where Add Tool…'s menu on the toolbar named `name` keeps the text of its command search field. +pub(crate) fn command_query_id(name: &str) -> egui::Id { + add_menu_id(name).with("query") +} + /// The area of Add Tool…'s menu on the toolbar named `name`. pub(crate) fn add_menu_id(name: &str) -> egui::Id { egui::Id::unique(("custom-toolbar-add", key(name))) @@ -1376,8 +1715,9 @@ pub(crate) fn add_menu_id(name: &str) -> egui::Id { /// Add Tool…'s menu, which the + button on the toolbar `bar` opens: under Remove Tool the tools in /// the toolbar, where a click takes one out; then every tool under the All Tools drawer's headings, -/// where a click adds one at the end (dimmed: in the toolbar already). It scrolls past the window's -/// bottom bars, as other long menus do ([`widgets::menu_scroll`]). +/// where a click adds one at the end (dimmed: in the toolbar already); then its command rows +/// ([`command_section`]). It scrolls past the window's bottom bars, as other long menus do +/// ([`widgets::menu_scroll`]). fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: &mut Vec) { egui::Popup::menu(button).id(add_menu_id(&bar.name)).show(|ui| { widgets::menu_min_width(ui, 200.0); @@ -1401,6 +1741,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & } } } + command_section(ui, t, &bar.name, actions); }); }); } @@ -1480,7 +1821,7 @@ mod tests { let names: Vec<&str> = toolbars_menu(&app).into_iter().filter(|(_, id, _)| *id == "window.toolbar.custom").map(|(l, ..)| l).collect(); assert_eq!(names, ["Mine", "Toolbar 1"]); let list = app.run("window.toolbar.list", json!({})).unwrap(); - let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "floating": true, "side": "left", "order": null}); + let blank = |name: &str| json!({"name": name, "shown": true, "double": false, "slots": [], "commands": [], "floating": true, "side": "left", "order": null}); assert_eq!(list, json!([blank("Mine"), blank("Toolbar 1")])); } @@ -1579,7 +1920,10 @@ mod tests { assert!(app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Nope"})).is_err()); let r = app.run("toolbar.removeTool", json!({"tool": "artboard", "toolbar": "Mine"})).unwrap(); assert_eq!(r, json!([["pen", "curvature"]])); + // Its command buttons go with it. + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); let mine = find(&app.ui, "Mine").cloned().unwrap(); + assert_eq!(mine.commands, ["object.group"]); // Another workspace has its own toolbars (none); coming back brings Mine back. app.run("window.workspace", json!({"name": "Essentials"})).unwrap(); assert!(app.ui.custom_toolbars.is_empty()); @@ -2253,6 +2597,7 @@ mod tests { .iter() .map(|id| crate::state::FloatingFlyout { tools: vec![id.to_string(), "curvature".into()], pos: [0.0, 0.0] }) .collect(), + commands: vec![], }; let long = "x".repeat(MAX_NAME + 1); let mut bars = vec![ diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index 5c1fa8f6ed..9d9d38b09d 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -304,7 +304,11 @@ pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option (|| { if let Some(name) = crate::custom_toolbars::target(&app.ui, p)? { - // A toolbar made with New Toolbar goes back to blank, as it was made. + // A toolbar made with New Toolbar goes back to blank, as it was made, without its + // command buttons too. + if let Some(bar) = crate::custom_toolbars::find_mut(&mut app.ui, &name) { + bar.commands.clear(); + } return edit_custom(app, &name, |cats| { cats.clear(); Ok(()) diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 0973a752b2..5184fdbf36 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -668,7 +668,7 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { let list = app.run("window.toolbar.list", json!({})).unwrap(); assert_eq!( list, - json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]], "floating": true, "side": "left", "order": null}]) + json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]], "commands": [], "floating": true, "side": "left", "order": null}]) ); // A second tool goes after the first. let shown = open(&mut app, 19.0); @@ -891,3 +891,241 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { assert!(slot_of(&app, tool).is_some(), "{tool}"); } } + +/// The command buttons of the toolbar made with New Toolbar called Mine. +fn mine_commands(app: &VectorcraftApp) -> Vec { + crate::custom_toolbars::find(&app.ui, "Mine").unwrap().commands.clone() +} + +/// `toolbar.addCommand` puts command buttons on a toolbar made with New Toolbar and moves them, +/// `toolbar.removeCommand` takes them off, and a bad call changes nothing. Manage Toolbars' copy +/// keeps them, and `toolbar.reset` takes them off with the tools. +#[test] +fn command_buttons_are_added_moved_and_removed_by_their_commands() { + let mut app = app(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let added = app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + assert_eq!(added, json!(["object.group"])); + app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.path.cleanUp", "toolbar": "Mine", "at": 0})).unwrap(); + assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "moved, not added twice"); + for (p, why) in [ + (json!({"command": "no.such", "toolbar": "Mine"}), "an unknown command"), + (json!({"command": "tool:pen", "toolbar": "Mine"}), "a tool"), + (json!({"command": "object.group", "toolbar": "Mine", "at": 2}), "a place past the end"), + (json!({"command": "object.group", "toolbar": "Mine", "at": -1}), "a negative place"), + (json!({"command": "toolbar.addTool", "toolbar": "Mine"}), "a command that needs params"), + (json!({"command": "object.group"}), "no toolbar"), + (json!({"toolbar": "Mine"}), "no command"), + ] { + assert!(app.run("toolbar.addCommand", p.clone()).is_err(), "{why}: {p}"); + assert_eq!(mine_commands(&app), ["object.path.cleanUp", "object.group"], "{why} changes nothing"); + } + assert!(app.run("toolbar.removeCommand", json!({"command": "object.group"})).is_err(), "no toolbar"); + let list = app.run("window.toolbar.list", json!({})).unwrap(); + assert_eq!(list[0]["commands"], json!(["object.path.cleanUp", "object.group"])); + let copy = app.run("window.toolbar.duplicate", json!({"name": "Mine"})).unwrap(); + let copy = copy["toolbar"].as_str().unwrap().to_string(); + assert_eq!(crate::custom_toolbars::find(&app.ui, ©).unwrap().commands, mine_commands(&app), "the copy has them"); + let left = app.run("toolbar.removeCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + assert_eq!(left, json!(["object.path.cleanUp"])); + app.run("toolbar.addTool", json!({"tool": "pen", "toolbar": "Mine"})).unwrap(); + app.run("toolbar.reset", json!({"toolbar": "Mine"})).unwrap(); + assert!(mine_commands(&app).is_empty(), "Reset makes the toolbar blank"); + assert_eq!(crate::custom_toolbars::find(&app.ui, ©).unwrap().commands.len(), 2, "the copy keeps its own"); +} + +/// The text painted inside the toolbar called Mine that starts with `text`: a point inside it and +/// its color. +fn on_mine(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, text: &str) -> Option<(Pos2, Color32)> { + let shown = frame(app, ctx, time, vec![]); + let bar = ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id("Mine")))?; + shown.into_iter().find(|(s, p, _)| s.starts_with(text) && bar.contains(*p)).map(|(_, p, c)| (p, c)) +} + +/// A command button shows its command's label, without the ellipsis, and a click runs what the +/// command's menu item runs. While that item would be dimmed, the button is dimmed too and a click +/// runs nothing. A command whose item ends in … opens its dialog. +#[test] +fn a_command_button_runs_its_command_and_is_dimmed_while_it_cannot() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let t = Tokens::get(&ctx); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + for c in ["object.group", "object.path.cleanUp"] { + app.run("toolbar.addCommand", json!({"command": c, "toolbar": "Mine"})).unwrap(); + } + let undo = |app: &VectorcraftApp| app.session.active().map_or(0, |d| d.history.undo.len()); + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let (at, color) = on_mine(&mut app, &ctx, 0.1, "Group").expect("the button shows Group"); + assert_eq!(color, t.text_disabled, "dimmed with nothing selected"); + let before = undo(&app); + app.ui.status.clear(); + click(&mut app, &ctx, 1.0, at); + assert_eq!(undo(&app), before, "a dimmed button runs nothing"); + assert!(!app.ui.status.is_empty(), "the status line says why"); + app.run("select.all", json!({})).unwrap(); + let (at, color) = on_mine(&mut app, &ctx, 2.0, "Group").expect("the button shows Group"); + assert_eq!(color, t.text, "not dimmed with objects selected"); + click(&mut app, &ctx, 3.0, at); + assert!(undo(&app) > before, "Group ran"); + let (at, _) = on_mine(&mut app, &ctx, 4.0, "Clean Up").expect("the button shows Clean Up"); + assert!(on_mine(&mut app, &ctx, 4.1, "Clean Up…").is_none(), "without the ellipsis"); + assert!(app.ui.dialog.is_none()); + click(&mut app, &ctx, 5.0, at); + assert!(app.ui.dialog.is_some(), "Clean Up… opens its dialog"); +} + +/// Command buttons are kept with the preferences, and a toolbar saved before toolbars held commands +/// loads with none. A command that is gone, such as an uninstalled plug-in's, stays: its button is +/// dimmed and shows its id, a click runs nothing and says so, and Remove Command takes it off. +#[test] +fn a_missing_command_stays_dimmed_until_it_is_removed() { + let mut app = app(); + let ctx = ctx(); + let t = Tokens::get(&ctx); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push("plugin:x".into()); + let kept = app.ui.custom_toolbars.clone(); + let prefs: crate::state::UiState = serde_json::from_slice(&serde_json::to_vec(&app.ui).unwrap()).unwrap(); + assert_eq!(prefs.sanitized().custom_toolbars, kept, "kept with the preferences, the missing command too"); + let mut old = serde_json::to_value(&kept[0]).unwrap(); + old.as_object_mut().unwrap().remove("commands"); + let old: crate::state::CustomToolbar = serde_json::from_value(old).unwrap(); + assert!(old.commands.is_empty(), "an older toolbar loads without commands"); + frame(&mut app, &ctx, 0.0, vec![]); + let (at, color) = on_mine(&mut app, &ctx, 0.1, "plug").expect("the button shows the command's id"); + assert_eq!(color, t.text_disabled); + app.ui.status.clear(); + click(&mut app, &ctx, 1.0, at); + assert!(app.ui.status.contains("plugin:x"), "the status line names it: {}", app.ui.status); + let left = app.run("toolbar.removeCommand", json!({"command": "plugin:x", "toolbar": "Mine"})).unwrap(); + assert_eq!(left, json!(["object.group"])); +} + +/// Add Tool…'s menu lists a toolbar's command buttons under Remove Command, where a click takes one +/// off, and its Add Command submenu searches the menu commands: a click on a match adds its button +/// at the end of the toolbar. +#[test] +fn the_add_tool_menu_adds_and_removes_commands() { + let mut app = app(); + let ctx = ctx(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": "object.group", "toolbar": "Mine"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + frame(&mut app, &ctx, 0.1, vec![]); + // The + button, which moves down as command buttons are added above it. + let plus = || { + let bar = ctx.memory(|m| m.area_rect(crate::custom_toolbars::area_id("Mine"))).expect("the toolbar is shown"); + crate::toolbar::tests::widget_rects(&ctx, vec2(26.0, 26.0)).into_iter().find(|r| bar.contains(r.center())).expect("the + button") + }; + // The menu's text named `name`, opened with a click on the + button unless it is open. + let menu_text = |app: &mut VectorcraftApp, time: f64, name: &str| { + let mut shown = frame(app, &ctx, time, vec![]); + if !shown.iter().any(|(s, ..)| s == "Select:") { + click(app, &ctx, time + 0.2, plus().center()); + frame(app, &ctx, time + 0.5, vec![]); + shown = frame(app, &ctx, time + 0.6, vec![]); + } + let menu = ctx.memory(|m| m.area_rect(crate::custom_toolbars::add_menu_id("Mine")))?; + shown.into_iter().find(|(s, p, _)| s.trim() == name && menu.contains(*p)).map(|(_, p, _)| p) + }; + assert!(menu_text(&mut app, 1.0, "Remove Command:").is_some(), "a heading over the toolbar's commands"); + // The Add Command submenu opens under the pointer and searches as text is typed. + let row = menu_text(&mut app, 2.0, "Add Command").expect("the Add Command row"); + frame(&mut app, &ctx, 3.0, vec![Event::PointerMoved(row)]); + frame(&mut app, &ctx, 3.5, vec![Event::PointerMoved(row)]); + let field = crate::custom_toolbars::command_query_id("Mine").with("edit"); + ctx.memory_mut(|m| m.request_focus(field)); + frame(&mut app, &ctx, 4.0, vec![]); + frame(&mut app, &ctx, 4.1, vec![Event::Text("clean up".into())]); + frame(&mut app, &ctx, 4.2, vec![]); + let shown = frame(&mut app, &ctx, 4.3, vec![]); + let at = shown.iter().find(|(s, ..)| s.trim().ends_with("Clean Up…")).map(|(_, p, _)| *p).expect("Clean Up… is found"); + click(&mut app, &ctx, 5.0, at); + assert_eq!(mine_commands(&app), ["object.group", "object.path.cleanUp"], "added at the end"); + let pen = crate::palette::command_matches(&ctx, false, "pen", 30); + assert!(!pen.is_empty() && pen.iter().all(|(id, _)| !id.starts_with("tool:")), "tools are not listed among the commands: {pen:?}"); + let toolbar = crate::palette::command_matches(&ctx, false, "toolbar add", 30); + assert!(toolbar.iter().all(|(id, _)| id != "toolbar.addTool" && id != "toolbar.addCommand"), "commands that need params: {toolbar:?}"); + // Under Remove Command, Group is listed by its full name, and a click takes it off. + let name = crate::palette::button_text(&ctx, false, "object.group").expect("Group's result").name; + let group = menu_text(&mut app, 10.0, &name).unwrap_or_else(|| panic!("{name} under Remove Command")); + click(&mut app, &ctx, 11.0, group); + assert_eq!(mine_commands(&app), ["object.path.cleanUp"]); +} + +/// A button for a panel shows the panel, as the panel's Command Palette result does. +#[test] +fn a_panel_button_shows_its_panel() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let panel = crate::state::all_panels() + .map(|(id, _)| id) + .find(|id| !crate::panel_docking::visible(&app.ui, id) && crate::palette::is_command(&format!("panel:{id}"))) + .expect("a hidden panel"); + let id = format!("panel:{panel}"); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let label = crate::palette::button_text(&ctx, false, &id).expect("the panel's result").label; + let start: String = label.chars().take(3).collect(); + let (at, _) = on_mine(&mut app, &ctx, 0.1, &start).unwrap_or_else(|| panic!("the button shows {label}")); + click(&mut app, &ctx, 1.0, at); + frame(&mut app, &ctx, 1.5, vec![]); + assert!(crate::panel_docking::visible(&app.ui, panel), "{panel} is shown"); +} + +/// A button for a plug-in's command that is not installed is dimmed and shows the command's id; +/// once the plug-in is installed it shows the plug-in's name and can run, and when the plug-in is +/// removed again it is dimmed again. +#[test] +fn a_plugin_command_button_works_again_when_the_plugin_returns() { + use vectorcraft_plugins::wat as tpl; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + let t = Tokens::get(&ctx); + // A name no other test gives a plug-in. + let filter = "test.UI.toolbar_command-probe"; + let id = format!("plugin:{filter}"); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + crate::custom_toolbars::find_mut(&mut app.ui, "Mine").unwrap().commands.push(id.clone()); + app.run("select.all", json!({})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![]); + let gone = on_mine(&mut app, &ctx, 0.1, "plugin:").map(|(_, c)| c); + let manifest = format!(r#"{{"id":"{filter}","name":"Toolbar Probe","version":"1","kind":"filter","params":{{}}}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + frame(&mut app, &ctx, 1.0, vec![]); + let back = on_mine(&mut app, &ctx, 1.1, "Toolbar").map(|(_, c)| c); + let added = app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine", "at": 0})); + vectorcraft_plugins::registry::remove(filter); + frame(&mut app, &ctx, 2.0, vec![]); + let gone_again = on_mine(&mut app, &ctx, 2.1, "plugin:").map(|(_, c)| c); + assert_eq!(gone, Some(t.text_disabled), "dimmed, with its id, while it is not installed"); + assert_eq!(back, Some(t.text), "its name, and it can run, once it is installed"); + assert!(added.is_ok(), "an installed plug-in's command can be added: {added:?}"); + assert_eq!(gone_again, Some(t.text_disabled), "dimmed again once it is removed"); +} + +/// The toolbars ask only a few command buttons in a frame whether they can run, and the others in +/// the next frames. +#[test] +fn command_buttons_ask_whether_they_can_run_a_few_at_a_time() { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), Default::default()); + let ctx = ctx(); + app.run("window.toolbar.new", json!({"name": "Mine"})).unwrap(); + let ids: Vec = crate::palette::command_matches(&ctx, false, "object", 40).into_iter().map(|(id, _)| id).take(20).collect(); + assert_eq!(ids.len(), 20); + for id in &ids { + app.run("toolbar.addCommand", json!({"command": id, "toolbar": "Mine"})).unwrap(); + } + frame(&mut app, &ctx, 0.0, vec![]); + let (first, waiting) = crate::custom_toolbars::asked(&ctx); + assert!(first < ids.len() && waiting, "{first} asked in the first frame"); + for k in 1..5 { + frame(&mut app, &ctx, f64::from(k), vec![]); + } + assert_eq!(crate::custom_toolbars::asked(&ctx), (ids.len(), false), "every button was asked in the next frames"); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..cd7cb481cc 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -614,6 +614,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{tool: id, group?: bool, toolbar?: name} take `tool` (with `group`, its whole group) out of the current toolbar (with `toolbar`, out of that toolbar made with New Toolbar; one not in it stays out), as dragging it into the Edit Toolbar drawer does; returns the toolbar's slots", ), + ( + "toolbar.addCommand", + "Toolbar: Add Command", + "", + "{command: id, toolbar: name, at?: n} put a button for `command` (a Command Palette result other than a tool: a command's id, or `plugin:`, `effect:` or `panel:`) on the toolbar made with New Toolbar called `toolbar`, after its tools, moving it if it is there already: at place `at` among its command buttons (0 = the first; omitted: at the end), as Add Command in its Add Tool… menu and Move Up and Move Down in the button's context menu do; a click on the button runs what the command's menu item runs; an unknown command, a tool, a command that needs params a click does not give (such as this one) or an `at` past the end is an error and changes nothing; kept with the workspace; returns the toolbar's commands", + ), + ( + "toolbar.removeCommand", + "Toolbar: Remove Command", + "", + "{command: id, toolbar: name} take the button for `command` off the toolbar made with New Toolbar called `toolbar` (one not on it stays off; a command that is no longer installed can be taken off too), as Remove Command in its Add Tool… menu and Remove from Toolbar in the button's context menu do; returns the toolbar's commands", + ), ( "toolbar.reset", "Toolbar: Reset", @@ -672,7 +684,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.toolbar.list", "List Toolbars", "", - "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", + "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, commands, floating, side, order}], `commands` the Command Palette results of its command buttons, `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)", ), ("window.taskBar", "Contextual Task Bar", "", "{}"), ( diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..b103caef50 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -327,6 +327,8 @@ pub(crate) struct Catalog { list: Vec, index: search::Index, ranked: std::sync::Mutex>, + /// Where each id is in `list`. + by_id: std::collections::HashMap, } impl std::ops::Deref for Catalog { @@ -375,7 +377,69 @@ fn catalog(lang: crate::i18n::Lang, native: bool) -> Catalog { // A group's row in the `search` context gives its words in `lang`; a plain row is not read. let search_row = |key: &str| crate::i18n::tr_ctx_row(lang, words::CONTEXT, key).map(str::to_string); let index = search::Index::build(&list, &shown_homes, ¶ms_texts(&list), search_row); - Catalog { list, index, ranked: std::sync::Mutex::new(None) } + let by_id = list.iter().enumerate().map(|(i, e)| (e.id.clone(), i)).collect(); + Catalog { list, index, ranked: std::sync::Mutex::new(None), by_id } +} + +/// What a command button on a toolbar made with New Toolbar shows for the result `id` +/// ([`button_text`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct ButtonText { + /// The result's label in the interface language, without the menu path in front of it and + /// without a closing ellipsis. + pub label: String, + /// The result's full name in the interface language, as the palette lists it. + pub name: String, + /// The shortcut as the menus show it, or empty. + pub shortcut: String, +} + +/// The label and shortcut of the palette result `id` in the interface language, from the entries +/// built once per language, plug-in set and shortcut set (`native`: with the native menu bar); none +/// when the palette lists no result with that id now (an uninstalled plug-in's command). +pub(crate) fn button_text(ctx: &egui::Context, native: bool, id: &str) -> Option { + let entries = entries_in(ctx, crate::i18n::current(), native); + let e = entries.by_id.get(id).and_then(|&i| entries.list.get(i))?; + let label = label_of(e).trim_end(); + let label = label.strip_suffix('…').or_else(|| label.strip_suffix("...")).unwrap_or(label).trim_end(); + Some(ButtonText { label: label.to_string(), name: e.shown.clone(), shortcut: menus::shown_shortcut(&e.shortcut) }) +} + +/// The results a toolbar made with New Toolbar can hold as command buttons that the query `q` +/// matches, best first, at most `most`: the results [`is_command`] allows. Each is its id and its +/// name in the interface language (`native`: as [`button_text`]). +pub(crate) fn command_matches(ctx: &egui::Context, native: bool, q: &str, most: usize) -> Vec<(String, String)> { + let entries = entries_in(ctx, crate::i18n::current(), native); + matching(&entries, q, &[], &CommandUses::default()) + .into_iter() + .filter(|e| is_command(&e.id)) + .take(most) + .map(|e| (e.id.clone(), e.shown.clone())) + .collect() +} + +/// Can a toolbar made with New Toolbar hold the result `id` as a command button now: is it a +/// palette result other than a tool, and not a UI command that fails without params a click does +/// not give ([`crate::shortcut_editor::ui_command_needs_params`]: `toolbar.addTool` needs a +/// `tool`)? The ids are listed again when the plug-ins or the shortcuts change, not on every call. +pub(crate) fn is_command(id: &str) -> bool { + type Ids = ((u64, u64), Arc>); + static IDS: std::sync::Mutex> = std::sync::Mutex::new(None); + if id.starts_with("tool:") { + return false; + } + let key = (menus::plugin_revision(), crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed)); + let kept = IDS.lock().ok().and_then(|ids| ids.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v.clone())); + let ids = kept.unwrap_or_else(|| { + let filters: Vec = crate::shortcut_editor::filter_items().iter().map(|f| format!("plugin:{}", f.id)).collect(); + let ids = drafts().into_iter().map(|d| d.id).filter(|id| !id.starts_with("tool:") && !crate::shortcut_editor::ui_command_needs_params(id)); + let ids: Arc> = Arc::new(ids.chain(filters).collect()); + if let Ok(mut kept) = IDS.lock() { + *kept = Some((key, ids.clone())); + } + ids + }); + ids.contains(id) } /// The params text of each entry's command, which the index reads a description from @@ -531,7 +595,7 @@ pub(crate) enum Picked { /// ([`crate::shortcut_editor::dimmed`]), with the engine's reason when it gives one and `name` in /// place of the command's id. A panel can't be shown in Presentation Mode, a tool can always be /// chosen, and every other result asks about the command its pick runs. -fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { +pub(crate) fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { if id.starts_with("tool:") { return None; } @@ -585,7 +649,7 @@ impl Availability { /// mode, an open dialog, and the background saves and exports, file reads, plug-in runs and traces /// that run or show their progress. A click asks again for what it leaves out (a panel shown, a /// tool chosen) without changing it ([`show`]); typing in the search field does not. -fn availability_key(app: &VectorcraftApp) -> u64 { +pub(crate) fn availability_key(app: &VectorcraftApp) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); crate::native_menu::state_hash(app, None).hash(&mut h); @@ -4016,6 +4080,7 @@ mod tests { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], }; // Window › Tools hides the Tools panel while a toolbar made with New Toolbar holds the Pen // Tool: the row names that toolbar. @@ -5301,6 +5366,7 @@ mod tests { slot_tool: Default::default(), double: false, floating: vec![], + commands: vec![], } } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index ed49600660..adad0d4e4e 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -1004,7 +1004,7 @@ mod tests { /// `entries` with their index, the params text of each in `params`. fn described(entries: Vec, params: &[&str]) -> Catalog { let index = Index::build(&entries, &[], params, |_| None); - Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) } + Catalog { list: entries, index, ranked: std::sync::Mutex::new(None), by_id: Default::default() } } /// Where `id` is among the results of `query`. @@ -1464,7 +1464,7 @@ mod tests { #[test] fn without_an_index_only_the_substring_rule_matches() { let entries = vec![entry("Remove Background…", "a.one"), entry("Zz Group", "b.two")]; - let c = Catalog { list: entries, index: Index::default(), ranked: std::sync::Mutex::new(None) }; + let c = Catalog { list: entries, index: Index::default(), ranked: std::sync::Mutex::new(None), by_id: Default::default() }; assert!(ranked(&c, "mov.nd").is_empty(), "{:?}", ranked(&c, "mov.nd")); assert_eq!(ranked(&c, "background mov"), ["a.one"]); } @@ -1519,7 +1519,12 @@ mod tests { fn a_catalog_row_adds_words_to_a_group() { let entries = || vec![entry("Zz Delete", "a.one")]; let row = |key: &str| (key == "remove, delete, erase, clear").then(|| "Entfernen, ganz weg, text".to_string()); - let with = Catalog { list: entries(), index: Index::build(&entries(), &[], &[], row), ranked: std::sync::Mutex::new(None) }; + let with = Catalog { + list: entries(), + index: Index::build(&entries(), &[], &[], row), + ranked: std::sync::Mutex::new(None), + by_id: Default::default(), + }; assert_eq!(ranked(&with, "entfernen"), ["a.one"]); assert!(ranked(&with, "ganz weg").is_empty(), "two words are left out"); assert!(ranked(&with, "text").is_empty(), "text stays in its own group"); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a9d7b022a7..c4bfb9f835 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -991,6 +991,16 @@ fn a_menu_bar_item_runs(id: &str, params: &str) -> bool { || menu_target(id).is_some_and(|(target, _)| target != id || !names_a_required_field(params)) } +/// Is `id` a UI command that fails when it runs with no params: its params doc names a field a call +/// must give, no item of the menu bar runs it ([`a_menu_bar_item_runs`]), and a key press does not +/// run it on its own ([`ui_listed_on_its_own`])? `toolbar.addTool` needs a `tool`. +pub(crate) fn ui_command_needs_params(id: &str) -> bool { + crate::menus::UI_COMMANDS + .iter() + .find(|c| c.0 == id) + .is_some_and(|c| names_a_required_field(c.3) && !a_menu_bar_item_runs(c.0, c.3) && !ui_listed_on_its_own(c.0, c.2, c.3)) +} + /// Is engine command `c` listed in Edit › Keyboard Shortcuts whether or not an item of the menu bar /// runs it? A command with a menu path of its own is. One without (a panel menu item) is when a key /// alone can run it: it has a default key, or it is an undoable command, not an alias, whose params diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index f8bce4e088..a2284e3b6f 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1087,6 +1087,11 @@ pub struct CustomToolbar { /// The groups torn off it, each floating as its own strip; they show while it does. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub floating: Vec, + /// Its command buttons, after its tools: Command Palette result ids (a command's id, or + /// `plugin:`, `effect:` or `panel:` and an id). A command that is gone, such as an uninstalled + /// plug-in's, is kept and shows as unavailable until it comes back. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub commands: Vec, } /// A category of an edited toolbar: its name (one of the Basic toolbar's; none in the Advanced diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..6d2998e113 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -479,8 +479,17 @@ toolbars Tab hid are turned off. A toolbar's ••• button button (Add Tool…) opens a menu of every tool under the drawer's headings: a click on a tool runs `toolbar.addTool {tool, toolbar}`, which puts it at the end, and the tools under its Remove Tool heading run `toolbar.removeTool {tool, toolbar}`; the tools already in the toolbar are dimmed under their headings. The drawer has no Show section -there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with -it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag, +there. The same menu's Add Command submenu searches the Command Palette's results other than tools, and a pick runs +`toolbar.addCommand {command, toolbar}`, which puts a command button at the end of the toolbar, after its tools; +`toolbar.addCommand {command, toolbar, at}` moves one to place `at` among the command buttons (Move Up and Move Down +in the button's context menu), and `toolbar.removeCommand {command, toolbar}` takes one off (Remove Command in the +menu, Remove from Toolbar in the context menu). `command` is a palette result's id: a command's id, or +`plugin:`, `effect:` or `panel:`. A click on the button runs what the command's menu item runs, and the +button is dimmed while that item is. An unknown command, a tool, a command that needs params a click does not give +(`toolbar.addTool`), a place past the end or a missing `toolbar` is an error and changes nothing. A command that is +no longer installed keeps its button, dimmed, and `toolbar.removeCommand` still takes it off. +`window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with it. +`window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, commands, shown flag, two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked). `window.toolbar.dock {name, side?, order?}` docks a toolbar in the lane along the window's left or right edge, and `window.toolbar.float {name, x?, y?}` floats it again; dropping its title bar on an edge or dragging it out of its diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..bcdbcab44c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3678,6 +3678,26 @@ own layout rules. {"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} ``` +## Command buttons on toolbars made with New Toolbar + +A toolbar made with New Toolbar holds command buttons after its tools. `toolbar.addCommand {command, toolbar, at?}` +(Add Command in the toolbar's Add Tool… menu, remote mode, `invoke_menu`) puts a button for `command` on the toolbar +named `toolbar`, or moves the button when the toolbar has it already: at place `at` among its command buttons, 0 for +the first, or at the end without `at`. `command` is a Command Palette result's id: a command's id, or +`plugin:`, `effect:` or `panel:`. `toolbar.removeCommand {command, toolbar}` takes a button off. Both +answer with the toolbar's command buttons, and `window.toolbar.list` reports `commands` for each toolbar. An unknown +command, a tool, a command that needs params a click does not give (`toolbar.addTool`), an `at` past the end or a +missing `toolbar` is an error and changes nothing. A click on a button runs what the command's menu item runs, so a +command whose item ends in … opens its dialog, and the button is dimmed while that item is. A command that is no +longer installed, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it is +installed again or removed. `toolbar.reset {toolbar}` takes the buttons off with the tools. The buttons are kept with +the workspace, and toolbars saved before command buttons existed load without any. Command buttons are VectorCraft's +own. + +```json +{"name":"invoke_menu","arguments":{"command":"toolbar.addCommand","params":{"command":"object.group","toolbar":"Toolbar 1"}}} +``` + ## Help search Help › VectorCraft Help… and F1 show the Help panel. `help.discover {query?}` opens it without diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..7c0e29b42d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1132,6 +1132,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The dock's double arrow collapses Properties, Layers and Libraries to icons at the top of the icon column, popping out like the other icon panels, and expands them again (`window.collapseDock`, kept with the preferences and in saved workspaces). The icon column's own arrow (expanding the icon panels into a full column) is not done. - Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`). - A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`). + - A toolbar made with New Toolbar also holds command buttons, after its tools. The Add Command submenu at the end of its Add Tool… menu searches every Command Palette result other than a tool (menu commands, plug-in commands, effects and panels), and a pick adds a button at the end; Remove Command in the same menu lists the buttons and takes one off. A button shows its command's label without the ellipsis, on up to two lines, and its full name and shortcut on hover. A click runs what the command's menu item runs, so a command whose item ends in … opens its dialog. While that item is dimmed the button is dimmed and runs nothing. The button's context menu has Move Up, Move Down and Remove from Toolbar. The buttons are kept with the toolbar in the workspace, Manage Toolbars' copy keeps them, and a toolbar saved without them loads unchanged. A command that is gone, such as an uninstalled plug-in's, keeps its button, dimmed and labeled with its id, until it comes back or is removed. Not done: dragging a menu item or a Command Palette result onto a toolbar, an Add to Toolbar item in the palette, dragging command buttons to reorder or remove them, and command icons (a button shows its label). Command buttons are VectorCraft's own (`toolbar.addCommand`, `toolbar.removeCommand`; `command_buttons_are_added_moved_and_removed_by_their_commands`, `a_command_button_runs_its_command_and_is_dimmed_while_it_cannot`, `a_missing_command_stays_dimmed_until_it_is_removed`, `a_plugin_command_button_works_again_when_the_plugin_returns`, `a_panel_button_shows_its_panel`, `command_buttons_ask_whether_they_can_run_a_few_at_a_time`, `the_add_tool_menu_adds_and_removes_commands`). - Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`). - In the All Tools drawer a tool the toolbar holds is drawn throughout — name, shortcut and icon — in the dim text colour, one step dimmer than a tool not in it, so it still reads as in the toolbar while its name stays readable against the panel; the disabled colour it was drawn in before was about 2.6:1 on the panel, unreadable at the drawer's 12.5 px (#8294; `tools_in_the_toolbar_are_dimmed_in_the_drawer` in `crates/ui-egui/src/edit_toolbar/tests.rs`, which asserts the painted colour's contrast). The dimming is VectorCraft's own (#1018). - A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`). From 82e3d6dac34458445d9bf5511a55957a323e2294 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 09:11:54 -0800 Subject: [PATCH 024/160] 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 @@ + +