From 3cbe61a6d0e23bc9e28c3d3ebcf09ec2bc833f6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 05:55:50 -0800 Subject: [PATCH 01/13] MCP: ui.menuDialog's params text names the dialog keys ui.inspect reports Since the move to the craft UI framework, the dialogs ui.menuDialog opens report their command id as their `key` in ui.inspect and ui.dialog, except Transform Each and the envelope dialogs. The params text, docs/mcp.md and docs/control-protocol.md still named the earlier kinds (`move`, `scale`, `vectorHalftone`, `rearrangeArtboards`, `renameArtboards`, `arrangeGrid`, `divideDashes`, `smoothBridge`, `tangentCircle`, `textTweaker`, `command` and others), which no dialog reports. - The params text of ui.menuDialog (and its copy in the MCP catalog) says the key is the command id and names the four exceptions, and says Smooth, and Simplify until its dialog keeps its settings, show a slider rather than a dialog. ui.simplifyAuto and ui.simplifyMoreOptions name the Simplify dialog's key `object.path.simplify`. - The params text of tool.options names the keys of the dialogs the Rotate, Scale, Reflect, Shear, selection and Type on a Path tools open: `object.rotate`, `object.scale`, `object.reflect`, `object.shear`, `object.move` and `type.pathOptions`. - docs/mcp.md and docs/control-protocol.md name the keys the dialogs report, Type on a Path Options and Rasterize included. - Tests open every command the ui.menuDialog params text lists, each of those tools' options and Simplify's More Options, and check the key against the params text, and that every key the ui.menuDialog text names is one a listed command opens. --- crates/mcp/src/ui_catalog.rs | 8 +- crates/ui-egui/src/dialogs/tests.rs | 110 ++++++++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 8 +- docs/control-protocol.md | 18 ++-- docs/mcp.md | 18 ++-- 5 files changed, 136 insertions(+), 26 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..3fe2e6b0e4 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (its `key` in ui.inspect and ui.dialog is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, and `envelopeOptions` for object.envelope.options; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", @@ -1549,7 +1549,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyAuto", "Auto-Simplify", "", - "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", ), ( "ui.smoothAuto", @@ -1561,7 +1561,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyMoreOptions", "More Options", "", - "{} the Simplify dialog (dialog `simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", + "{} the Simplify dialog (dialog `object.path.simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", ), ( "ui.dialogReset", diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index c45284ba5a..8b01a622ae 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1003,3 +1003,113 @@ fn a_failed_tool_choice_restores_the_brush_key_color_initiator() { assert_eq!(app.session.tool_id(), "rectangle", "Cancel must preserve the successful replacement"); assert_eq!(unchanged(&app), before); } + +/// The `key` of each dialog `ui.inspect` lists, bottom first. +fn dialog_keys(app: &VectorcraftApp) -> Vec { + let ctx = app.ui_ctx.clone().expect("a window app"); + let ui = crate::control::inspect(app, &ctx); + ui["dialogs"].as_array().into_iter().flatten().filter_map(|d| d["key"].as_str().map(str::to_string)).collect() +} + +/// A drawing every dialog `ui.menuDialog` lists can open on: two artboards and two selected rectangles, the first a +/// crease, and for `command` a selected envelope when Reset or Envelope Options needs one. +fn menu_dialog_app(command: &str) -> VectorcraftApp { + let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200, "artboards": 2})).unwrap(); + let crease = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run(crate::addons::packaging::SET_ROLE, json!({"role": "crease", "ids": [crease]})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let envelope = match command { + "object.envelope.resetWithWarp" | "object.envelope.options" => Some("object.envelope.makeWithWarp"), + "object.envelope.resetWithMesh" => Some("object.envelope.makeWithMesh"), + _ => None, + }; + if let Some(make) = envelope { + app.session.execute(make, &json!({})).unwrap(); + } + app +} + +/// The part of `doc` after `start`, up to the first of `ends`; empty when `doc` does not have `start`. +fn clause<'a>(doc: &'a str, start: &str, ends: &[char]) -> &'a str { + let Some(at) = doc.find(start) else { return "" }; + let rest = &doc[at + start.len()..]; + &rest[..rest.find(ends).unwrap_or(rest.len())] +} + +/// Whether `clause` names command `id` as a word of its own. +fn names(clause: &str, id: &str) -> bool { + clause.split([' ', ',']).any(|word| word == id) +} + +/// Each command `ui.menuDialog`'s params text lists opens the dialog that text names, by the `key` `ui.inspect` and +/// `ui.dialog` report: the command id unless the text names another key for that command, and no dialog for the +/// commands the text says show a slider. Every key the text names is one a listed command opens. +#[test] +fn menu_dialog_opens_the_dialog_keys_its_params_text_names() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.menuDialog").expect("registered").3; + let list = doc.strip_prefix("{command: ").and_then(|rest| rest.split_once('}')).expect("a command list").0; + let sliders = clause(doc, "not a dialog, for ", &[';']); + let mut opened = Vec::new(); + for id in list.split('|') { + let mut app = menu_dialog_app(id); + app.run("ui.menuDialog", json!({"command": id})).unwrap_or_else(|e| panic!("{id}: {e}")); + settle(&mut app); + let keys = dialog_keys(&app); + match keys.last() { + None => assert!(names(sliders, id), "{id} opens no dialog, and the params text does not say it shows a slider"), + Some(key) if key == id => assert!(!names(sliders, id), "{id} opens a dialog, and the params text says it shows a slider"), + Some(key) => assert!( + names(clause(doc, &format!("`{key}` for "), &[',', ';']), id), + "{id} opens `{key}`, which the params text does not name for it" + ), + } + opened.extend(keys); + } + let except = clause(doc, "is the command id, except ", &[';']); + for named in except.split('`').skip(1).step_by(2) { + assert!(opened.iter().any(|key| key == named), "the params text names `{named}`, which no listed command opens"); + } + // Simplify opens its dialog, under its command id, once OK in that dialog has kept the settings. + let mut app = menu_dialog_app("object.path.simplify"); + let ctx = app.ui_ctx.clone().expect("a window app"); + craft::ui::runtime::memory::set_saved_value(&ctx, &super::path_ops::SIMPLIFY_KEY, Some(craft::ui::patterns::form_dialogs::DialogFields::new())); + app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap(); + settle(&mut app); + assert_eq!(dialog_keys(&app), ["object.path.simplify"]); +} + +/// The transform, selection and Type on a Path tools' `tool.options` open dialogs whose `key` its params text names. +#[test] +fn tool_options_opens_the_dialog_keys_its_params_text_names() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "tool.options").expect("registered").3; + for tool in ["rotate", "scale", "reflect", "shear", "selection", "directSelection", "groupSelection", "typeOnPath", "verticalTypeOnPath"] { + let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + if tool.ends_with("OnPath") { + let text = app.session.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap(); + app.session.execute("select.set", &json!({"ids": [text["id"]]})).unwrap(); + } + app.run("tool.options", json!({"tool": tool})).unwrap_or_else(|e| panic!("{tool}: {e}")); + settle(&mut app); + let keys = dialog_keys(&app); + let key = keys.last().unwrap_or_else(|| panic!("{tool} opens no dialog")); + assert!(doc.contains(&format!("`{key}`")), "{tool} opens `{key}`, which the tool.options params text does not name"); + } +} + +/// More Options on the Simplify slider opens the dialog whose `key` the ui.simplifyMoreOptions params text names. +#[test] +fn simplify_more_options_opens_the_dialog_key_its_params_text_names() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.simplifyMoreOptions").expect("registered").3; + let mut app = menu_dialog_app("object.path.simplify"); + app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap(); + settle(&mut app); + app.run("ui.simplifyMoreOptions", json!({})).unwrap(); + settle(&mut app); + let keys = dialog_keys(&app); + let key = keys.last().expect("More Options opens a dialog"); + assert!(doc.contains(&format!("(dialog `{key}`")), "More Options opens `{key}`, which its params text does not name"); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..6afceabb91 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1193,7 +1193,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (its `key` in ui.inspect and ui.dialog is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, and `envelopeOptions` for object.envelope.options; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", ), ( "ui.widthPointEdit", @@ -1550,7 +1550,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyAuto", "Auto-Simplify", "", - "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", ), ( "ui.smoothAuto", @@ -1562,7 +1562,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyMoreOptions", "More Options", "", - "{} the Simplify dialog (dialog `simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", + "{} the Simplify dialog (dialog `object.path.simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", ), ( "ui.dialogReset", diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df9b36eee8..e8d5c92ab6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -194,8 +194,8 @@ for `eyedropper` it opens Eyedropper Options, an `eyedropperOptions` dialog (fie `apply`, the attribute trees of `eyedropper.setOptions`) whose `ui.dialog.confirm` runs `eyedropper.setOptions` (what `appearance.copyFrom` copies). For `hand` it fits the artboard in the window (`view.fitArtboard`) and for `zoom` it shows 100% (`view.actualSize`). For `rotate`, `scale`, `reflect` and `shear` it opens the same dialog as Object › -Transform (dialog kind = the tool id), or fails with `nothing selected`. For `selection`, `directSelection` and -`groupSelection` it opens the Move dialog (kind `move`), with the same failure; Move opens on the offset of the last +Transform (dialog key `object.`, such as `object.rotate`), or fails with `nothing selected`. For `selection`, `directSelection` and +`groupSelection` it opens the Move dialog (key `object.move`), with the same failure; Move opens on the offset of the last drag or Move (`dx`, `dy`) and with the `copy`, `objects` and `preview` it was last confirmed with (its `patterns` is the `transformPatternTiles` preference, which its OK sets). `ui.key` Enter with one of those seven tools opens its dialog too (nothing happens without a selection), with the transform tools' `origin` at their reference @@ -203,8 +203,8 @@ point. For `lineSegment`, `arc`, `rectangularGrid` and `polarGrid` it opens the click opens (kind = the tool id), without `x` and `y` and with `__toolOptions: true`, whose `ui.dialog.confirm` runs `tool.setOption {tool, values}` and draws nothing; the next drag with the tool and its click dialog use the values (the line's `fillLine`, the grids' Default Size `width`, `height` and `reference` too). For `typeOnPath` and -`verticalTypeOnPath` it opens Type on a Path Options for the selected type on a path (a `command` dialog running -`type.pathOptions`), or fails when no type on a path is selected. Gradient tool handles snap to +`verticalTypeOnPath` it opens Type on a Path Options for the selected type on a path (dialog key +`type.pathOptions`, which runs that command), or fails when no type on a path is selected. Gradient tool handles snap to anchors, edges and smart guides; Shift constrains them to 45° steps from the `constrainAngle` preference. Effect dialogs: `engine.execute {command: "effect.dialog", params: {effect, index?, item?}}` opens the `effect` dialog @@ -637,9 +637,9 @@ Spot Colors: the Swatches panel menu's Spot Colors… (`ui.spotColors`) opens th true shows and separates spot colours defined in Lab from their Lab values, false from their working-CMYK equivalents); `ui.dialog.confirm` runs `swatch.spotOptions {useLab}` as one undo step. -Scale options: `ui.menuDialog {command}` opens the dialog a command's menu item opens (`object.scale` → `scale`, +Scale options: `ui.menuDialog {command}` opens the dialog a command's menu item opens (`object.scale` → `object.scale`, `object.transformEach` → `transformEach`, also Move, Rotate, Reflect, Shear and the Path dialogs). The Scale dialog -(`scale`) and Object → Transform → Transform Each… (dialog `transformEach`: `scaleH`, +(`object.scale`) and Object → Transform → Transform Each… (dialog `transformEach`: `scaleH`, `scaleV` %, and `absH`, `absV` pt, the width and height each object becomes with `relative` false, absent while they read "Mixed"; `moveH`, `moveV` pt, `rotate` °, `reflectX`, `reflectY`, `random`, `reference` 0–8, `copy`, `preview`) have the fields `corners` (Scale Corners) and `strokes` (Scale Strokes & Effects). They start from the preferences @@ -768,8 +768,8 @@ stays open. Document Raster Effects Settings: Effect → Document Raster Effects Settings… (`ui.rasterEffectsSettingsDialog` for agents) opens the `rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports (`resolution`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround` in pt, `preserveSpotColors`); -`ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens a -`command` dialog for `object.rasterize` whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`, +`ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens the +`object.rasterize` dialog, whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround`) start from these settings. `colorModel`, `antiAlias` (`none`, `art`, `type`) and `background` (`white`, `transparent`) are dropdowns; `ui.dialog.set` also takes any other value the command takes, and the dialog sends it unchanged. @@ -1074,7 +1074,7 @@ Colour adjustment effects (Effect → Color Adjustments) open the `effect` dialo `channel` for Curves and Levels, `points` for Curves, `color` for Shift to Color) and they preview live; set them with `ui.dialog.set` and `ui.dialog.confirm` to apply (Curves also has a graph: drag its points). Object → Vector Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "object.vectorHalftone"}}`) opens the -`vectorHalftone` dialog (fields `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal`, +`object.vectorHalftone` dialog (fields `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal`, `preview`): it previews live and `ui.dialog.confirm` keeps the halftone as one undo step. Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..e04d026dc8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10884,7 +10884,7 @@ Artboard tool has selected, else its active one. One artboard takes `name`, trim order, `name-1`, `name-2` and so on. A locked artboard is renamed too. An empty name fails with `` `name` must not be empty ``, a name that is not a string fails with `` `name` must be a string ``, and an artboard that is not in the document fails with `no such artboard`. When every artboard already has its new name, the command -records no undo step → `{renamed: [index…]}`. With no params, a menu click opens the `renameArtboards` dialog (fields +records no undo step → `{renamed: [index…]}`. With no params, a menu click opens the `artboard.rename` dialog (fields `name` and `indices`), and OK with an empty name changes nothing. The Artboards panel's name field runs this command too. Switch Orientation: `artboard.switchOrientation {index? | indices?, scaleArt?, patterns?, lockedAndHidden?}` swaps the width and height of each @@ -10989,7 +10989,7 @@ The reply adds `indices` and `moved`, the number of artboards that moved; with n locked, or already in place) no undo step is recorded. Without `indices` the command lays out every artboard, and its reply is `{artboards, rows, columns}`; `at` there puts the grid's top-left at `at` too. In the desktop app, the Artboard tool's canvas menu and Contextual Task Bar (Rearrange), and while the Artboard tool is in use the Artboards -panel's menu (Rearrange…), open the Rearrange dialog (kind `rearrangeArtboards` with field `indices`) for the +panel's menu (Rearrange…), open the Rearrange dialog (key `artboard.rearrange` with field `indices`) for the artboards the tool has selected, showing their count. With another tool Rearrange… is off. The panel's Rearrange button stays Rearrange All Artboards. Its OK changes nothing yet: the grid's outline follows the pointer, and the next press on the canvas runs `artboard.rearrange` with `indices` and `at` at the press, as one undo step. Enter, when @@ -16686,7 +16686,7 @@ Commands: With `fit`, every run between corners and ends holds a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path with no corner holds whole periods); otherwise the lengths are exact and the last piece of each run is what is left. The pieces are selected; more than 100,000 is refused. → `{ids, dashes}`. - Divide into Dashes… opens a dialog (`ui.menuDialog {command}`, kind `divideDashes`) whose fields are these + Divide into Dashes… opens a dialog (`ui.menuDialog {command}`, key `addon.pathtools.divideDashes`) whose fields are these parameters, with Preview. - `addon.pathtools.expandDashes {ids?}` turns the dashed stroke of each path and compound path under `ids` (default: the selection) into separate open paths, one per dash, as one undo step (Object › Plug-ins › Path Precision Tools › @@ -16725,7 +16725,7 @@ Commands: reach has one circle inside the other, when no pair within reach can be bridged (suggesting a larger radius or gap only when the largest would bridge a pair of them under these rules), when no two circles are within reach, and above 2,000 circles or 8,000 bridges. → `{ids, alone}`: the shapes and the circles left as they are, with `id` as well for two circles. Smooth Bridge… opens a dialog - (`ui.menuDialog {command}`, kind `smoothBridge`) with Constant Gap (a Gap field in place of the Radius field in + (`ui.menuDialog {command}`, key `addon.pathtools.bridge`) with Constant Gap (a Gap field in place of the Radius field in percent), Reach (unavailable with two circles selected), Keep Originals and Preview. - `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so @@ -16745,7 +16745,7 @@ Commands: circles), when `circle` is past the last one, when `ids` names an object twice, when the shapes lie at one point or are too small for the radius, above 2,000 segments in all, and when the search for other shapes goes past its limits. → `{ids, found}` (`found`: how many circles touch the shapes). Tangent Circle… opens a dialog - (`ui.menuDialog {command}`, kind `tangentCircle`) with the radius (used with two shapes selected; 36 pt to start), a + (`ui.menuDialog {command}`, key `addon.pathtools.tangentCircle`) with the radius (used with two shapes selected; 36 pt to start), a Circle menu (All, or one circle by number, as many as the last preview found) and Preview, which starts on. - `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?, every?, minAngle?, maxAngle?}` cuts live corners, the ones Direct Selection's corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and @@ -17445,7 +17445,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs -(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose +(`ui.menuDialog {command}`; each dialog's `key` is its command id, such as `addon.arrange.grid`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. ```json @@ -17641,7 +17641,7 @@ are skipped as `addon.packaging.setRole` skips them; cut lines and objects witho command fails when the objects hold no Crease, Partial Cut or Perforation line it can change, and with an angle outside the range or one that is not a number. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`. -Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, kind `command`) on the +Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, key `addon.packaging.setFoldAngle`) on the angle that the selected lines it can change fold at (90° when they differ), shown with every decimal place it has. While the selection holds no such line, `ui.menuDialog` fails with the reason the command gives. While the selection holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it as it is typed, as one undo step; canceling the edit restores the lines' angles and leaves no undo step. The Reset button beside it takes their own angles away. @@ -17830,8 +17830,8 @@ A `start` or `end` byte inside a character rounds down to that character's start | `seed` | whole number (0): `random` with the same seed and text gives the same values | | `skipSpaces` | true: spaces and line breaks keep their values and don't count | -→ `{count (characters changed), ids}`. Text Tweaker… opens a dialog (`ui.menuDialog {command}`, dialog kind -`textTweaker`) whose fields are the command's parameters, with Preview; another attribute starts from its own +→ `{count (characters changed), ids}`. Text Tweaker… opens a dialog (`ui.menuDialog {command}`, dialog key +`addon.type.textTweaker`) whose fields are the command's parameters, with Preview; another attribute starts from its own default values, and the seed starts new whenever the document has changed. ```json From 7eda2320dcf911cb9666f0084be7cc19ccb32559 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:57:21 -0800 Subject: [PATCH 02/13] MCP: ui.menuDialog's params text lists every command whose dialog it opens The params text of ui.menuDialog (and its copy in the MCP catalog) did not list the add-on and other commands whose dialogs ui.menuDialog also opens: Set Corners, Divide into Dashes, Bridge, Tangent Circle, Text Tweaker, Color Legend, `addon.arrange.randomizeOpacity`, `addon.arrange.sort`, Color Nearest, Select by Artboards, `type.smartPunctuation`, and the variable and data set dialogs. - The list now names those commands. The text says the variable and data set dialogs report the key `variables`, that the Color Nearest and Select by Artboards dialogs have no `key`, when Rename Variable, Set Data Set and Rename Data Set open, and that ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id`. - A test runs ui.menuDialog for every command and fails when one opens a dialog that the params text does not list. The key test compares each dialog's key with the key the params text gives for its command. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 91 ++++++++++++++++++++----- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 3 files changed, 77 insertions(+), 18 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 3fe2e6b0e4..b0d3bba69c 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (its `key` in ui.inspect and ui.dialog is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, and `envelopeOptions` for object.envelope.options; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 8b01a622ae..0a44ffdeef 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1011,6 +1011,13 @@ fn dialog_keys(app: &VectorcraftApp) -> Vec { ui["dialogs"].as_array().into_iter().flatten().filter_map(|d| d["key"].as_str().map(str::to_string)).collect() } +/// The `key` of each dialog `ui.inspect` lists, bottom first, `None` for a dialog without one. +fn dialog_entries(app: &VectorcraftApp) -> Vec> { + let ctx = app.ui_ctx.clone().expect("a window app"); + let ui = crate::control::inspect(app, &ctx); + ui["dialogs"].as_array().into_iter().flatten().map(|d| d["key"].as_str().map(str::to_string)).collect() +} + /// A drawing every dialog `ui.menuDialog` lists can open on: two artboards and two selected rectangles, the first a /// crease, and for `command` a selected envelope when Reset or Envelope Options needs one. fn menu_dialog_app(command: &str) -> VectorcraftApp { @@ -1019,18 +1026,25 @@ fn menu_dialog_app(command: &str) -> VectorcraftApp { let crease = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 60, "height": 20})).unwrap(); app.run(crate::addons::packaging::SET_ROLE, json!({"role": "crease", "ids": [crease]})).unwrap(); + // A variable and a data set, for the dialogs that edit one. + app.session.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap(); + app.session.execute("dataset.new", &json!({"name": "Row"})).unwrap(); app.run("select.all", json!({})).unwrap(); - let envelope = match command { - "object.envelope.resetWithWarp" | "object.envelope.options" => Some("object.envelope.makeWithWarp"), - "object.envelope.resetWithMesh" => Some("object.envelope.makeWithMesh"), - _ => None, - }; - if let Some(make) = envelope { + if let Some(make) = envelope_for(command) { app.session.execute(make, &json!({})).unwrap(); } app } +/// The command that makes the envelope `command`'s dialog needs selected, if it needs one. +fn envelope_for(command: &str) -> Option<&'static str> { + match command { + "object.envelope.resetWithWarp" | "object.envelope.options" => Some("object.envelope.makeWithWarp"), + "object.envelope.resetWithMesh" => Some("object.envelope.makeWithMesh"), + _ => None, + } +} + /// The part of `doc` after `start`, up to the first of `ends`; empty when `doc` does not have `start`. fn clause<'a>(doc: &'a str, start: &str, ends: &[char]) -> &'a str { let Some(at) = doc.find(start) else { return "" }; @@ -1043,31 +1057,44 @@ fn names(clause: &str, id: &str) -> bool { clause.split([' ', ',']).any(|word| word == id) } -/// Each command `ui.menuDialog`'s params text lists opens the dialog that text names, by the `key` `ui.inspect` and -/// `ui.dialog` report: the command id unless the text names another key for that command, and no dialog for the -/// commands the text says show a slider. Every key the text names is one a listed command opens. +/// Each command `ui.menuDialog`'s params text lists opens the dialog that text names, by the `key` `ui.inspect` +/// reports: the command id unless the text names another key for that command, none for the commands the text says +/// have no key, and no dialog for the commands the text says show a slider. Every key the text names is one a listed +/// command opens. #[test] fn menu_dialog_opens_the_dialog_keys_its_params_text_names() { let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.menuDialog").expect("registered").3; let list = doc.strip_prefix("{command: ").and_then(|rest| rest.split_once('}')).expect("a command list").0; let sliders = clause(doc, "not a dialog, for ", &[';']); + let keyless = clause(doc, "the dialogs of ", &[';']); + let except = clause(doc, "is the command id, except ", &[';']); let mut opened = Vec::new(); for id in list.split('|') { + let expected = except + .split(',') + .filter_map(|entry| entry.split_once('`')?.1.split_once("` for ")) + .find_map(|(key, commands)| names(commands, id).then_some(key)) + .unwrap_or(id); let mut app = menu_dialog_app(id); app.run("ui.menuDialog", json!({"command": id})).unwrap_or_else(|e| panic!("{id}: {e}")); settle(&mut app); - let keys = dialog_keys(&app); + let entries = dialog_entries(&app); + assert_eq!( + entries.last().is_some_and(Option::is_none), + names(keyless, id), + "{id}: whether its dialog has a `key` differs from the params text" + ); + let keys: Vec = entries.into_iter().flatten().collect(); match keys.last() { + None if names(keyless, id) => {} None => assert!(names(sliders, id), "{id} opens no dialog, and the params text does not say it shows a slider"), - Some(key) if key == id => assert!(!names(sliders, id), "{id} opens a dialog, and the params text says it shows a slider"), - Some(key) => assert!( - names(clause(doc, &format!("`{key}` for "), &[',', ';']), id), - "{id} opens `{key}`, which the params text does not name for it" - ), + Some(key) => { + assert!(!names(sliders, id), "{id} opens a dialog, and the params text says it shows a slider"); + assert_eq!(key, expected, "{id}: its dialog key differs from the params text"); + } } opened.extend(keys); } - let except = clause(doc, "is the command id, except ", &[';']); for named in except.split('`').skip(1).step_by(2) { assert!(opened.iter().any(|key| key == named), "the params text names `{named}`, which no listed command opens"); } @@ -1080,6 +1107,38 @@ fn menu_dialog_opens_the_dialog_keys_its_params_text_names() { assert_eq!(dialog_keys(&app), ["object.path.simplify"]); } +/// Every command whose dialog `ui.menuDialog` opens and `ui.inspect` lists, with a `key` or without one, is one its +/// params text lists. Open Simplify and Smooth sliders count as dialogs too. +#[test] +fn menu_dialog_params_text_lists_every_command_whose_dialog_it_opens() { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.menuDialog").expect("registered").3; + let list: Vec<&str> = doc.strip_prefix("{command: ").and_then(|rest| rest.split_once('}')).expect("a command list").0.split('|').collect(); + let mut app = menu_dialog_app(""); + let ids: Vec = + app.session.commands().into_iter().map(|c| c.id.to_string()).chain(crate::menus::UI_COMMANDS.iter().map(|c| c.0.to_string())).collect(); + let mut missing = Vec::new(); + for id in ids { + // The Reset and Envelope Options dialogs open only with an envelope selected. + if envelope_for(&id).is_some() { + app = menu_dialog_app(&id); + } + if app.run("ui.menuDialog", json!({"command": id})).is_err() { + if envelope_for(&id).is_some() { + app = menu_dialog_app(""); + } + continue; + } + settle(&mut app); + let opened = + !dialog_entries(&app).is_empty() || crate::dialogs::simplify_slider::showing(&app) || crate::dialogs::smooth_slider::showing(&app); + if opened && !list.contains(&id.as_str()) { + missing.push(id.clone()); + } + app = menu_dialog_app(""); + } + assert!(missing.is_empty(), "ui.menuDialog opens a dialog for {missing:?}, which its params text does not list"); +} + /// The transform, selection and Type on a Path tools' `tool.options` open dialogs whose `key` its params text names. #[test] fn tool_options_opens_the_dialog_keys_its_params_text_names() { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 6afceabb91..06c5869129 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (its `key` in ui.inspect and ui.dialog is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, and `envelopeOptions` for object.envelope.options; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From c72600c1adc80eb8ac0b56f30c9d33313a13ce3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:13:13 -0800 Subject: [PATCH 03/13] MCP: the Simplify and Smooth sliders are canvas popovers, not dialogs The params text of ui.simplifyAuto and ui.smoothAuto (in both command catalogs) and docs/mcp.md described the Simplify and Smooth sliders as dialogs `simplifySlider` and `smoothSlider` that ui.dialog.confirm keeps. The sliders are canvas popovers: ui.inspect does not list them, and the ui.dialog commands do not control them. - The text says Enter or a click outside the popover keeps the result, with one undo step when the paths changed and none otherwise, and Escape restores the paths. - The tool.options test compares each tool's dialog key with the key the params text gives for that tool. --- crates/mcp/src/ui_catalog.rs | 4 ++-- crates/ui-egui/src/dialogs/tests.rs | 31 +++++++++++++++---------- crates/ui-egui/src/menus/ui_commands.rs | 4 ++-- docs/mcp.md | 15 +++++++----- 4 files changed, 32 insertions(+), 22 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b0d3bba69c..c5a5a46211 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1549,13 +1549,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyAuto", "Auto-Simplify", "", - "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + "{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect does not list the popover as a dialog, and ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do not control it; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", ), ( "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect does not list the popover as a dialog, and ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do not control it) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 0a44ffdeef..d861f71a02 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1143,19 +1143,26 @@ fn menu_dialog_params_text_lists_every_command_whose_dialog_it_opens() { #[test] fn tool_options_opens_the_dialog_keys_its_params_text_names() { let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "tool.options").expect("registered").3; - for tool in ["rotate", "scale", "reflect", "shear", "selection", "directSelection", "groupSelection", "typeOnPath", "verticalTypeOnPath"] { - let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); - app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); - let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); - if tool.ends_with("OnPath") { - let text = app.session.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap(); - app.session.execute("select.set", &json!({"ids": [text["id"]]})).unwrap(); + for group in ["rotate|scale|reflect|shear", "selection|directSelection|groupSelection", "typeOnPath|verticalTypeOnPath"] { + let documented = clause(doc, &format!("{group} → "), &[';']); + let keys: Vec<&str> = documented.split('`').skip(1).step_by(2).collect(); + let tools: Vec<&str> = group.split('|').collect(); + assert!(keys.len() == 1 || keys.len() == tools.len(), "{group}: the params text must pair tools with dialog keys"); + for (index, tool) in tools.into_iter().enumerate() { + let expected = keys[if keys.len() == 1 { 0 } else { index }]; + let mut app = window(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap(); + if tool.ends_with("OnPath") { + let text = app.session.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap(); + app.session.execute("select.set", &json!({"ids": [text["id"]]})).unwrap(); + } + app.run("tool.options", json!({"tool": tool})).unwrap_or_else(|e| panic!("{tool}: {e}")); + settle(&mut app); + let keys = dialog_keys(&app); + let key = keys.last().unwrap_or_else(|| panic!("{tool} opens no dialog")); + assert_eq!(key, expected, "{tool}: its dialog key differs from the params text"); } - app.run("tool.options", json!({"tool": tool})).unwrap_or_else(|e| panic!("{tool}: {e}")); - settle(&mut app); - let keys = dialog_keys(&app); - let key = keys.last().unwrap_or_else(|| panic!("{tool} opens no dialog")); - assert!(doc.contains(&format!("`{key}`")), "{tool} opens `{key}`, which the tool.options params text does not name"); } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 06c5869129..e831d54c90 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1550,13 +1550,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyAuto", "Auto-Simplify", "", - "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + "{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect does not list the popover as a dialog, and ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do not control it; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", ), ( "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect does not list the popover as a dialog, and ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do not control it) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", diff --git a/docs/mcp.md b/docs/mcp.md index e04d026dc8..8e2ce85100 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8465,9 +8465,11 @@ A path with only lone anchors selected, and every path with `wholePaths: true`, {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} ``` -In the desktop app, Object › Path › Simplify opens the slider (`ui.menuDialog {command: "object.path.simplify"}`, -dialog `simplifySlider` with field `level`) at the Auto-Simplify level for the selection and previews the result until -`ui.dialog.confirm`. `ui.simplifyAuto` moves the open slider back to the Auto-Simplify level, and `ui.simplifyMoreOptions` +In the desktop app, Object › Path › Simplify opens a canvas popover (`ui.menuDialog {command: "object.path.simplify"}`) +with a slider for `level` (0..100) at the Auto-Simplify level for the selection. The canvas previews the result. +Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths. `ui.inspect` does not list +the popover as a dialog, and `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` do not control it. +`ui.simplifyAuto` moves the open slider back to the Auto-Simplify level, and `ui.simplifyMoreOptions` opens the Simplify dialog at the slider's tolerance. When OK confirms the dialog with `retain` ticked, the menu item opens the dialog on those settings next time. @@ -8553,9 +8555,10 @@ are VectorCraft's own. 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 -Auto-Smooth level, and the slider previews the result until `ui.dialog.confirm`; `ui.smoothAuto` moves the open -slider back to the Auto-Smooth level. +canvas popover (`ui.menuDialog {command: "object.path.smooth"}`) with a slider for `level` (0..100) at the +Auto-Smooth level. The canvas previews the result. Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; +Escape restores the paths. `ui.inspect` does not list the popover as a dialog, and `ui.dialog.set`, `ui.dialog.confirm` +and `ui.dialog.cancel` do not control it. `ui.smoothAuto` moves the open slider back to the Auto-Smooth level. ## Circle through two or three points From e1b3943f46c2708bc793d62be6dab6b6a51d5322 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:52:10 -0800 Subject: [PATCH 04/13] MCP: tool.options' params text says where its dialog names appear The params text of tool.options (in both command catalogs) and docs/control-protocol.md named the dialogs' keys without saying that they are the `key` ui.inspect reports. The `dialog` field tool.options returns holds `rotate`, `scale`, `reflect` or `shear` for the transform tools, `move` for the selection tools and `command` for the Type on a Path tools. - The text names both: the `key` in ui.inspect and the returned `dialog` field. - The tool.options test checks the returned `dialog` field against the params text as well as the key. - The ui.menuDialog test checks that the Simplify and Smooth popovers are showing when the params text says those commands show a slider. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 26 ++++++++++++++++++++++--- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/control-protocol.md | 11 +++++++---- 4 files changed, 32 insertions(+), 9 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c5a5a46211..5e336e3849 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index d861f71a02..12ad414fc5 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1087,7 +1087,15 @@ fn menu_dialog_opens_the_dialog_keys_its_params_text_names() { let keys: Vec = entries.into_iter().flatten().collect(); match keys.last() { None if names(keyless, id) => {} - None => assert!(names(sliders, id), "{id} opens no dialog, and the params text does not say it shows a slider"), + None => { + assert!(names(sliders, id), "{id} opens no dialog, and the params text does not say it shows a slider"); + let showing = match id { + "object.path.simplify" => crate::dialogs::simplify_slider::showing(&app), + "object.path.smooth" => crate::dialogs::smooth_slider::showing(&app), + _ => false, + }; + assert!(showing, "{id}: its slider is not showing"); + } Some(key) => { assert!(!names(sliders, id), "{id} opens a dialog, and the params text says it shows a slider"); assert_eq!(key, expected, "{id}: its dialog key differs from the params text"); @@ -1143,7 +1151,12 @@ fn menu_dialog_params_text_lists_every_command_whose_dialog_it_opens() { #[test] fn tool_options_opens_the_dialog_keys_its_params_text_names() { let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "tool.options").expect("registered").3; - for group in ["rotate|scale|reflect|shear", "selection|directSelection|groupSelection", "typeOnPath|verticalTypeOnPath"] { + for (group, response_doc) in [ + ("rotate|scale|reflect|shear", "rotate|scale|reflect|shear for the corresponding transform tool"), + ("selection|directSelection|groupSelection", "move for selection|directSelection|groupSelection"), + ("typeOnPath|verticalTypeOnPath", "command for typeOnPath|verticalTypeOnPath"), + ] { + assert!(doc.contains(response_doc), "{group}: the params text must document its expected response dialog values"); let documented = clause(doc, &format!("{group} → "), &[';']); let keys: Vec<&str> = documented.split('`').skip(1).step_by(2).collect(); let tools: Vec<&str> = group.split('|').collect(); @@ -1157,11 +1170,18 @@ fn tool_options_opens_the_dialog_keys_its_params_text_names() { let text = app.session.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap(); app.session.execute("select.set", &json!({"ids": [text["id"]]})).unwrap(); } - app.run("tool.options", json!({"tool": tool})).unwrap_or_else(|e| panic!("{tool}: {e}")); + let response = app.run("tool.options", json!({"tool": tool})).unwrap_or_else(|e| panic!("{tool}: {e}")); + let expected_dialog = match tool { + "selection" | "directSelection" | "groupSelection" => "move", + "typeOnPath" | "verticalTypeOnPath" => "command", + _ => tool, + }; + assert_eq!(response["dialog"], expected_dialog, "{tool}: its response names the wrong dialog"); settle(&mut app); let keys = dialog_keys(&app); let key = keys.last().unwrap_or_else(|| panic!("{tool} opens no dialog")); assert_eq!(key, expected, "{tool}: its dialog key differs from the params text"); + assert!(doc.contains(&format!("`{key}`")), "{tool} opens `{key}`, which the tool.options params text does not name"); } } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e831d54c90..37d498a335 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1193,7 +1193,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), fillArea → the same Shape Builder Tool Options (Fill Area uses their gapDetection, gapLength and openFilledAsClosed), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e8d5c92ab6..0e9daff967 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -194,8 +194,10 @@ for `eyedropper` it opens Eyedropper Options, an `eyedropperOptions` dialog (fie `apply`, the attribute trees of `eyedropper.setOptions`) whose `ui.dialog.confirm` runs `eyedropper.setOptions` (what `appearance.copyFrom` copies). For `hand` it fits the artboard in the window (`view.fitArtboard`) and for `zoom` it shows 100% (`view.actualSize`). For `rotate`, `scale`, `reflect` and `shear` it opens the same dialog as Object › -Transform (dialog key `object.`, such as `object.rotate`), or fails with `nothing selected`. For `selection`, `directSelection` and -`groupSelection` it opens the Move dialog (key `object.move`), with the same failure; Move opens on the offset of the last +Transform (`key` in `ui.inspect`: `object.`, such as `object.rotate`), or fails with `nothing selected`. +The returned `dialog` field holds `rotate`, `scale`, `reflect` or `shear`, respectively. For `selection`, `directSelection` and +`groupSelection` it opens the Move dialog (`key` in `ui.inspect`: `object.move`), with the same failure, and returns +`dialog: "move"`. Move opens on the offset of the last drag or Move (`dx`, `dy`) and with the `copy`, `objects` and `preview` it was last confirmed with (its `patterns` is the `transformPatternTiles` preference, which its OK sets). `ui.key` Enter with one of those seven tools opens its dialog too (nothing happens without a selection), with the transform tools' `origin` at their reference @@ -203,8 +205,9 @@ point. For `lineSegment`, `arc`, `rectangularGrid` and `polarGrid` it opens the click opens (kind = the tool id), without `x` and `y` and with `__toolOptions: true`, whose `ui.dialog.confirm` runs `tool.setOption {tool, values}` and draws nothing; the next drag with the tool and its click dialog use the values (the line's `fillLine`, the grids' Default Size `width`, `height` and `reference` too). For `typeOnPath` and -`verticalTypeOnPath` it opens Type on a Path Options for the selected type on a path (dialog key -`type.pathOptions`, which runs that command), or fails when no type on a path is selected. Gradient tool handles snap to +`verticalTypeOnPath` it opens Type on a Path Options for the selected type on a path (`key` in `ui.inspect`: +`type.pathOptions`, which runs that command), or fails when no type on a path is selected. The returned `dialog` field +holds `command`. Gradient tool handles snap to anchors, edges and smart guides; Shift constrains them to 45° steps from the `constrainAngle` preference. Effect dialogs: `engine.execute {command: "effect.dialog", params: {effect, index?, item?}}` opens the `effect` dialog From a1bba4a8e4151a37e5be60e9db0ab14a08d0fdda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:22:24 -0800 Subject: [PATCH 05/13] Tests: the tool.options test reads each tool's dialog value from the params text The tool.options test compared the params text with fixed phrases and hard-coded the `dialog` value each tool returns. It now parses the " for " pairs after "The returned `dialog` field holds" and checks each tool's response against the value the text gives it. It fails when the text names a tool the test does not run, gives a tool two values, or gives transform values to tools other than the transform tools. It also checks that the text says the dialog names are the `key` in ui.inspect. --- crates/ui-egui/src/dialogs/tests.rs | 54 ++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 12ad414fc5..8b8070257c 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1151,12 +1151,45 @@ fn menu_dialog_params_text_lists_every_command_whose_dialog_it_opens() { #[test] fn tool_options_opens_the_dialog_keys_its_params_text_names() { let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "tool.options").expect("registered").3; - for (group, response_doc) in [ - ("rotate|scale|reflect|shear", "rotate|scale|reflect|shear for the corresponding transform tool"), - ("selection|directSelection|groupSelection", "move for selection|directSelection|groupSelection"), - ("typeOnPath|verticalTypeOnPath", "command for typeOnPath|verticalTypeOnPath"), - ] { - assert!(doc.contains(response_doc), "{group}: the params text must document its expected response dialog values"); + let plain = doc.replace('`', ""); + assert!(plain.contains("key in ui.inspect"), "the params text must say the dialog names are the `key` in ui.inspect"); + let field = clause(&plain, "returned dialog field holds ", &['.']); + // The `dialog` value the params text gives for `tool`: " for " pairs, where names the tool + // itself (with "the corresponding transform tool" and every value in the transform group) or one value for + // every tool in . + let documented_dialog = |tool: &str| -> Option { + let mut mappings = field.split(", ").map(|part| part.trim_start_matches("and ")).filter_map(|part| { + let (values, tools) = part.split_once(" for ")?; + if tools == "the corresponding transform tool" && values.split('|').any(|v| v == tool) { + Some(tool.to_string()) + } else if tools.split('|').any(|t| t == tool) { + Some(values.to_string()) + } else { + None + } + }); + let mapping = mappings.next(); + assert!(mappings.next().is_none(), "{tool}: the params text gives more than one `dialog` mapping"); + mapping + }; + let groups = ["rotate|scale|reflect|shear", "selection|directSelection|groupSelection", "typeOnPath|verticalTypeOnPath"]; + let checked: Vec<&str> = groups.iter().flat_map(|g| g.split('|')).collect(); + let mut named_tools = Vec::new(); + for part in field.split(", ").map(|part| part.trim_start_matches("and ")) { + let (values, tools) = part.split_once(" for ").unwrap_or_else(|| panic!("`{part}` pairs no dialog value with tools")); + let named = if tools == "the corresponding transform tool" { + assert!(values.split('|').all(|value| groups[0].split('|').any(|tool| tool == value)), "`{part}` names a non-transform tool"); + values + } else { + tools + }; + for tool in named.split('|') { + assert!(checked.contains(&tool), "the params text gives a `dialog` value for {tool}, which this test does not check"); + assert!(!named_tools.contains(&tool), "{tool}: the params text gives more than one `dialog` mapping"); + named_tools.push(tool); + } + } + for group in groups { let documented = clause(doc, &format!("{group} → "), &[';']); let keys: Vec<&str> = documented.split('`').skip(1).step_by(2).collect(); let tools: Vec<&str> = group.split('|').collect(); @@ -1171,12 +1204,9 @@ fn tool_options_opens_the_dialog_keys_its_params_text_names() { app.session.execute("select.set", &json!({"ids": [text["id"]]})).unwrap(); } let response = app.run("tool.options", json!({"tool": tool})).unwrap_or_else(|e| panic!("{tool}: {e}")); - let expected_dialog = match tool { - "selection" | "directSelection" | "groupSelection" => "move", - "typeOnPath" | "verticalTypeOnPath" => "command", - _ => tool, - }; - assert_eq!(response["dialog"], expected_dialog, "{tool}: its response names the wrong dialog"); + let expected_dialog = + documented_dialog(tool).unwrap_or_else(|| panic!("{tool}: the params text does not say which `dialog` its response holds")); + assert_eq!(response["dialog"], expected_dialog.as_str(), "{tool}: its response names a `dialog` other than the params text's"); settle(&mut app); let keys = dialog_keys(&app); let key = keys.last().unwrap_or_else(|| panic!("{tool} opens no dialog")); From 647c96e72d8d44fd770c5c546a7435874c974629 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:55:35 -0800 Subject: [PATCH 06/13] Tests: Simplify's kept settings come from OK in its dialog, and tool.options' phrase entries need no fixed wording The menu dialog test now turns on Retain with a new tolerance in the Simplify dialog, confirms it, and checks that the reopened dialog shows both. The tool.options test reads any non-list tools phrase as the transform tools' own mapping. --- crates/ui-egui/src/dialogs/tests.rs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 8b8070257c..5311a8c2d3 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1106,13 +1106,21 @@ fn menu_dialog_opens_the_dialog_keys_its_params_text_names() { for named in except.split('`').skip(1).step_by(2) { assert!(opened.iter().any(|key| key == named), "the params text names `{named}`, which no listed command opens"); } - // Simplify opens its dialog, under its command id, once OK in that dialog has kept the settings. + // Simplify opens its dialog, under its command id, with the kept tolerance once OK in that dialog has kept the + // settings. let mut app = menu_dialog_app("object.path.simplify"); - let ctx = app.ui_ctx.clone().expect("a window app"); - craft::ui::runtime::memory::set_saved_value(&ctx, &super::path_ops::SIMPLIFY_KEY, Some(craft::ui::patterns::form_dialogs::DialogFields::new())); + app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap(); + settle(&mut app); + app.run("ui.simplifyMoreOptions", json!({})).unwrap(); + settle(&mut app); + set_all(&mut app, [("tolerance", json!(7.5)), ("retain", json!(true))]); + assert!(confirm(&mut app), "OK in the Simplify dialog is taken"); + settle(&mut app); app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap(); settle(&mut app); assert_eq!(dialog_keys(&app), ["object.path.simplify"]); + assert_eq!(field(&app, "tolerance"), Some(7.5), "the reopened dialog shows the kept tolerance"); + assert!(flag(&app, "retain"), "the reopened dialog keeps Retain on"); } /// Every command whose dialog `ui.menuDialog` opens and `ui.inspect` lists, with a `key` or without one, is one its @@ -1155,12 +1163,12 @@ fn tool_options_opens_the_dialog_keys_its_params_text_names() { assert!(plain.contains("key in ui.inspect"), "the params text must say the dialog names are the `key` in ui.inspect"); let field = clause(&plain, "returned dialog field holds ", &['.']); // The `dialog` value the params text gives for `tool`: " for " pairs, where names the tool - // itself (with "the corresponding transform tool" and every value in the transform group) or one value for - // every tool in . + // itself (with a phrase rather than a `|` list of tool ids, and every value in the transform group) or one + // value for every tool in . let documented_dialog = |tool: &str| -> Option { let mut mappings = field.split(", ").map(|part| part.trim_start_matches("and ")).filter_map(|part| { let (values, tools) = part.split_once(" for ")?; - if tools == "the corresponding transform tool" && values.split('|').any(|v| v == tool) { + if tools.contains(' ') && values.split('|').any(|v| v == tool) { Some(tool.to_string()) } else if tools.split('|').any(|t| t == tool) { Some(values.to_string()) @@ -1177,7 +1185,7 @@ fn tool_options_opens_the_dialog_keys_its_params_text_names() { let mut named_tools = Vec::new(); for part in field.split(", ").map(|part| part.trim_start_matches("and ")) { let (values, tools) = part.split_once(" for ").unwrap_or_else(|| panic!("`{part}` pairs no dialog value with tools")); - let named = if tools == "the corresponding transform tool" { + let named = if tools.contains(' ') { assert!(values.split('|').all(|value| groups[0].split('|').any(|tool| tool == value)), "`{part}` names a non-transform tool"); values } else { From 0c4a558686c54026b3cb5df08e6c954e9be4e9c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:50:02 -0800 Subject: [PATCH 07/13] MCP: ui.menuDialog's params text lists Offset Objects and Match Objects Cause: main gained the Arrange add-on's Offset Objects and Match Objects dialogs (addon.arrange.offset, addon.arrange.match) after this branch started. ui.menuDialog opens both, but its params text in crates/ui-egui/src/menus/ui_commands.rs and crates/mcp/src/ui_catalog.rs did not list them, so the branch's menu_dialog_params_text_lists_every_command_whose_dialog_it_opens test failed once main was merged in. Both lists now name the two commands; each dialog's key is its command id. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 5e336e3849..f4712b2795 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 37d498a335..0e569c5b61 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From b1ca790ddfe38a16b28158b54611e4fd42919120 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 11:15:09 -0800 Subject: [PATCH 08/13] MCP: ui.menuDialog lists object.stepAndRepeat Main added Object > Step and Repeat, whose dialog ui.menuDialog opens under the key object.stepAndRepeat. The command list in ui.menuDialog's params text (and its MCP mirror) did not name it, so menu_dialog_params_text_lists_every_command_whose_dialog_it_opens failed on the branch merged with main. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 45972991a8..e1ff8d54a0 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 806938b41c..370b12d2b1 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 09f6e7b99622e87f4016bac8587393005fce659c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:09:28 -0800 Subject: [PATCH 09/13] MCP docs: Simplify opens the popover only when no retained settings select the dialog --- docs/mcp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 718cbb8dec..f89256a633 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8575,8 +8575,8 @@ A path with only lone anchors selected, and every path with `wholePaths: true`, {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} ``` -In the desktop app, Object › Path › Simplify opens a canvas popover (`ui.menuDialog {command: "object.path.simplify"}`) -with a slider for `level` (0..100) at the Auto-Simplify level for the selection. The canvas previews the result. +In the desktop app, unless retained settings select the Simplify dialog (see below), Object › Path › Simplify opens a +canvas popover (`ui.menuDialog {command: "object.path.simplify"}`) with a slider for `level` (0..100) at the Auto-Simplify level for the selection. The canvas previews the result. Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths. `ui.inspect` does not list the popover as a dialog, and `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` do not control it. `ui.simplifyAuto` moves the open slider back to the Auto-Simplify level, and `ui.simplifyMoreOptions` From fe89d3f81e3c1e0b28b332a636f79056ae7ec0d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:54:45 -0800 Subject: [PATCH 10/13] Scripts: list rebuilds count against the run, a stop is not masked, bad answers throw at the call - pageItems, pathItems and textFrames build their list of a document again after every edit. The rebuild walked the whole document without counting anything against the run, so a loop that edits and reads a collection in a large document did unbounded host work. A rebuilt list now counts 16 bytes per object (as the selection's list does) against the run's host-call allowance, and the path and type lists count the page items they scan. - An edit's own ordinary error was returned ahead of a stop (an uncatchable Abort) from putting back the selection or switching back to the active document, so a script could catch it and go on. A stop now comes first. - An answer to a waiting call that could not be read as a value (nested too deep, too many entries) ended the run instead of being thrown at the call. It is now thrown there, where the script can catch it, and a ScriptUI dialog that waited for the answer stops showing, as when its host call fails. - The selection cost test also compares the host calls, under the same 64 KiB limit for both documents. --- crates/engine/src/script/dom.rs | 74 ++++++++++++++++---- crates/engine/src/script/dom/paths.rs | 24 ++++--- crates/engine/src/script/dom/tags.rs | 2 +- crates/engine/src/script/dom/text.rs | 25 ++++--- crates/engine/src/script/dom/text/threads.rs | 2 +- crates/engine/src/tests/script_dom.rs | 47 +++++++++++-- crates/js/src/host_tests.rs | 23 ++++++ crates/js/src/interp.rs | 27 ++++++- crates/js/src/realm.rs | 29 ++++++-- crates/js/src/scriptui_tests.rs | 26 +++++++ 10 files changed, 231 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d8d01956f4..bb1e03158b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -620,10 +620,12 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { } /// The ids of a document's page items, topmost first, each group or compound path before the -/// objects in it ([`State`] keeps the lists of the last documents read). -fn page_items(h: &Host, st: &DocState) -> Rc> { +/// objects in it ([`State`] keeps the lists of the last documents read). Building the list again, +/// after an edit or for another document, counts against the run's host-call allowance as a list +/// of that many objects does ([`list_charge`]). +fn page_items(h: &Host, st: &DocState) -> std::result::Result>, HostError> { if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) { - return ids; + return Ok(ids); } fn walk(nodes: &[Arc], out: &mut Vec) { for n in nodes.iter().rev() { @@ -641,9 +643,16 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { } let mut ids = Vec::new(); walk(&st.doc.layers, &mut ids); + h.charge_call(list_charge(ids.len()))?; let ids = Rc::new(ids); keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone())); - ids + Ok(ids) +} + +/// The bytes a list of `n` objects that a collection builds again counts against the run's +/// host-call allowance, as the selection's list counts them ([`selection_of`]). +pub(super) fn list_charge(n: usize) -> u64 { + 16u64.saturating_mul(n as u64) } /// The objects directly in the layers and sublayers of a document: what deleting every page item @@ -901,8 +910,8 @@ fn on_doc_steps( restored = restore_layer(h, uid, layer.0, &layer.1); } } - // The document that was active is active again before any error is given: `f`'s error first, - // then the selection's, then the switch back's. + // The document that was active is active again before any error is given: an error that ends + // the run first, then `f`'s error, then the selection's, then the switch back's. let back = match active { Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop), _ => Ok(()), @@ -914,12 +923,35 @@ fn on_doc_steps( { st.activated = activated; } + first_error(r, restored, back) +} + +/// [`on_doc`]'s result from `f`'s result `r`, then putting back the selection and the layer +/// (`restored`) and the active document (`back`): an error that ends the run first, since a +/// script could catch `f`'s ordinary error, then the first error in that order. +fn first_error( + r: std::result::Result, + restored: std::result::Result<(), HostError>, + back: std::result::Result<(), HostError>, +) -> std::result::Result { + if !r.as_ref().is_err_and(ends_run) { + restored.as_ref().err().into_iter().chain(back.as_ref().err()).find(|e| ends_run(e)).map_or(Ok(()), |e| Err(e.clone()))?; + } let v = r?; restored?; back?; Ok(v) } +/// Whether `e` ends the run, so that a script cannot catch it. +fn ends_run(e: &HostError) -> bool { + match e { + HostError::Abort(_) => true, + HostError::Marked { error, .. } => ends_run(error), + _ => false, + } +} + /// Marks stale the style objects whose styles a command the run ran removed or renamed. pub(super) fn after_kept_command(h: &Host) { text::styles::after_command(h); @@ -2061,7 +2093,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { fn items_length(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let n = with_doc(h, doc, |_, st| page_items(h, st).len()); + let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?; Ok(num(float(n as u64))) } @@ -2102,7 +2134,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { r => r, }, Data::Number(n) => match position(*n) { - Some(i) => Ok(item_at(h, doc, i)), + Some(i) => item_at(h, doc, i), None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), r => r, @@ -2113,8 +2145,8 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { } /// The object at position `i` of `pageItems`, or `undefined` past the end. -fn item_at(h: &Host, doc: Doc, i: usize) -> Data { - with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))) +fn item_at(h: &Host, doc: Doc, i: usize) -> Answer { + with_doc(h, doc, |_, st| Ok(page_items(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn items_by_name(h: &Host, a: &[Data]) -> Answer { @@ -2126,7 +2158,7 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer { /// The first object of `pageItems` named `name`, or `Not found`. fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { - let ids = page_items(h, st); + let ids = page_items(h, st)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -2138,7 +2170,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { Data::String(_) => items_by_name(h, a), Data::Number(n) => { let doc = items_doc(h, a)?; - match position(*n).map(|i| item_at(h, doc, i)) { + match position(*n).map(|i| item_at(h, doc, i)).transpose()? { None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())), Some(d) => Ok(d), } @@ -3157,6 +3189,24 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + /// A stop from putting back the selection or the active document is not hidden by the edit's + /// own error, which a script could catch; ordinary errors keep their order. + #[test] + fn an_edit_gives_a_stop_ahead_of_its_own_error() { + let error = |m: &str| HostError::Error(m.into()); + let stop = || HostError::Abort("stop".into()); + let marked = || HostError::Marked { error: Box::new(stop()), mark: 0 }; + assert_eq!(first_error::<()>(Err(error("edit")), Err(stop()), Ok(())), Err(stop())); + assert_eq!(first_error::<()>(Err(error("edit")), Ok(()), Err(stop())), Err(stop())); + assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(marked())), Err(marked())); + assert_eq!(first_error(Ok(1), Ok(()), Err(stop())), Err(stop())); + // The edit's own stop comes first, and with no stop the edit's error does. + assert_eq!(first_error::<()>(Err(HostError::Abort("edit".into())), Err(stop()), Ok(())), Err(HostError::Abort("edit".into()))); + assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(error("back"))), Err(error("edit"))); + assert_eq!(first_error::<()>(Ok(()), Err(error("selection")), Err(error("back"))), Err(error("selection"))); + assert_eq!(first_error(Ok(1), Ok(()), Ok(())), Ok(1)); + } + #[test] fn page_item_lists_are_kept_for_several_documents() { let docs: Vec> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect(); diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e4f6bb203e..805ead2eef 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -367,16 +367,18 @@ fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { // ---- Document.pathItems ---- -/// The ids of a document's paths, in the order of its page items. -fn path_items(h: &super::Host, st: &DocState) -> Rc> { +/// The ids of a document's paths, in the order of its page items. Building the list again counts +/// the page items it looks through against the run's host-call allowance. +fn path_items(h: &super::Host, st: &DocState) -> Result>, HostError> { if let Some(ids) = super::kept_list(&h.dom.paths, st) { - return ids; + return Ok(ids); } - let all = super::page_items(h, st); + let all = super::page_items(h, st)?; + h.charge_call(all.len() as u64)?; let ids: Rc> = Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); super::keep_list(&h.dom.paths, st, &ids); - ids + Ok(ids) } pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { @@ -396,7 +398,7 @@ fn items_typename(h: &super::Host, a: &[Data]) -> Answer { fn items_length(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -408,14 +410,14 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -438,10 +440,10 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) - }); + Ok::<_, HostError>((ids, refused)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); diff --git a/crates/engine/src/script/dom/tags.rs b/crates/engine/src/script/dom/tags.rs index 294165b252..dff0120f78 100644 --- a/crates/engine/src/script/dom/tags.rs +++ b/crates/engine/src/script/dom/tags.rs @@ -74,7 +74,7 @@ fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> Control Ok(()) }), Owner::Doc(doc) => with_doc(h, doc, |_, st| { - let ids = page_items(h, st); + let ids = page_items(h, st)?; h.charge_call(ids.len() as u64)?; for id in ids.iter() { if let Some(n) = st.doc.node(*id) { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 998652b81c..3c4acac317 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1233,18 +1233,21 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember { } /// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the -/// document is unchanged. -fn frame_ids(h: &Host, st: &DocState) -> Rc> { +/// document is unchanged. Building the list again counts the page items it looks through against +/// the run's host-call allowance. +fn frame_ids(h: &Host, st: &DocState) -> std::result::Result>, HostError> { if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() && *uid == st.uid && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) { - return ids.clone(); + return Ok(ids.clone()); } - let ids: Vec = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); + let all = page_items(h, st)?; + h.charge_call(all.len() as u64)?; + let ids: Vec = all.iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); let ids = Rc::new(ids); *h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone())); - ids + Ok(ids) } fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { @@ -1253,7 +1256,7 @@ fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { fn frames_length(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) + Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64))) } fn frames_parent(h: &Host, a: &[Data]) -> Answer { @@ -1265,14 +1268,14 @@ fn frames_at(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn frames_by_name(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st); + let ids = frame_ids(h, st)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -1364,13 +1367,13 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st); + let ids = frame_ids(h, st)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - (ids, refused, on_locked) - }); + Ok::<_, HostError>((ids, refused, on_locked)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs index e159893e8d..5ade055bc6 100644 --- a/crates/engine/src/script/dom/text/threads.rs +++ b/crates/engine/src/script/dom/text/threads.rs @@ -633,7 +633,7 @@ fn heads(h: &Host, st: &DocState) -> std::result::Result>, HostEr { return Ok(ids.clone()); } - let ids = frame_ids(h, st); + let ids = frame_ids(h, st)?; h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::())?; // A frame listed by an earlier thread belongs to that one, as `story_of` finds it. let (mut threaded, mut first) = (HashSet::new(), HashSet::new()); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 14878904fb..d6b6c29784 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2368,8 +2368,17 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() { assert_eq!(out[0][0].as_array().map(Vec::len), Some(3)); // Each pass edits the document, so nothing kept from the last read can be reused. let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;"; + // The script's fuel, and the host's calls and the bytes they count, which hold the work the + // host does for them: 64 KiB is less than one list of the large document's objects. + let cost = |s: &mut Session| { + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let r = run(s, edits); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let r = r.unwrap_or_else(|e| panic!("the reads went over: {e}")); + (r["fuelUsed"].as_u64().unwrap(), r["hostCalls"].as_u64().unwrap()) + }; s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); - let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap(); + let small = cost(&mut s); // 3 objects doubled 11 times: 6,144. s.execute("select.all", &json!({})).unwrap(); for _ in 0..11 { @@ -2377,11 +2386,39 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() { s.execute("select.all", &json!({})).unwrap(); } s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); - crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); - let large = run(&mut s, edits); + assert_eq!(small, cost(&mut s)); +} + +/// Building a collection's list again after an edit counts the objects it lists against the +/// run's allowance, so a loop that edits and reads `pageItems`, `pathItems` or `textFrames` in a +/// large document ends with the limit instead of walking the document each time for nothing. +#[test] +fn rebuilding_a_collection_after_an_edit_counts_against_the_run() { + let (mut s, a, _) = doc(); + let source = |list: &str| { + format!("var d = app.activeDocument, it = d.pageItems[0]; for (var i = 0; i < 40; i++) {{ it.opacity = 50 + i % 2; d.{list}.length; }}") + }; + let lists = ["pageItems", "pathItems", "textFrames"]; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let small: Vec = lists.iter().map(|l| run(&mut s, &source(l)).is_ok()).collect(); crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); - let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap(); - assert_eq!(small, large); + assert_eq!(small, vec![true; 3], "a small document stays under 1 MiB"); + // 2 objects doubled 11 times: 4,096, a list of 64 KiB each time it is built again. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..11 { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + // Nothing selected, so putting the selection back after each edit passes no list of ids. + s.execute("select.none", &json!({})).unwrap(); + for list in lists { + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let r = run(&mut s, &source(list)); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + let e = r.map(|r| panic!("{list}: 40 lists of 4,096 objects stayed under 1 MiB: {r}")).unwrap_err().to_string(); + assert!(e.contains("passed more data to and from commands"), "{list}: {e}"); + } } /// A collection read with a name gives what `getByName` gives, and throws as it does for no match. diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index cd7518eb4b..e00d034c1a 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -874,6 +874,29 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); } +/// An answer that cannot be read as a value, for a global function or a member of a host class, +/// is thrown at the call that waited, where the script catches it, and the run goes on. +#[test] +fn an_answer_that_cannot_be_read_is_thrown_at_the_waiting_call() { + let mut nested = Data::Null; + for _ in 0..20 { + nested = Data::Array(vec![nested]); + } + for call in ["ask('x')", "thing.fetch()"] { + let source = format!("var m = 'none'; try {{ {call}; }} catch (e) {{ m = e.name + '|' + e.message; }} m + '|after'"); + let mut r = realm(1_000_000); + with_ask(&mut r); + with_thing(&mut r, None); + r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 }); + r.start(&source).unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(nested.clone()).unwrap(); + let JsValue::String(out) = finish(&mut r, 1_000).0.unwrap() else { panic!("{call}: not a string") }; + assert!(out.starts_with("RangeError|") && out.contains("nested too deep") && out.ends_with("|after"), "{call}: {out}"); + } +} + /// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by /// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing` /// with the handle `[0]`. diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index fa4b649e74..390dd3f5c8 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -274,6 +274,21 @@ pub(crate) struct Pause { pub(crate) struct Resumption { resume: ResumeFn, keep: Vec, + /// Runs when the answer cannot be read, so the resume function never gets it. + failed: Option, +} + +impl Resumption { + /// The built-in does not get the host's answer: its failure function runs with its kept + /// values, which `thrown` is kept from collection with. + pub(crate) fn fail(self, interp: &mut Interp, thrown: &Value) { + let Some(failed) = self.failed else { return }; + let mark = interp.temp_roots.len(); + interp.temp_roots.extend(self.keep.iter().cloned()); + interp.temp_roots.push(thrown.clone()); + failed(interp, &self.keep); + interp.temp_roots.truncate(mark); + } } pub(crate) struct Interp { @@ -378,6 +393,10 @@ pub(crate) struct Interp { /// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its /// answer is read as such a member's result is ([`Interp::write_hosted`]). pub(crate) waiting_hosted: bool, + /// The answer to the call that waited could not be read as a value + /// ([`crate::Realm::answer`]): the value on top of the stack is the exception, which the next + /// step throws at that call. + pub(crate) answer_throws: bool, /// A host class's constructor runs with `new`: it may not wait for its result. pub(crate) constructing: bool, /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before @@ -690,6 +709,7 @@ impl Interp { can_wait: Rc::default(), waiting: false, waiting_hosted: false, + answer_throws: false, constructing: false, resuming: None, again: None, @@ -1031,6 +1051,11 @@ impl Interp { fn step(&mut self) -> JsResult> { self.tick()?; + // An answer that could not be read is thrown at the call that waited for it. + if std::mem::take(&mut self.answer_throws) { + let thrown = self.pop()?; + return Err(Abrupt::Throw(thrown)); + } // A built-in that waited for the host takes the answer on top of the stack before the // instruction after its call runs; what it throws is thrown at that call. if let Some(r) = self.resuming.take() { @@ -3571,7 +3596,7 @@ impl Interp { } self.temp_roots.truncate(mark); let answer = answer?; - let r = Resumption { resume, keep }; + let r = Resumption { resume, keep, failed }; if self.waiting && !was_waiting { self.resuming = Some(r); return Ok(answer); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 439b231d16..4a810927ab 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -380,6 +380,7 @@ impl Realm { interp.host_abort = None; interp.waiting = false; interp.waiting_hosted = false; + interp.answer_throws = false; interp.constructing = false; interp.resuming = None; interp.again = None; @@ -426,6 +427,7 @@ impl Realm { interp.join_stack.clear(); interp.waiting = false; interp.waiting_hosted = false; + interp.answer_throws = false; interp.constructing = false; interp.resuming = None; interp.again = None; @@ -566,8 +568,10 @@ impl Realm { /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next /// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the /// call, the built-in takes `d` first and gives its own result, and what it throws is thrown - /// at its call. A result past the heap limit ends the run with that - /// limit, and with no call waiting this gives an internal error. + /// at its call. A result that cannot be read as a value, such as one nested too deep, is + /// thrown at the call as an immediate result would be, and the built-in does not get it. A + /// result past the heap limit ends the run with that limit, and with no call waiting this gives + /// an internal error. pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; if !interp.waiting { @@ -584,10 +588,23 @@ impl Realm { let hosted = std::mem::take(&mut interp.waiting_hosted); // The value on top of the stack stood in for the result. let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) }; - let r = written.and_then(|v| { - interp.stack.pop(); - interp.push(v) - }); + let r = match written { + // An answer that cannot be read as a value (too deep, too many entries, a stale host + // reference) is thrown at the call, where the script can catch it, and a built-in + // that waited with the call does not get it: it fails as when its host call throws. + Err(Abrupt::Throw(thrown)) => { + interp.stack.pop(); + if let Some(r) = interp.resuming.take() { + r.fail(interp, &thrown); + } + interp.answer_throws = true; + interp.push(thrown) + } + written => written.and_then(|v| { + interp.stack.pop(); + interp.push(v) + }), + }; match r { Ok(()) => Ok(()), Err(e) => self.outcome(Err(e)).map(drop), diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index dc4a942d6c..d8c7014ea0 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -229,6 +229,32 @@ fn a_dialog_can_be_shown_again_after_it_closed() { assert_eq!(r.run(&format!("{FORM} [w.show(), w.show()].join()")).unwrap(), JsValue::String("1,2".into())); } +/// An event the host gives a waiting `show()` that cannot be read is thrown at `show()`, and the +/// dialog is no longer showing, so it can be shown again. +#[test] +fn an_event_that_cannot_be_read_ends_show_and_the_dialog_can_show_again() { + let (mut r, seen, _) = realm(Vec::new()); + r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 }); + let mut nested = Data::Null; + for _ in 0..20 { + nested = Data::Array(vec![nested]); + } + r.start("var w = new Window('dialog'), m = 'none'; try { w.show(); } catch (e) { m = e.name; } m + '|' + w.show()").unwrap(); + assert_eq!(r.advance(100_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(nested).unwrap(); + assert_eq!(seen.borrow().ends, vec![(0.0, false)], "show ended without its result"); + assert_eq!(r.advance(100_000).unwrap(), Progress::Paused); + assert!(r.waits(), "the second show waits for its event"); + r.answer(close()).unwrap(); + let mut out = r.advance(100_000).unwrap(); + while out == Progress::Paused { + out = r.advance(100_000).unwrap(); + } + assert_eq!(out, Progress::Done(JsValue::String("RangeError|0".into()))); + assert_eq!(seen.borrow().ends, vec![(0.0, false), (0.0, true)]); +} + #[test] fn types_that_are_not_available_yet_throw_errors_that_say_so() { for (source, want) in [ From 1662723cae541837df6b0fdb13a3b09ee2f73c90 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 17:54:45 -0800 Subject: [PATCH 11/13] MCP: ui.menuDialog lists the slider keys and Edit Points Only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main now lists the Smooth and Simplify sliders in ui.inspect as dialogs smoothSlider and simplifySlider, which ui.dialog.set, confirm and cancel control, and Object › Plug-ins › Selection Tools › Edit Points Only… opens through ui.menuDialog. The params text of ui.menuDialog, ui.smoothAuto and ui.simplifyAuto, docs/mcp.md and the menu dialog key test now say so. --- crates/mcp/src/ui_catalog.rs | 6 +++--- crates/ui-egui/src/dialogs/tests.rs | 28 ++++++++++--------------- crates/ui-egui/src/menus/ui_commands.rs | 6 +++--- docs/mcp.md | 14 +++++++------ 4 files changed, 25 insertions(+), 29 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index e1ff8d54a0..2c8f54eb6e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", @@ -1549,13 +1549,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyAuto", "Auto-Simplify", "", - "{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect does not list the popover as a dialog, and ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do not control it; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + "{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `simplifySlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", ), ( "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect does not list the popover as a dialog, and ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do not control it) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `smoothSlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 5311a8c2d3..38c156048e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -1059,13 +1059,12 @@ fn names(clause: &str, id: &str) -> bool { /// Each command `ui.menuDialog`'s params text lists opens the dialog that text names, by the `key` `ui.inspect` /// reports: the command id unless the text names another key for that command, none for the commands the text says -/// have no key, and no dialog for the commands the text says show a slider. Every key the text names is one a listed -/// command opens. +/// have no key, and the slider's key for Smooth and Simplify, whose sliders show over the canvas. Every key the text +/// names is one a listed command opens. #[test] fn menu_dialog_opens_the_dialog_keys_its_params_text_names() { let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.menuDialog").expect("registered").3; let list = doc.strip_prefix("{command: ").and_then(|rest| rest.split_once('}')).expect("a command list").0; - let sliders = clause(doc, "not a dialog, for ", &[';']); let keyless = clause(doc, "the dialogs of ", &[';']); let except = clause(doc, "is the command id, except ", &[';']); let mut opened = Vec::new(); @@ -1086,21 +1085,16 @@ fn menu_dialog_opens_the_dialog_keys_its_params_text_names() { ); let keys: Vec = entries.into_iter().flatten().collect(); match keys.last() { - None if names(keyless, id) => {} - None => { - assert!(names(sliders, id), "{id} opens no dialog, and the params text does not say it shows a slider"); - let showing = match id { - "object.path.simplify" => crate::dialogs::simplify_slider::showing(&app), - "object.path.smooth" => crate::dialogs::smooth_slider::showing(&app), - _ => false, - }; - assert!(showing, "{id}: its slider is not showing"); - } - Some(key) => { - assert!(!names(sliders, id), "{id} opens a dialog, and the params text says it shows a slider"); - assert_eq!(key, expected, "{id}: its dialog key differs from the params text"); - } + None => assert!(names(keyless, id), "{id} opens no dialog"), + Some(key) => assert_eq!(key, expected, "{id}: its dialog key differs from the params text"), } + // Smooth and Simplify open the slider over the canvas, which ui.inspect lists under its own key. + let showing = match id { + "object.path.simplify" => crate::dialogs::simplify_slider::showing(&app), + "object.path.smooth" => crate::dialogs::smooth_slider::showing(&app), + _ => true, + }; + assert!(showing, "{id}: its slider is not showing"); opened.extend(keys); } for named in except.split('`').skip(1).step_by(2) { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 370b12d2b1..5681df62bf 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, and `envelopeOptions` for object.envelope.options; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; a slider over the canvas, not a dialog, for object.path.smooth, and for object.path.simplify until OK in its dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", @@ -1550,13 +1550,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.simplifyAuto", "Auto-Simplify", "", - "{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect does not list the popover as a dialog, and ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do not control it; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + "{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `simplifySlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", ), ( "ui.smoothAuto", "Auto-Smooth", "", - "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect does not list the popover as a dialog, and ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel do not control it) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", + "{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `smoothSlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open", ), ( "ui.simplifyMoreOptions", diff --git a/docs/mcp.md b/docs/mcp.md index e979efa27e..31412c3703 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8669,8 +8669,9 @@ A path with only lone anchors selected, and every path with `wholePaths: true`, In the desktop app, unless retained settings select the Simplify dialog (see below), Object › Path › Simplify opens a canvas popover (`ui.menuDialog {command: "object.path.simplify"}`) with a slider for `level` (0..100) at the Auto-Simplify level for the selection. The canvas previews the result. -Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths. `ui.inspect` does not list -the popover as a dialog, and `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` do not control it. +Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths. `ui.inspect` lists +the popover as dialog `simplifySlider` with field `level`. `ui.dialog.set` moves the slider and refuses a level outside +0..100, `ui.dialog.confirm` keeps the result as Enter does, and `ui.dialog.cancel` restores the paths as Escape does. `ui.simplifyAuto` moves the open slider back to the Auto-Simplify level, and `ui.simplifyMoreOptions` opens the Simplify dialog at the slider's tolerance. When OK confirms the dialog with `retain` ticked, the menu item opens the dialog on those settings next time. @@ -8759,8 +8760,9 @@ In the desktop app, Object › Path › Smooth, the canvas context menu's Smooth path) and the Contextual Task Bar's Smooth (with a path selected whole with the Direct Selection tool) open the canvas popover (`ui.menuDialog {command: "object.path.smooth"}`) with a slider for `level` (0..100) at the Auto-Smooth level. The canvas previews the result. Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; -Escape restores the paths. `ui.inspect` does not list the popover as a dialog, and `ui.dialog.set`, `ui.dialog.confirm` -and `ui.dialog.cancel` do not control it. `ui.smoothAuto` moves the open slider back to the Auto-Smooth level. +Escape restores the paths. `ui.inspect` lists the popover as dialog `smoothSlider` with field `level`. `ui.dialog.set` +moves the slider and refuses a level outside 0..100, `ui.dialog.confirm` keeps the result as Enter does, and +`ui.dialog.cancel` restores the paths as Escape does. `ui.smoothAuto` moves the open slider back to the Auto-Smooth level. ## Circle through two or three points @@ -17593,8 +17595,8 @@ anchor points selected on them. Nothing selected, no anchor point left to keep ( {"name":"run_command","arguments":{"command":"addon.select.editPointsOnly","params":{"segmentEnds":false}}} ``` -In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog with Keep Ends of Selected -Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection +In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog (`ui.menuDialog {command}`, key +`addon.select.editPointsOnly`) with Keep Ends of Selected Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection back. After a failed preview, a successful preview or OK clears the dialog's error only if that error is still the current status message. Messages from other commands stay displayed. From 1d6af09cff84cd608f9359d0a220081b1b5342eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 17:59:40 -0800 Subject: [PATCH 12/13] Scripts: a stop from end when show() fails ends the run When show() failed (an answer that could not be read, a host call that threw, or a handler that threw), the dialog's failure function called the host's end and dropped its result, so an Abort from end did not stop the run and the script could catch the error and finish. The failure function now returns that stop, and the answer and call paths end the run with it before the error reaches the script. --- crates/js/src/interp.rs | 23 ++++++++++----- crates/js/src/realm.rs | 17 +++++++---- crates/js/src/scriptui.rs | 22 +++++++++++---- crates/js/src/scriptui_tests.rs | 50 +++++++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 19 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 390dd3f5c8..517caa9c06 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -254,8 +254,10 @@ pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult /// resume function gives. pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; -/// What a [`Pause`] does with its kept values when its host call fails. -pub(crate) type FailFn = fn(&mut Interp, &[Value]); +/// What a [`Pause`] does with its kept values when its host call fails. An error it gives that is +/// not thrown (a stop, such as a host's Abort) ends the run in place of a thrown failure; a thrown +/// one gives way to the failure. +pub(crate) type FailFn = fn(&mut Interp, &[Value]) -> JsResult<()>; /// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to /// `resume` with `keep`, at once when the host answers at once. When the host waits @@ -280,14 +282,16 @@ pub(crate) struct Resumption { impl Resumption { /// The built-in does not get the host's answer: its failure function runs with its kept - /// values, which `thrown` is kept from collection with. - pub(crate) fn fail(self, interp: &mut Interp, thrown: &Value) { - let Some(failed) = self.failed else { return }; + /// values, which `thrown` is kept from collection with. → the stop the failure function + /// gave, which ends the run in place of `thrown`. + pub(crate) fn fail(self, interp: &mut Interp, thrown: &Value) -> JsResult<()> { + let Some(failed) = self.failed else { return Ok(()) }; let mark = interp.temp_roots.len(); interp.temp_roots.extend(self.keep.iter().cloned()); interp.temp_roots.push(thrown.clone()); - failed(interp, &self.keep); + let r = failed(interp, &self.keep); interp.temp_roots.truncate(mark); + r } } @@ -3585,6 +3589,7 @@ impl Interp { Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), _ => self.call(&host, &Value::Undefined, &args), }; + let mut stop = Ok(()); if let Err(e) = &answer && let Some(failed) = failed { @@ -3592,9 +3597,13 @@ impl Interp { if let Abrupt::Throw(v) = e { self.temp_roots.push(v.clone()); } - failed(self, &keep); + stop = failed(self, &keep); } self.temp_roots.truncate(mark); + // A stop from `failed` is not masked by a thrown error the script could catch. + if matches!(answer, Err(Abrupt::Throw(_))) { + stop?; + } let answer = answer?; let r = Resumption { resume, keep, failed }; if self.waiting && !was_waiting { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 4a810927ab..d673c92d26 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -591,14 +591,19 @@ impl Realm { let r = match written { // An answer that cannot be read as a value (too deep, too many entries, a stale host // reference) is thrown at the call, where the script can catch it, and a built-in - // that waited with the call does not get it: it fails as when its host call throws. + // that waited with the call does not get it: it fails as when its host call throws. A + // stop its failure gives (an Abort from the host) ends the run before the error is + // thrown. Err(Abrupt::Throw(thrown)) => { interp.stack.pop(); - if let Some(r) = interp.resuming.take() { - r.fail(interp, &thrown); - } - interp.answer_throws = true; - interp.push(thrown) + let stop = match interp.resuming.take() { + Some(r) => r.fail(interp, &thrown), + None => Ok(()), + }; + stop.and_then(|()| { + interp.answer_throws = true; + interp.push(thrown) + }) } written => written.and_then(|v| { interp.stack.pop(); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 47d8aeaffb..a5f74e7f54 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1543,16 +1543,21 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { }) } -/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. -fn failed(i: &mut Interp, keep: &[Value]) { - let Some(win) = arg(keep, 0).as_object() else { return }; +/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. → a stop +/// (an Abort) the host's `end` gave; an error `end` throws gives way to the failure. +fn failed(i: &mut Interp, keep: &[Value]) -> JsResult<()> { + let Some(win) = arg(keep, 0).as_object() else { return Ok(()) }; if classes(i).ok().and_then(|c| c.showing) != Some(win) { - return; + return Ok(()); } set_showing(i, None); if let Ok(end) = host_fn(i, "end") { - let _ = i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]); + match i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]) { + Ok(_) | Err(Abrupt::Throw(_)) => {} + Err(stop) => return Err(stop), + } } + Ok(()) } /// `show()` ends with `result`. @@ -1611,10 +1616,15 @@ fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResu Abrupt::Throw(t) => vec![t.clone()], _ => Vec::new(), }; + let thrown_error = !thrown.is_empty(); let mark = i.temp_roots.len(); i.temp_roots.extend(thrown); - failed(i, keep); + let stop = failed(i, keep); i.temp_roots.truncate(mark); + // A stop from `end` is not masked by a thrown error the script could catch. + if thrown_error { + stop?; + } } v } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index d8c7014ea0..dafe4dabc8 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -255,6 +255,56 @@ fn an_event_that_cannot_be_read_ends_show_and_the_dialog_can_show_again() { assert_eq!(seen.borrow().ends, vec![(0.0, false), (0.0, true)]); } +/// A realm whose `end` stops the run (an Abort) when `show()` ends without its result, whose +/// `open` throws when `open_fails`, and whose `wait` gives `events` in order, then waits. +fn stopping_realm(open_fails: bool, events: Vec) -> Realm { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let queue = RefCell::new(VecDeque::from(events)); + let open: HostFunction = Rc::new(move |_| if open_fails { Err(HostError::Error("no window".into())) } else { Ok(Data::Undefined) }); + let wait: HostFunction = Rc::new(move |_| queue.borrow_mut().pop_front().ok_or(HostError::Wait)); + let end: HostFunction = Rc::new(|args| match args.get(1) { + Some(Data::Bool(true)) => Ok(Data::Undefined), + _ => Err(HostError::Abort("stopped by the host".into())), + }); + let items = vec![("open".into(), HostItem::Function(open)), ("wait".into(), HostItem::Function(wait)), ("end".into(), HostItem::Function(end))]; + r.define_script_ui(items).unwrap(); + r +} + +fn is_host_stop(e: &RunError) -> bool { + e.kind == RunErrorKind::Limit(LimitKind::Host) && e.message == "stopped by the host" +} + +/// A stop the host's `end` gives when `show()` fails ends the run: the script cannot catch the +/// failure and go on, whether the event could not be read, the host call threw or a handler threw. +#[test] +fn a_stop_from_end_when_show_fails_ends_the_run() { + let caught = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \ + b.onClick = function () { throw new Error('handler'); }; \ + try { w.show(); } catch (e) {} 'went on'"; + + let mut r = stopping_realm(false, Vec::new()); + r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 }); + let mut nested = Data::Null; + for _ in 0..20 { + nested = Data::Array(vec![nested]); + } + r.start(caught).unwrap(); + assert_eq!(r.advance(100_000).unwrap(), Progress::Paused); + assert!(r.waits()); + let answered = r.answer(nested); + assert!(answered.as_ref().is_err_and(is_host_stop), "unreadable event: {answered:?}"); + + let mut r = stopping_realm(true, Vec::new()); + let ran = r.run(caught); + assert!(ran.as_ref().is_err_and(is_host_stop), "open threw: {ran:?}"); + + let mut r = stopping_realm(false, vec![click(1)]); + let ran = r.run(caught); + assert!(ran.as_ref().is_err_and(is_host_stop), "handler threw: {ran:?}"); +} + #[test] fn types_that_are_not_available_yet_throw_errors_that_say_so() { for (source, want) in [ From 1e4e7cfbfe678c73961bf726a09975a0a310b31d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 18:19:35 -0800 Subject: [PATCH 13/13] Selection: a path selected whole shows its anchors without direction handles With the Selection tool, a selected path drew the direction handles of every anchor, so it looked as if Direct Selection were active. The canvas marks now draw the handles only where a tool drags them: a partial selection's anchors, a selected segment, and a path selected itself under a tool that edits anchors. Every other selected path, including the members of a group or compound path selected whole, shows its anchors selected with no handles. A lone anchor selected whole is drawn with its handles retracted. --- crates/ui-egui/src/canvas/selection.rs | 48 +++++++++-- crates/ui-egui/src/canvas/selection/tests.rs | 87 +++++++++++++++++--- 2 files changed, 116 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/canvas/selection.rs b/crates/ui-egui/src/canvas/selection.rs index dd2b85fcca..4f50576df8 100644 --- a/crates/ui-egui/src/canvas/selection.rs +++ b/crates/ui-egui/src/canvas/selection.rs @@ -29,7 +29,6 @@ use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit // PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract. use super::{BodyKind, VectorcraftApp, Win}; // PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`). -// PLAN: BezierOverlay selects anchors of every path under `HandlesShown`, so a whole-selected container draws handles that the old marks hid outside Direct Selection. /// The anchor square's side at Selection & Anchor Display › Size 3, the default, in points. const ANCHOR_AT_DEFAULT_SIZE: f32 = 5.0; @@ -60,6 +59,12 @@ pub(super) struct Anchors { pub paths: Vec, /// The selected anchors and the selected segment. pub selection: PathSelection, + /// The paths whose anchors show selected without direction handles: paths selected whole, or inside a container + /// selected whole, under a tool that does not drag handles, and the paths inside a container selected whole under + /// one that does ([`vectorcraft_tools::catalog::edits_anchors`]). + pub plain: Vec, + /// Every anchor of `plain`, selected. + pub plain_selection: PathSelection, /// Anchors as squares, or as circles under the Curvature tool. pub shown: AnchorsShown, /// Whose direction handles show. @@ -259,15 +264,21 @@ fn grid_path(key: u64, points: impl Iterator, color: Color32) -> E /// The anchors and handles of the selection. An object selected whole has every anchor selected, and so do the /// paths inside a group, compound path or clip group selected whole; with Direct Selection's partial selection only -/// the chosen anchors are, and a selected segment hollows the others. `tool_points` is whether the tool draws its own -/// points (the Curvature tool while it draws), which leaves nothing here. `tool` is the tool whose marks show -/// ([`super::shown_tool`]). Nothing too big to outline, and nothing during Halftone Preview. +/// the chosen anchors are, and a selected segment hollows the others. Direction handles show for a partial selection's +/// anchors, for a selected segment, and for a path selected whole when `tool` drags handles +/// ([`vectorcraft_tools::catalog::edits_anchors`]); every other path goes to [`Anchors::plain`], whose anchors show +/// without handles. `tool_points` is whether the tool draws its own points (the Curvature tool while it draws), which +/// leaves nothing here. `tool` is the tool whose marks show ([`super::shown_tool`]). Nothing too big to outline, and +/// nothing during Halftone Preview. pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> Anchors { let curvature = tool == "curvature"; + let drags_handles = vectorcraft_tools::catalog::edits_anchors(tool); let prefs = &app.session.prefs; let mut out = Anchors { paths: vec![], selection: PathSelection::default(), + plain: vec![], + plain_selection: PathSelection::default(), shown: if curvature { AnchorsShown::Curvature } else { AnchorsShown::All }, handles: if prefs.show_handles_multiple_anchors { HandlesShown::Selected } else { HandlesShown::OneAnchor }, segment_mark: SegmentMark::Line, @@ -279,6 +290,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin let (sel, hides) = (&st.selection, ViewHides::of(app)); // The selected anchors by path, and the selected segment with its path. let mut chosen: Vec<(u64, Vec)> = vec![]; + let mut plain: Vec<(u64, Vec)> = vec![]; let mut segment: Option<(u64, KnotRef)> = None; for id in &sel.objects { let Some(node) = st.doc.node(*id) else { continue }; @@ -295,8 +307,15 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin return; } let NodeKind::Path { path, .. } = &c.kind else { return }; - out.paths.push(edit_path(c.id.0, path, color)); let segments = sel.segments.get(&c.id); + // The handles the tools drag ([`vectorcraft_tools::direct`]'s `handle_anchors`): a partial selection's, a + // selected segment's, and those of a path selected itself under a tool that edits anchors. + if partial.is_none() && segments.is_none() && !(drags_handles && c.id == *id) { + out.plain.push(edit_path(c.id.0, path, color)); + plain.push((c.id.0, path.anchors().map(|(si, ai, _)| KnotRef::new(si, ai)).collect())); + return; + } + out.paths.push(edit_path(c.id.0, path, color)); if let Some(&(si, seg)) = segments.and_then(|s| s.iter().next()) { segment.get_or_insert((c.id.0, KnotRef::new(si, seg))); } @@ -326,6 +345,14 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin ); selection.others = by_key(chosen.into_iter().filter(|(key, _)| Some(*key) != primary)); out.selection = selection; + // `show` draws `plain` with `HandlesShown::OneAnchor`, which shows handles only while one anchor is selected. A + // lone anchor is drawn with its handles retracted instead; the selection's outline still draws its path. + if plain.iter().map(|(_, knots)| knots.len()).sum::() == 1 { + for knot in out.plain.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) { + (knot.in_ctrl, knot.out_ctrl) = (knot.anchor, knot.anchor); + } + } + out.plain_selection.others = by_key(plain); out } @@ -660,6 +687,15 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp .path_options(&anchors.options) .show_at(ui, rect); } + if !anchors.plain.is_empty() { + let mut paths = anchors.plain.clone(); + let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection) + .tool(BezierTool::Anchors) + .handles(HandlesShown::OneAnchor) + .anchors(anchors.shown) + .path_options(&anchors.options) + .show_at(ui, rect); + } let dots = &marks.dots; if !(dots.centers.is_empty() && dots.origins.is_empty() && dots.key_anchor.is_none()) { SelectionDots { common: Common::new(), dots }.label("Selection dots").show_at(ui, rect); @@ -734,7 +770,7 @@ impl SelectionMarks { o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift)); o.revision = outline_revision(&o.paths, o.key.as_ref(), o.color.to_array()); } - for knot in self.anchors.paths.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) { + for knot in self.anchors.paths.iter_mut().chain(&mut self.anchors.plain).flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) { knot.anchor += by; knot.in_ctrl += by; knot.out_ctrl += by; diff --git a/crates/ui-egui/src/canvas/selection/tests.rs b/crates/ui-egui/src/canvas/selection/tests.rs index e413a5655c..42e0bc620b 100644 --- a/crates/ui-egui/src/canvas/selection/tests.rs +++ b/crates/ui-egui/src/canvas/selection/tests.rs @@ -50,6 +50,11 @@ fn marks(app: &VectorcraftApp) -> Anchors { anchors(app, app.session.active().unwrap(), app.session.tool_id(), false) } +/// Every path whose anchors show, with handles or without. +fn shown_paths(anchors: &Anchors) -> Vec<&EditPath> { + anchors.paths.iter().chain(&anchors.plain).collect() +} + fn all_selected(selection: &PathSelection) -> usize { selection.anchors.len() + selection.others.iter().map(|(_, knots)| knots.len()).sum::() } @@ -215,7 +220,7 @@ fn a_clip_group_over_a_huge_path_shows_its_clipping_path() { vec![vectorcraft_geom::Rect::new(100.0, 100.0, 200.0, 200.0)], "the square's outline, not the bounds of the huge art" ); - assert_eq!(marks(&app).paths.iter().map(|p| p.anchor_count()).sum::(), 4, "and its four anchors"); + assert_eq!(shown_paths(&marks(&app)).iter().map(|p| p.anchor_count()).sum::(), 4, "and its four anchors"); } #[test] @@ -228,13 +233,13 @@ fn a_huge_selection_shows_its_bounds_instead_of_every_outline() { assert_eq!((huge.len(), huge[0].0, huge[0].1.len()), (1, color, 1), "one bounds path in the layer colour"); let st = app.session.active().unwrap(); assert!(outlines(&app, st)[0].paths[0].elements().len() < 10, "a rectangle, not the outline"); - assert!(marks(&app).paths.is_empty(), "no anchors either"); + assert!(shown_paths(&marks(&app)).is_empty(), "no anchors either"); assert!(dots(&app, st).origins.is_empty()); app.run("edit.undo", json!({})).unwrap(); app.run("path.create", json!({"d": format!("M20 20 {} Z", points(200))})).unwrap(); let st = app.session.active().unwrap(); assert!(outlines(&app, st)[0].paths[0].elements().len() > 200, "a path of few points is outlined whole"); - assert_eq!(marks(&app).paths.len(), 1); + assert_eq!(shown_paths(&marks(&app)).len(), 1); } #[test] @@ -389,7 +394,7 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() { app.run("select.set", json!({"ids": [group.0]})).unwrap(); let st = app.session.active().unwrap(); let outlined: Vec> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect(); - let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let anchored = shown_paths(&marks(app)).iter().map(|p| p.anchor_count()).collect::>(); let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec()); (outlined, anchored, hovered) }; @@ -422,7 +427,7 @@ fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() { app.run("select.set", json!({"ids": [group.0]})).unwrap(); let st = app.session.active().unwrap(); let outlined: Vec = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect(); - let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::>(); + let anchored = shown_paths(&marks(app)).iter().map(|p| p.anchor_count()).collect::>(); let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box()); (outlined, anchored, hovered) }; @@ -554,9 +559,64 @@ fn the_anchors_of_a_container_selected_whole_draw_selected() { app.select_tool("directSelection"); app.run("select.set", json!({"ids": [group.0]})).unwrap(); let shown = marks(&app); - // The ellipse's four anchors and the square's four. - assert_eq!(all_selected(&shown.selection), 8); - assert_eq!(shown.paths.len(), 2); + // The ellipse's four anchors and the square's four, drawn without handles: the tools drag only the handles of a + // path selected itself. + assert_eq!(all_selected(&shown.plain_selection), 8); + assert_eq!(shown.plain.len(), 2); + assert!(shown.paths.is_empty() && all_selected(&shown.selection) == 0, "no member's handles show"); +} + +/// The Selection tool shows a path selected whole with every anchor selected and no direction handles; Direct +/// Selection shows the same path's handles, and a partial selection's anchors keep theirs under either tool. +#[test] +fn the_selection_tool_shows_a_whole_paths_anchors_without_handles() { + let (mut app, curve) = scene(); + let count = { + let NodeKind::Path { path, .. } = &app.session.active().unwrap().doc.node(curve).unwrap().kind else { panic!("a path") }; + path.anchor_count() + }; + app.select_tool("selection"); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let shown = marks(&app); + assert!(shown.paths.is_empty(), "no path of the Selection tool's marks shows handles"); + assert_eq!(shown.plain.iter().map(|p| p.key).collect::>(), vec![curve.0]); + assert_eq!(all_selected(&shown.plain_selection), count, "every anchor draws selected"); + + app.select_tool("directSelection"); + let direct = marks(&app); + assert!(direct.plain.is_empty(), "Direct Selection draws the path with its handles"); + assert_eq!((direct.selection.path, direct.selection.anchors.len()), (Some(curve.0), count)); + + app.select_tool("selection"); + app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 2]], "mode": "set"})).unwrap(); + let partial = marks(&app); + assert!(partial.plain.is_empty(), "a partial selection keeps its anchor's handles"); + assert_eq!(partial.selection.anchors, vec![KnotRef::new(0, 2)]); +} + +/// A lone anchor selected whole under the Selection tool is drawn with its handles retracted, since the overlay shows +/// handles while one anchor is selected. +#[test] +fn a_lone_anchor_selected_whole_shows_no_handles() { + let mut app = blank(); + let point = id_of(&app.run("path.create", json!({"d": "M40 40"})).unwrap()); + app.run("path.setHandle", json!({"id": point.0, "anchor": 0, "which": "out", "x": 60, "y": 10, "independent": true})).unwrap(); + let NodeKind::Path { path, .. } = &app.session.active().unwrap().doc.node(point).unwrap().kind else { panic!("a path") }; + assert_eq!((path.anchor_count(), path.subpaths[0].anchors[0].h_out), (1, Point::new(60.0, 10.0)), "one anchor with a handle"); + app.select_tool("selection"); + app.run("select.set", json!({"ids": [point.0]})).unwrap(); + let shown = marks(&app); + assert_eq!(all_selected(&shown.plain_selection), 1); + let knots: Vec<_> = shown.plain.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots).collect(); + assert_eq!(knots.len(), 1); + assert!(knots.iter().all(|k| k.in_ctrl == k.anchor && k.out_ctrl == k.anchor), "the lone anchor's handles are retracted"); + + // Two anchors keep their handles in the marks: the overlay shows none while more than one is selected. + let curve = id_of(&app.run("path.create", json!({"d": "M40 140 C60 110 90 110 110 140"})).unwrap()); + app.run("select.set", json!({"ids": [curve.0]})).unwrap(); + let two = marks(&app); + assert_eq!(all_selected(&two.plain_selection), 2); + assert!(two.plain.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots).any(|k| k.out_ctrl != k.anchor), "the curve keeps its shape"); } #[test] @@ -844,9 +904,9 @@ fn the_outline_revision_follows_what_is_drawn() { #[test] fn an_empty_selection_has_no_marks() { let (mut app, _) = scene(); - assert!(!seen(&app).is_empty() && !marks(&app).paths.is_empty()); + assert!(!seen(&app).is_empty() && !shown_paths(&marks(&app)).is_empty()); app.run("select.none", json!({})).unwrap(); - assert!(seen(&app).is_empty() && marks(&app).paths.is_empty()); + assert!(seen(&app).is_empty() && shown_paths(&marks(&app)).is_empty()); let st = app.session.active().unwrap(); assert_eq!(dots(&app, st).centers.len() + dots(&app, st).origins.len(), 0); } @@ -891,7 +951,7 @@ thread_local! { fn kept(app: &VectorcraftApp) -> (Vec>, usize) { let marks = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks"); let boxes = marks.outlines.iter().map(|o| o.paths.iter().map(|p| p.bounding_box()).collect()).collect(); - (boxes, all_selected(&marks.anchors.selection)) + (boxes, all_selected(&marks.anchors.selection) + all_selected(&marks.anchors.plain_selection)) } // Whole-app frames build the selection's marks once for each change: none in frames that change nothing, one after @@ -914,7 +974,8 @@ fn the_canvas_builds_the_selection_marks_once_per_change() { assert_eq!(frames(&mut app, 5), 1, "a new selection builds its marks once"); let st = app.session.active().unwrap(); let boxes = outlines(&app, st).iter().map(|o| o.paths.iter().map(|p| p.bounding_box()).collect()).collect::>(); - assert_eq!(kept(&app), (boxes, all_selected(&marks(&app).selection))); + let shown = marks(&app); + assert_eq!(kept(&app), (boxes, all_selected(&shown.selection) + all_selected(&shown.plain_selection))); app.select_tool("directSelection"); assert_eq!(frames(&mut app, 5), 1, "another tool builds the marks once"); } @@ -932,7 +993,7 @@ fn points_of(outlines: &[Outlined], anchors: &Anchors, dots: &Dots) -> Vec