From a315b7ef6b2c10b4057f13a09f116d4b58cdeff2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 17:25:12 -0800 Subject: [PATCH 1/8] Tools: setting a tool option with a bad value returns an error tool.setOption checks every option it is given before it sets any. An option the tool does not have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option, for example "tool `smooth`: `fidelity` must be a number from 0.05 to 100". On an error no option, saved preference or undo step changes, also when another option in the same call is good. `{}` reads the options and sets nothing. A `tool` that is not a string, a `values` that is not an object, a `key` without a `value` and an option given both as `key` and in `values` are errors too. - Tool::check_option (and check_options for options set together) is added beside set_option, and every tool with options implements it. A tool without options takes none. Most checks use the range the setter clamped to. The Arc tool's lengthX and lengthY now take a number greater than 0 and at most 1e6, and the Line tool's length 0 to 1e6; before, a negative length was taken as its absolute value and the Arc lengths had no upper limit. The Live Paint tools and the Shape Builder use check_builder_options, so their width and gapLength are still clamped to their range. - A Place `current` given with a new `queue` is an index into that queue, and the queue is set first. A parametric shape's `kind` is set before the values given with it, and those values are checked against the new kind's ranges. - Tool Options dialogs (freehand, Liquify, Symbolism, Live Paint, Shape Builder, Objects on Path, Flare, the grid, arc and line tools and the path add-ons) stay open when an option is refused. - docs/control-protocol.md, docs/mcp.md and the tool.setOption params text describe the errors. --- crates/engine/src/tests/draw2.rs | 16 +- crates/engine/src/tests/toolsettings.rs | 102 ++++++++++++ crates/engine/src/tooling.rs | 28 +++- crates/mcp/src/tests/liquify.rs | 15 ++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/addons/anchor_eraser.rs | 10 ++ crates/tools/src/addons/box3d.rs | 29 ++++ crates/tools/src/addons/contour.rs | 9 + crates/tools/src/addons/corner_tool.rs | 10 ++ crates/tools/src/addons/extend_path.rs | 8 + crates/tools/src/addons/parametric_shape.rs | 26 +++ crates/tools/src/addons/shared_edge.rs | 10 ++ crates/tools/src/addons/smart_pen.rs | 4 + crates/tools/src/builder.rs | 3 + crates/tools/src/builder/live_paint.rs | 8 + crates/tools/src/cropimage.rs | 13 ++ crates/tools/src/cut.rs | 9 + crates/tools/src/dimension.rs | 7 + crates/tools/src/distort/liquify.rs | 19 +++ crates/tools/src/distort/puppet.rs | 9 + crates/tools/src/draw2/family.rs | 19 +++ crates/tools/src/draw2/gesture.rs | 20 +++ crates/tools/src/extra.rs | 12 ++ crates/tools/src/intertwine.rs | 4 + crates/tools/src/lib.rs | 13 ++ crates/tools/src/objects_on_path.rs | 9 + crates/tools/src/option_check.rs | 154 ++++++++++++++++++ crates/tools/src/place.rs | 56 +++++++ crates/tools/src/shape.rs | 14 ++ crates/tools/src/symbolism.rs | 12 ++ crates/tools/src/text/tool.rs | 19 +++ crates/tools/src/xform/artboard.rs | 12 ++ crates/tools/src/xform/eyedropper.rs | 10 ++ crates/tools/src/xform/free.rs | 9 + crates/tools/src/xform/transform.rs | 9 + crates/ui-egui/src/addons/pathtools.rs | 7 +- crates/ui-egui/src/dialogs.rs | 10 ++ crates/ui-egui/src/dialogs/flare_options.rs | 15 +- crates/ui-egui/src/dialogs/freehand.rs | 4 +- crates/ui-egui/src/dialogs/freehand/tests.rs | 18 ++ crates/ui-egui/src/dialogs/liquify.rs | 4 +- .../ui-egui/src/dialogs/live_paint_bucket.rs | 4 +- .../src/dialogs/live_paint_selection.rs | 4 +- .../src/dialogs/objects_on_path_options.rs | 4 +- .../src/dialogs/shape_builder_options.rs | 4 +- crates/ui-egui/src/dialogs/shapes.rs | 18 +- .../ui-egui/src/dialogs/symbolism_options.rs | 4 +- .../src/dialogs/tests_rectangular_grid.rs | 14 ++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 2 +- docs/control-protocol.md | 6 +- docs/mcp.md | 12 ++ docs/target-app-parity.md | 1 + 53 files changed, 796 insertions(+), 46 deletions(-) create mode 100644 crates/tools/src/option_check.rs diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 79dbd366f6..ea6e382b5f 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -5185,14 +5185,20 @@ fn pencil_at_the_lowest_fidelity_takes_degenerate_strokes() { } } -/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's stays at 0.05 or more. +/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's 0.05 or more: a lower Fidelity is +/// an error that leaves the option as it was. #[test] fn pencil_option_takes_a_hundredth_and_smooth_keeps_its_floor() { let mut s = session(); - for (tool, want) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] { - s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap(); - assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(want), "{tool}"); - s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})).unwrap(); + for (tool, floor) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] { + let before = s.tool_options_of(tool)["fidelity"].clone(); + let e = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap_err(); + assert_eq!(e, format!("tool `{tool}`: `fidelity` must be a number from {floor} to 100")); + assert_eq!(s.tool_options_of(tool)["fidelity"], before, "{tool}"); + s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": floor}})).unwrap(); + assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(floor), "{tool}"); + let hundredth = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})); + assert_eq!(hundredth.is_ok(), tool != "smooth", "{tool}"); assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(if tool == "smooth" { 0.05 } else { 0.02 }), "{tool}"); } } diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index e896a0ab32..eae2a16aa4 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -324,3 +324,105 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() { assert_eq!(s.tool_options()["fidelity"], json!(3.0), "{id}"); } } + +/// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an +/// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also +/// when another option given with it is good, and nothing is saved or recorded for undo. +#[test] +fn bad_option_values_are_errors_that_set_nothing() { + let mut s = session(); + select(&mut s, "smooth"); + let (options, saved, undo) = (s.tool_options(), s.prefs.tool_settings.clone(), s.doc().unwrap().history.undo.len()); + let fidelity = "tool `smooth`: `fidelity` must be a number from 0.05 to 100"; + for bad in [json!("abc"), json!(true), json!(-3), json!(1e9), json!(null), json!([2])] { + assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": bad})).unwrap_err(), fidelity, "{bad}"); + } + let cases = [ + (json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"), + (json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"), + (json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"), + (json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"), + (json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"), + (json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"), + ( + json!({"tool": "mirrorCut", "key": "axis", "value": "diagonal"}), + "tool `mirrorCut`: `axis` must be one of `vertical`, `horizontal`, `free`", + ), + (json!({"tool": "selection", "key": "fidelity", "value": 4}), "tool `selection`: unknown option `fidelity`"), + (json!({"values": [1]}), "`values` must be an object"), + (json!({"tool": 3, "key": "fidelity", "value": 4}), "`tool` must be a tool id"), + (json!({"key": "fidelity"}), "`value` is missing for `fidelity`"), + ]; + for (p, want) in cases { + assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); + } + assert_eq!(s.tool_options_of("pencil")["closeWithin"], session().tool_options_of("pencil")["closeWithin"]); + assert_eq!((s.tool_options(), &s.prefs.tool_settings, s.doc().unwrap().history.undo.len()), (options, &saved, undo)); + // A good value after the errors is set and read back. + assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": 9})).unwrap()["fidelity"], json!(9.0)); +} + +/// `tool.setOption {}` reads the options, of the active tool or of the tool named, and saves nothing. +#[test] +fn an_empty_set_option_reads_and_saves_nothing() { + let mut s = session(); + select(&mut s, "smooth"); + let saved = s.prefs.tool_settings.clone(); + assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options()); + assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare")); + assert_eq!(s.prefs.tool_settings, saved); +} + +/// A Place queue with a malformed entry is an error, and the queue held stays as it was. +#[test] +fn a_malformed_place_queue_is_an_error() { + let mut s = session(); + select(&mut s, "place"); + let entry = json!({"params": {"svg": ""}, "name": "a", "width": 10, "height": 10}); + s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry]}})).unwrap(); + let bad = json!({"params": {}, "name": "b", "width": "wide", "height": 10}); + let e = s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry, bad]}})).unwrap_err(); + assert!(e.starts_with("tool `place`: `queue` must be"), "{e}"); + assert_eq!(s.tool_options()["names"], json!(["a"])); + assert_eq!( + s.set_tool_option_cmd(&json!({"key": "current", "value": 1})).unwrap_err(), + "tool `place`: `current` must be the index of a queued file, from 0 to 0" + ); +} + +/// A `current` given with a new Place queue picks among the files of that queue. +#[test] +fn a_place_queue_and_its_current_file_set_together() { + let mut s = session(); + select(&mut s, "place"); + let entry = |name: &str| json!({"params": {"svg": ""}, "name": name, "width": 10, "height": 10}); + let queue = json!({"entries": [entry("a"), entry("b"), entry("c")]}); + let out = s.set_tool_option_cmd(&json!({"values": {"queue": queue, "current": 2}})).unwrap(); + assert_eq!((out["names"].clone(), out["current"].clone()), (json!(["a", "b", "c"]), json!(2))); + let short = json!({"entries": [entry("d")]}); + let e = s.set_tool_option_cmd(&json!({"values": {"queue": short, "current": 2}})).unwrap_err(); + assert_eq!(e, "tool `place`: `current` must be the index of a queued file, from 0 to 0"); + assert_eq!(s.tool_options()["names"], json!(["a", "b", "c"]), "a refused call keeps the queue held"); +} + +/// A value given with a parametric shape's new `kind` is checked against that kind's range and +/// set on it, whether the tool is chosen or not. +#[test] +fn a_parametric_shape_kind_and_its_values_set_together() { + for active in [false, true] { + let mut s = session(); + if active { + select(&mut s, "parametricShape"); + } + let set = |s: &mut Session, values: serde_json::Value| s.set_tool_option_cmd(&json!({"tool": "parametricShape", "values": values})); + set(&mut s, json!({"kind": "polygon"})).unwrap(); + let out = set(&mut s, json!({"kind": "star", "a": 0.8})).unwrap(); + assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(0.8)), "active {active}"); + set(&mut s, json!({"kind": "ring"})).unwrap(); + let out = set(&mut s, json!({"kind": "star", "a": 1.0})).unwrap(); + assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(1.0)), "active {active}"); + let e = set(&mut s, json!({"kind": "ring", "a": 1.0})).unwrap_err(); + assert!(e.contains("`a`"), "{e}"); + assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing"); + } +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 4dedfe7b28..df7ef4b1d8 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1273,9 +1273,14 @@ impl Session { } let active = id.is_none_or(|id| id == self.tool.id()); self.tool_set_since_reset |= active; + // The Place queue and a parametric shape's kind are set first: setting the queue starts + // again at its first file, and a `current` given with it is an index into it; setting the + // kind puts the shape's other numbers back to that kind's, and those given with it are its. + let first = |k: &str| k == "queue" || k == "kind"; + let ordered = || values.iter().filter(|(k, _)| first(k)).chain(values.iter().filter(|(k, _)| !first(k))); let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default())); let t = other.as_deref_mut().unwrap_or(self.tool.as_mut()); - for (k, v) in values { + for (k, v) in ordered() { t.set_option(k, v); } Self::store_tool_settings(&mut self.prefs, t); @@ -1287,7 +1292,7 @@ impl Session { // active tool. if let Some(lender) = self.lender.as_deref_mut() { if lender.id() == other.id() { - for (k, v) in values { + for (k, v) in ordered() { lender.set_option(k, v); } } @@ -1303,17 +1308,20 @@ impl Session { /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: - /// the active tool) → its options. + /// the active tool) → its options. With no option given, the options are read and nothing is + /// set. Every option given is checked first ([`vectorcraft_tools::Tool::check_option`]): an + /// unknown option, a value of the wrong type or a number out of range is an error that sets + /// none of them. pub fn set_tool_option_cmd(&mut self, p: &Value) -> std::result::Result { - let tool = p.get("tool").and_then(Value::as_str); + let (tool, values) = vectorcraft_tools::option_check::set_option_params(p)?; if let Some(t) = tool && vectorcraft_tools::tool_info(t).is_none() { return Err(format!("unknown tool `{t}`")); } - let mut values = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default(); - if let Some(k) = p.get("key").and_then(Value::as_str) { - values.insert(k.to_string(), p.get("value").cloned().unwrap_or(Value::Null)); + let active = tool.is_none_or(|t| t == self.tool.id()); + if values.is_empty() { + return Ok(self.tool_options_of(tool.unwrap_or(self.tool.id()))); } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; @@ -1334,8 +1342,12 @@ impl Session { return Err("Unknown dimension mode".into()); } } + match tool.filter(|_| !active) { + Some(id) => vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?, + None => vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?, + } // The active tool's merge being computed is applied with the options it was started with. - if tool.is_none_or(|t| t == self.tool.id()) { + if active { self.finish_tool_edit_later().map_err(|e| e.to_string())?; } Ok(self.set_tool_options(tool, &values)) diff --git a/crates/mcp/src/tests/liquify.rs b/crates/mcp/src/tests/liquify.rs index 4760380bc2..c6d3862384 100644 --- a/crates/mcp/src/tests/liquify.rs +++ b/crates/mcp/src/tests/liquify.rs @@ -28,6 +28,21 @@ fn tool_options_are_set_headless_and_kept_across_tool_switches() { assert_eq!(command(&mut h, "tool.setOption", json!({}))["detail"], json!(6.0)); } +/// A value the tool refuses is an error result naming the tool and the option, and the options +/// stay as they were, the good value given with it included. +#[test] +fn a_refused_option_value_is_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for values in [json!({"width": 64, "detail": 99}), json!({"width": 64, "detail": "fine"})] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": {"values": values}})); + assert!(r.is_error, "{r:?}"); + assert!(format!("{:?}", r.content).contains("tool `warp`: `detail` must be a number from 1 to 10"), "{r:?}"); + } + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + #[test] fn pointer_gestures_carry_pen_pressure() { let bloat = |pressure: f64| { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 037f8cd89b..7783f72f1f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -775,7 +775,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( "tool.toggleTouchMode", diff --git a/crates/tools/src/addons/anchor_eraser.rs b/crates/tools/src/addons/anchor_eraser.rs index 1eae255bc2..114e2b8e7a 100644 --- a/crates/tools/src/addons/anchor_eraser.rs +++ b/crates/tools/src/addons/anchor_eraser.rs @@ -152,6 +152,16 @@ impl Tool for AnchorEraserTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "size" => c::number(key, v, SIZE_RANGE.0, SIZE_RANGE.1), + "tolerance" => c::number(key, v, TOLERANCE_RANGE.0, TOLERANCE_RANGE.1), + "pressure" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index b0ecdc350e..e4f4b272c5 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -729,4 +729,33 @@ impl Tool for Box3dTool { _ => {} } } + + /// The options within their ranges. Any finite arc angle is taken: it is kept from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let max_radius = crate::shape::MAX_CORNER_RADIUS; + match key { + "shape" => c::one_of(key, v, &["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"]), + "cornerRadius" => c::number(key, v, 0.0, max_radius), + "cornerRadii" => { + let radii = v.as_array().filter(|a| a.len() == 4); + if radii.is_some_and(|a| a.iter().all(|r| r.as_f64().is_some_and(|r| r.is_finite() && (0.0..=max_radius).contains(&r)))) { + Ok(()) + } else { + Err(format!("`cornerRadii` must be four numbers from 0 to {max_radius}")) + } + } + "arcStart" | "arcEnd" => c::finite(key, v), + "arcMode" => c::one_of(key, v, &["whole", "pie", "chord", "arc"]), + "sides" | "points" => c::whole(key, v, 3, 1000), + "starRatio" => c::number(key, v, 0.01, 1.0), + "rounded" | "randomized" => c::number(key, v, -10.0, 10.0), + "turns" => c::number(key, v, 0.01, 1024.0), + "divergence" => c::number(key, v, 0.0, 1000.0), + "innerRadius" => c::number(key, v, 0.0, 0.999), + "angleX" | "angleY" | "angleZ" => c::number(key, v, -180.0, 180.0), + "cornerSymmetry" | "polyIsStar" | "clockwise" | "parallelX" | "parallelY" | "parallelZ" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } diff --git a/crates/tools/src/addons/contour.rs b/crates/tools/src/addons/contour.rs index e77bb29eed..3bac5a6649 100644 --- a/crates/tools/src/addons/contour.rs +++ b/crates/tools/src/addons/contour.rs @@ -248,6 +248,15 @@ impl Tool for ContourTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "corners" if value.as_str().and_then(Corners::parse).is_some() => Ok(()), + "corners" => Err("`corners` must be one of `sharp`, `round`, `square`".into()), + "miterLimit" => crate::option_check::number(key, value, 1.0, 500.0), + _ => Err(crate::option_check::unknown(key)), + } + } + fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/addons/corner_tool.rs b/crates/tools/src/addons/corner_tool.rs index 177926837e..a92f327d93 100644 --- a/crates/tools/src/addons/corner_tool.rs +++ b/crates/tools/src/addons/corner_tool.rs @@ -381,6 +381,16 @@ impl Tool for CornerTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "radius" => c::number(key, v, 0.0, MAX_RADIUS), + "kind" if serde_json::from_value::(v.clone()).is_ok() => Ok(()), + "kind" => Err("`kind` must be one of `round`, `invertedRound`, `chamfer`".into()), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs index d1f54861ca..b53d52d3e8 100644 --- a/crates/tools/src/addons/extend_path.rs +++ b/crates/tools/src/addons/extend_path.rs @@ -203,6 +203,14 @@ impl Tool for ExtendPathTool { self.mode = Mode(m); } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key != "mode" { + return Err(crate::option_check::unknown(key)); + } + let ids: Vec<&str> = ExtendMode::ALL.iter().map(|m| m.id()).collect(); + crate::option_check::one_of(key, v, &ids) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/parametric_shape.rs b/crates/tools/src/addons/parametric_shape.rs index d16cb63935..61ce83ecde 100644 --- a/crates/tools/src/addons/parametric_shape.rs +++ b/crates/tools/src/addons/parametric_shape.rs @@ -434,6 +434,32 @@ impl Tool for ParametricShapeTool { self.next = s; } } + + /// The numbers [`Self::options`] shows, each as [`apply`] checks it; null is not a value. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if self.options().get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + apply(self.next, &json!({ key: v })).map(|_| ()) + } + + /// The options together, as [`apply`] takes them: a `kind` given with them sets the kind + /// first, and the other values are checked against that kind's ranges. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let options = self.options(); + for (key, v) in values { + if options.get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + } + apply(self.next, &Value::Object(values.clone())).map(|_| ()) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/shared_edge.rs b/crates/tools/src/addons/shared_edge.rs index d11261800a..703e8e6f3f 100644 --- a/crates/tools/src/addons/shared_edge.rs +++ b/crates/tools/src/addons/shared_edge.rs @@ -214,6 +214,16 @@ impl Tool for SharedEdgeTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, DIAMETER_RANGE.0, DIAMETER_RANGE.1), + "tolerance" => c::number(key, v, 0.0, MAX_COINCIDENCE), + "together" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index cd72f1dd40..40ba482f8b 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -624,6 +624,10 @@ impl Tool for SmartPenTool { } } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "next" { crate::option_check::one_of(key, v, &["curved", "straight"]) } else { Err(crate::option_check::unknown(key)) } + } } #[cfg(test)] diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 2190d34180..55214e8b7b 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -775,6 +775,9 @@ impl Tool for ShapeBuilderTool { self.cache.clear(); self.cache.gap = self.gap(); } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_builder_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } /// Why `tool.setOption` cannot give the builder-family tool `tool` the options `values`, checked diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index 6b744e4435..fc27bbde59 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -437,6 +437,10 @@ impl Tool for LivePaintBucketTool { self.hover = LpHover::None; } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } + fn waiting(&self) -> bool { self.cache.waiting() } @@ -737,4 +741,8 @@ impl Tool for LivePaintSelectionTool { } self.hover = LpHover::None; } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index ff716bf171..e0fa322e3e 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -268,6 +268,19 @@ impl Tool for CropImageTool { }; } + /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key != "rect" { + return Err(crate::option_check::unknown(key)); + } + let numbers = value.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(Value::as_f64).collect::>>()); + match numbers.as_deref() { + _ if value.is_null() => Ok(()), + Some([x, y, w, h]) if [x, y, w, h].iter().all(|n| n.is_finite()) && *w >= 0.0 && *h >= 0.0 => Ok(()), + _ => Err(format!("`{key}` must be [x, y, width, height]: four finite numbers, width and height not negative")), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.reset(); vec![] diff --git a/crates/tools/src/cut.rs b/crates/tools/src/cut.rs index 906a632fb3..514e41e4c0 100644 --- a/crates/tools/src/cut.rs +++ b/crates/tools/src/cut.rs @@ -214,6 +214,15 @@ impl Tool for CutTool { _ => {} } } + /// Mirror & Cut's `axis` and `keep`; the other cutting tools have no options. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match (self.id, key) { + ("mirrorCut", "axis") => c::one_of(key, v, &["vertical", "horizontal", "free"]), + ("mirrorCut", "keep") => c::one_of(key, v, &["left", "right", "top", "bottom"]), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 14f7f85881..515ff33039 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -460,6 +460,13 @@ impl Tool for DimensionTool { self.style = o; } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "mode" => crate::option_check::one_of(key, value, &["linear", "angular", "radial", "radius", "diameter"]), + "style" => DimensionOptions::from_params(value.clone()).map(|_| ()), + _ => Err(crate::option_check::unknown(key)), + } + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.at = ev.pos; self.shift = ev.mods.shift; diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index efc68132a1..0606e36a74 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -829,6 +829,25 @@ impl Tool for LiquifyTool { } } } + /// The options of [`LiquifyParams::from_json`] within its ranges, `diameter` for both sizes, + /// `showBrush`, and `tool` naming this tool. A percentage is a fraction up to 1 and a percent + /// above it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "tool" if value.as_str() == Some(self.params.kind.id()) => Ok(()), + "tool" => Err(format!("`tool` must be `{}`", self.params.kind.id())), + "diameter" | "width" | "height" => c::number(key, value, 0.5, 10_000.0), + "angle" => c::finite(key, value), + "intensity" | "horizontal" | "vertical" => c::number(key, value, 0.0, 100.0), + "detail" => c::number(key, value, 1.0, 10.0), + "simplify" => c::number(key, value, 0.0, 100.0), + "rate" => c::number(key, value, -180.0, 180.0), + "complexity" => c::number(key, value, 0.0, 15.0), + "showBrush" | "usePressure" | "simplifyOn" | "affectAnchors" | "affectIn" | "affectOut" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } /// The tool claims Escape during an Alt-drag that sizes the brush. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { key == ToolKey::Escape && self.sizing.is_some() diff --git a/crates/tools/src/distort/puppet.rs b/crates/tools/src/distort/puppet.rs index f141378382..5a1e03cd1b 100644 --- a/crates/tools/src/distort/puppet.rs +++ b/crates/tools/src/distort/puppet.rs @@ -515,6 +515,15 @@ impl Tool for PuppetWarpTool { _ => {} } } + /// `showMesh`, `selectAllPins` and `expand`; `pins` and `selected` are read only. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "showMesh" | "selectAllPins" => c::boolean(key, value), + "expand" => c::number(key, value, 0.0, 1000.0), + _ => Err(c::unknown(key)), + } + } fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 8058101b1c..1dbeb83750 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -509,6 +509,25 @@ impl Tool for FamilyTool { } } } + /// The options the tool shows ([`Self::options`]): those of the arc, the spiral or the grid. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + let skew = vectorcraft_geom::shapes::GRID_SKEW_MAX; + match key { + "lengthX" | "lengthY" | "width" | "height" => c::positive(key, v, 1e6), + "reference" => c::whole(key, v, 0, 8), + "baseAlong" => c::one_of(key, v, &["x", "y", "X", "Y"]), + "slope" => c::number(key, v, -100.0, 100.0), + "decay" => c::number(key, v, 5.0, 150.0), + "segments" => c::whole(key, v, 2, 1000), + "rows" | "concentric" | "columns" | "radial" => c::whole(key, v, 0, 999), + "rowSkew" | "concentricSkew" | "columnSkew" | "radialSkew" => c::number(key, v, -skew, skew), + _ => c::boolean(key, v), + } + } } /// Arc segment length from a dialog or preference value. diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 9aed6f545b..9450ed14ca 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1644,6 +1644,26 @@ impl Tool for GestureTool { _ => {} } } + /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity that the + /// Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`). + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let smooth_store = key == "smoothFidelity" && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); + if !smooth_store && self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + match key { + "fidelity" => c::number(key, v, super::min_fidelity(self.id), 100.0), + "smoothFidelity" => c::number(key, v, super::min_fidelity("smooth"), 100.0), + "size" => c::number(key, v, 0.1, 1000.0), + "sizeVariation" => c::number(key, v, 0.0, 1000.0), + "angle" => c::number(key, v, -180.0, 180.0), + "roundness" => c::number(key, v, if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0), + "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), + "sizeMode" => c::one_of(key, v, &["fixed", "pressure"]), + _ => c::boolean(key, v), + } + } } #[cfg(test)] diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index d1a2672402..e5a0a280f4 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -267,6 +267,18 @@ impl Tool for FlareTool { } } } + /// The switches and [`FLARE_OPTIONS`] within their ranges, the counts whole. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if matches!(key, "raysOn" | "ringsOn") { + return c::boolean(key, v); + } + let Some(&(_, _, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return Err(c::unknown(key)) }; + if is_count(key) && v.as_f64().is_none_or(|n| n.fract() != 0.0) { + return Err(format!("`{key}` must be a whole number from {lo} to {hi}")); + } + c::number(key, v, lo, hi) + } } /// Where a Reshape press landed on a selected path. diff --git a/crates/tools/src/intertwine.rs b/crates/tools/src/intertwine.rs index fb292ea37c..5fed3b07f3 100644 --- a/crates/tools/src/intertwine.rs +++ b/crates/tools/src/intertwine.rs @@ -343,6 +343,10 @@ impl Tool for IntertwineTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "prev" { crate::option_check::string_or_null(key, value) } else { Err(crate::option_check::unknown(key)) } + } + fn busy(&self) -> bool { self.dragging } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index d46a7fd972..200ca37625 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -27,6 +27,7 @@ pub mod meshedit; pub mod mirror; pub mod nineslice; pub mod objects_on_path; +pub mod option_check; pub mod params; pub mod pathtype; pub mod pen; @@ -150,6 +151,18 @@ pub trait Tool: Send { Value::Null } fn set_option(&mut self, _key: &str, _value: &Value) {} + /// Whether [`Self::set_option`] takes `value` for option `key` as it is: an error names an + /// option the tool doesn't have, a value of the wrong type or a number out of range + /// (`tool.setOption` checks every option it is given with this before it sets any). A tool + /// without options takes none. + fn check_option(&self, key: &str, _value: &Value) -> Result<(), String> { + Err(option_check::unknown(key)) + } + /// Whether [`Self::set_option`] takes all of `values`, set together in one call: by default + /// each one checked on its own with [`Self::check_option`]. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + values.iter().try_for_each(|(k, v)| self.check_option(k, v)) + } /// Is an interaction in progress (drag, open pen path)? fn busy(&self) -> bool { false diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index 8f19259126..a452e9e79d 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -971,6 +971,15 @@ impl Tool for ObjectsOnPathTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "pivot" => c::whole(key, value, 0, 8), + "rotate" => c::number(key, value, -360.0, 360.0), + _ => Err(c::unknown(key)), + } + } + fn busy(&self) -> bool { self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() || self.moving.is_some() || self.member.is_some() } diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs new file mode 100644 index 0000000000..9c16deb9cf --- /dev/null +++ b/crates/tools/src/option_check.rs @@ -0,0 +1,154 @@ +//! Checks of tool option values ([`crate::Tool::check_option`]) and of `tool.setOption`'s +//! parameters. Each error names the option and what it takes. + +use serde_json::{Map, Value}; + +use crate::Tool; + +/// The error for an option the tool doesn't have. +pub fn unknown(key: &str) -> String { + format!("unknown option `{key}`") +} + +/// `v` is a finite number from `lo` to `hi`. +pub fn number(key: &str, v: &Value, lo: f64, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() && (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + } +} + +/// `v` is a finite number. +pub fn finite(key: &str, v: &Value) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() => Ok(()), + _ => Err(format!("`{key}` must be a finite number")), + } +} + +/// `v` is a finite number above 0 and at most `hi`. +pub fn positive(key: &str, v: &Value, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n > 0.0 && n <= hi => Ok(()), + _ => Err(format!("`{key}` must be a number above 0 and at most {hi}")), + } +} + +/// `v` is a whole number (written without a fraction) from `lo` to `hi`. +pub fn whole(key: &str, v: &Value, lo: u64, hi: u64) -> Result<(), String> { + match v.as_u64() { + Some(n) if (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a whole number from {lo} to {hi}")), + } +} + +/// `v` is true or false. +pub fn boolean(key: &str, v: &Value) -> Result<(), String> { + if v.is_boolean() { Ok(()) } else { Err(format!("`{key}` must be true or false")) } +} + +/// `v` is one of the strings `choices`. +pub fn one_of(key: &str, v: &Value, choices: &[&str]) -> Result<(), String> { + if v.as_str().is_some_and(|s| choices.contains(&s)) { + Ok(()) + } else { + let list: Vec = choices.iter().map(|c| format!("`{c}`")).collect(); + Err(format!("`{key}` must be one of {}", list.join(", "))) + } +} + +/// `v` is a string, or null. +pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { + if v.is_string() || v.is_null() { Ok(()) } else { Err(format!("`{key}` must be a string or null")) } +} + +/// What `tool.setOption {tool?, key?, value?, values?}` sets: the tool named (none: the active +/// tool) and the options, `key` and `value` among `values`. A parameter of the wrong type, a +/// `value` without a `key` or a `key` without a `value`, and an option given both as `key` and in +/// `values` are errors. With none of `key` and `values`, the options are empty: the command reads +/// them. +pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { + let tool = match p.get("tool") { + None => None, + Some(t) => Some(t.as_str().ok_or("`tool` must be a tool id")?), + }; + let mut values = match p.get("values") { + None => Map::new(), + Some(v) => v.as_object().cloned().ok_or("`values` must be an object")?, + }; + match (p.get("key"), p.get("value")) { + (None, None) => {} + (Some(k), v) => { + let k = k.as_str().ok_or("`key` must be a string")?; + let v = v.ok_or_else(|| format!("`value` is missing for `{k}`"))?; + if values.contains_key(k) { + return Err(format!("`{k}` is given both as `key` and in `values`")); + } + values.insert(k.to_string(), v.clone()); + } + (None, Some(_)) => return Err("`value` needs a `key`".into()), + } + Ok((tool, values)) +} + +/// Check every one of `values` as an option of `tool` ([`Tool::check_options`]), before any is +/// set: the first one the tool doesn't take is an error that names the tool. +pub fn check_values(tool: &dyn Tool, values: &Map) -> Result<(), String> { + tool.check_options(values).map_err(|e| format!("tool `{}`: {e}", tool.id())) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn numbers_are_checked_against_their_range() { + assert!(number("fidelity", &json!(0.05), 0.05, 100.0).is_ok()); + assert!(number("fidelity", &json!(100), 0.05, 100.0).is_ok()); + for bad in [json!(-3), json!(1e9), json!("abc"), json!(true), json!(null), json!(0.04)] { + assert_eq!(number("fidelity", &bad, 0.05, 100.0), Err("`fidelity` must be a number from 0.05 to 100".into()), "{bad}"); + } + assert!(whole("sides", &json!(3), 3, 1000).is_ok()); + for bad in [json!(2), json!(3.5), json!(1001), json!(-1), json!("6")] { + assert!(whole("sides", &bad, 3, 1000).is_err(), "{bad}"); + } + assert!(positive("width", &json!(0), 1e6).is_err()); + assert!(positive("width", &json!(1e6), 1e6).is_ok()); + assert!(finite("angle", &json!(720)).is_ok()); + assert!(finite("angle", &json!("720")).is_err()); + } + + #[test] + fn other_values_are_checked_by_kind() { + assert!(boolean("fill", &json!(false)).is_ok()); + assert_eq!(boolean("fill", &json!(0)), Err("`fill` must be true or false".into())); + assert!(one_of("axis", &json!("free"), &["vertical", "free"]).is_ok()); + assert_eq!(one_of("axis", &json!("diagonal"), &["vertical", "free"]), Err("`axis` must be one of `vertical`, `free`".into())); + assert!(string_or_null("prev", &json!(null)).is_ok()); + assert!(string_or_null("prev", &json!(3)).is_err()); + } + + #[test] + fn set_option_params_reads_the_tool_and_the_options() { + let p = json!({"tool": "smooth", "key": "fidelity", "value": 2, "values": {"x": 1}}); + let (tool, values) = set_option_params(&p).unwrap(); + assert_eq!(tool, Some("smooth")); + assert_eq!(Value::Object(values), json!({"fidelity": 2, "x": 1})); + let empty = json!({}); + let (tool, values) = set_option_params(&empty).unwrap(); + assert!(tool.is_none() && values.is_empty()); + assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); + assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); + assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); + assert_eq!(set_option_params(&json!({"key": "fill"})).err(), Some("`value` is missing for `fill`".into())); + assert_eq!(set_option_params(&json!({"value": 1})).err(), Some("`value` needs a `key`".into())); + assert_eq!( + set_option_params(&json!({"key": "fill", "value": true, "values": {"fill": false}})).err(), + Some("`fill` is given both as `key` and in `values`".into()) + ); + // An explicit null is a value: the Type tool's triggers take one. + assert!(set_option_params(&json!({"key": "stopEditing", "value": null})).is_ok()); + } +} diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index af67b38c00..360645f671 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -183,6 +183,33 @@ impl Tool for PlaceTool { } } + /// A queue whose every entry has its `params` object and a finite `width` and `height`, and + /// `current` within the queue held. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "queue" => check_queue(value).map(drop), + "current" => check_current(value, self.entries.len()), + _ => Err(crate::option_check::unknown(key)), + } + } + + /// As [`Self::check_option`], except that a `current` given with a `queue` is an index into + /// that queue (the queue is set first). + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let mut held = self.entries.len(); + if let Some(queue) = values.get("queue") { + held = check_queue(queue)?; + } + for (k, v) in values { + match k.as_str() { + "queue" => {} + "current" => check_current(v, held)?, + _ => self.check_option(k, v)?, + } + } + Ok(()) + } + /// Switching tools discards what the cursor holds. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.entries.clear(); @@ -191,6 +218,35 @@ impl Tool for PlaceTool { } } +/// The number of files `queue` holds, or an error when an entry lacks its `params` object or a +/// finite `width` and `height`. +fn check_queue(queue: &Value) -> Result { + let entry = |e: &Value| { + e.get("params").is_some_and(Value::is_object) + && e.get("name").is_none_or(Value::is_string) + && ["width", "height"].iter().all(|k| e.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite)) + }; + let entries = match queue.get("entries") { + None => Some(0), + Some(e) => e.as_array().filter(|a| a.iter().all(entry)).map(Vec::len), + }; + match entries { + Some(n) if queue.is_object() && queue.get("prev").is_none_or(Value::is_string) => Ok(n), + _ => Err("`queue` must be {entries: [{params, name, width, height}], prev?}: each entry with a params object and a finite \ + width and height" + .into()), + } +} + +/// `current` is the index of one of the `held` files. +fn check_current(current: &Value, held: usize) -> Result<(), String> { + match held { + _ if current.as_u64().is_some_and(|i| i < held as u64) => Ok(()), + 0 => Err("`current` can't be set: no file is queued".into()), + _ => Err(format!("`current` must be the index of a queued file, from 0 to {}", held - 1)), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 66728b4826..7489e74a32 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -817,6 +817,20 @@ impl Tool for ShapeTool { } } } + /// The options every shape tool keeps ([`Self::options`]). Any finite angle is taken: it is + /// kept as the same direction from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "sides" | "points" => c::whole(key, v, 3, 1000), + "cornerRadius" => c::number(key, v, 0.0, MAX_CORNER_RADIUS), + "starRatio" => c::number(key, v, 0.01, 1.0), + "length" => c::number(key, v, 0.0, 1e6), + "angle" => c::finite(key, v), + "fillLine" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 1618d6e7d6..c0e1d97137 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -222,6 +222,15 @@ impl Tool for SymbolismTool { _ => {} } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, 2.0, 2000.0), + "intensity" | "density" => c::number(key, v, 1.0, 10.0), + "symbol" | "style" => c::string_or_null(key, v), + _ => Err(c::unknown(key)), + } + } } /// Paintbrush: the freehand gesture, painting with the current brush. @@ -288,6 +297,9 @@ impl Tool for BrushPaintTool { self.inner.set_option(key, v); } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "brush" { crate::option_check::string_or_null(key, v) } else { self.inner.check_option(key, v) } + } fn wants_samples(&self) -> bool { self.inner.wants_samples() } diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index dd561bc616..44c6c1b0f6 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -608,6 +608,25 @@ impl Tool for TypeTool { _ => {} } } + /// The calls [`Self::set_option`] takes: `commitTyping`, `endTyping`, `selectAll` and + /// `stopEditing` take any value, the others the shapes they read. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + let index = |a: &str, b: &str| v.get(a).or_else(|| v.get(b)).and_then(Value::as_u64).is_some(); + let ok = match key { + "textSelection" => index("editing", "id") && index("anchor", "start") && index("caret", "end"), + "select" => index("start", "start") && index("end", "end"), + "prevTool" | "previousTool" => return crate::option_check::string_or_null(key, v), + "copy" => serde_json::from_value::>(v.clone()).is_ok(), + "commitTyping" | "endTyping" | "selectAll" | "stopEditing" => true, + _ => return Err(crate::option_check::unknown(key)), + }; + let shape = match key { + "textSelection" => "{editing, anchor, caret} with whole numbers", + "select" => "{start, end} with whole numbers", + _ => "a list of text runs", + }; + if ok { Ok(()) } else { Err(format!("`{key}` must be {shape}")) } + } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); if let (Some((_, s)), Some(d)) = (self.press, self.drag) { diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index 5af642c44b..e8cac59c88 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -726,6 +726,18 @@ impl Tool for ArtboardTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "active" if value.as_u64().is_some() => Ok(()), + "active" => Err("`active` must be an artboard index: a whole number from 0".into()), + "selected" if value.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|i| i.as_u64().is_some())) => Ok(()), + "selected" => Err("`selected` must be a list of artboard indexes, the active one first".into()), + "moveArt" | "scaleArt" | "suppressFitClick" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + /// A drag is moving or resizing artboards (Artboard Options › Update While Dragging reads it). fn transforming(&self) -> bool { matches!(self.drag, Some(Drag::Move { began: true, .. } | Drag::Resize { began: true, .. })) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index c5e05f004b..ce6b722f53 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -517,6 +517,16 @@ impl Tool for EyedropperTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "stop" => c::string_or_null(key, value), + "brushKeyColor" => c::boolean(key, value), + "textSelection" => self.text_selection.check_option(key, value), + _ => Err(c::unknown(key)), + } + } + /// Drop the range when its text is removed or no longer selected. fn after_command(&mut self, cx: &ToolContext) -> Vec { self.text_selection.after_command(cx) diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 1583584940..a747b38efe 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -379,6 +379,15 @@ impl Tool for FreeTransformTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "mode" => c::one_of(key, value, &["free", "perspective", "distort", "freeDistort"]), + "constrain" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.quad = None; self.guides.clear(); diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 263c0ea5e4..b8de339af4 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -337,6 +337,15 @@ impl Tool for TransformTool { } } + /// `origin` is `[x, y]`, or null to clear it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key != "origin" { + return Err(crate::option_check::unknown(key)); + } + let point = value.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|n| n.as_f64().is_some_and(f64::is_finite))); + if point || value.is_null() { Ok(()) } else { Err("`origin` must be [x, y] with finite numbers, or null".into()) } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } } diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index bfbcf0d5b3..c41a3f41b0 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -239,12 +239,15 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options. When the tool refuses one of them, nothing is set and the dialog +/// stays open. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let tool = d.str("__tool"); let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let r = app.run("tool.setOption", json!({ "tool": tool, "values": values })); - app.ui.dialog = None; + if r.is_ok() { + app.ui.dialog = None; + } r } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 552fbc0c06..c8d931f412 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -621,6 +621,16 @@ fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogRes r } +/// Set a tool's options with `tool.setOption` (`params`) and close the dialog; when the tool +/// refuses one of them, nothing is set and the dialog stays open. +fn set_tool_options_and_close(app: &mut VectorcraftApp, params: Value) -> DialogResult { + let r = app.run("tool.setOption", params); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// The field of a dialog opened over another (Import Shortcut Set over Keyboard Shortcuts) that /// holds the dialog under it, which Cancel and Escape show again. pub(crate) const PARENT: &str = "__parent"; diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index b94f6a7c2e..9da15fe4a2 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -16,7 +16,7 @@ use vectorcraft_geom::Point; use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params}; use super::document_setup::check; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -154,12 +154,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { values.insert(key.into(), json!(d.bool(key))); } if let Some((cmd, params)) = command { + // Options the tool would refuse leave the dialog open, before the flare is accepted. + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create("flare").as_ref(), &values)?; // Accept the preview once; option persistence follows successful artwork creation. let result = form::commit_preview(app, &cmd, params)?; app.run("tool.setOption", json!({ "tool": "flare", "values": values }))?; Ok(result) } else { - run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "flare", "values": values })) } } @@ -311,10 +313,11 @@ mod tests { super::super::confirm(&mut app).unwrap(); let parts = flare_parts(&app); assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}"); - // Out-of-range values are kept within the option's range. - app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 900, "diameter": -4}})).unwrap(); - let o = app.session.tool_options_of("flare"); - assert_eq!((o["opacity"].as_f64(), o["diameter"].as_f64()), (Some(100.0), Some(0.0))); + // An out-of-range value is an error, and no option changes. + let before = app.session.tool_options_of("flare"); + let e = app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 50, "diameter": -4}})).unwrap_err(); + assert_eq!(e, "tool `flare`: `diameter` must be a number from 0 to 1000"); + assert_eq!(app.session.tool_options_of("flare"), before); } #[test] diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 48f31731cc..00abac95d4 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -16,7 +16,7 @@ use serde_json::{Map, Value, json}; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -315,7 +315,7 @@ fn blob_tip_short_ratio(roundness: f64) -> f32 { /// OK: set the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 35d216bc77..df5071cf41 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -28,6 +28,24 @@ fn blob_tip_fields_confirm_and_cancel() { assert_eq!(app.session.tool_options_of("blobBrush")["roundness"], json!(0.0)); } +/// OK with a Fidelity the Smooth tool refuses shows the error and keeps the dialog open, with +/// nothing set; a Fidelity it takes then closes it. +#[test] +fn a_refused_fidelity_keeps_the_dialog_open() { + let mut app = app(); + app.run("tool.options", json!({"tool": "smooth"})).unwrap(); + let before = app.session.tool_options_of("smooth"); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(0.01)); + let e = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(e, "tool `smooth`: `fidelity` must be a number from 0.05 to 100"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + assert_eq!(app.session.tool_options_of("smooth"), before); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of("smooth")["fidelity"], json!(5.0)); +} + #[test] fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] { diff --git a/crates/ui-egui/src/dialogs/liquify.rs b/crates/ui-egui/src/dialogs/liquify.rs index 40aa677f17..18b8e48418 100644 --- a/crates/ui-egui/src/dialogs/liquify.rs +++ b/crates/ui-egui/src/dialogs/liquify.rs @@ -12,7 +12,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_tools::distort::liquify::LiquifyKind; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -145,7 +145,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { values.insert(key.into(), json!(d.f64(key, 0.0) / 100.0)); } } - run_and_close(app, "tool.setOption", json!({ "tool": kind(d).id(), "values": values })) + set_tool_options_and_close(app, json!({ "tool": kind(d).id(), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_bucket.rs b/crates/ui-egui/src/dialogs/live_paint_bucket.rs index c040cdcc31..cdce096e6b 100644 --- a/crates/ui-egui/src/dialogs/live_paint_bucket.rs +++ b/crates/ui-egui/src/dialogs/live_paint_bucket.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -84,7 +84,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_selection.rs b/crates/ui-egui/src/dialogs/live_paint_selection.rs index a1a91ad2b7..95584c2f96 100644 --- a/crates/ui-egui/src/dialogs/live_paint_selection.rs +++ b/crates/ui-egui/src/dialogs/live_paint_selection.rs @@ -13,7 +13,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -80,7 +80,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index 8a02cd37cf..7180fd6105 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -11,7 +11,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::objects_on_path::CENTER; -use super::{DialogSpec, run_and_close}; +use super::{DialogSpec, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -70,7 +70,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// Save: set the tool's Pivot and Rotate. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = ["pivot", "rotate"].iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/shape_builder_options.rs b/crates/ui-egui/src/dialogs/shape_builder_options.rs index 9393e0707e..d4edbad1f9 100644 --- a/crates/ui-egui/src/dialogs/shape_builder_options.rs +++ b/crates/ui-egui/src/dialogs/shape_builder_options.rs @@ -14,7 +14,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -124,7 +124,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("highlightColor"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": "shapeBuilder", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "shapeBuilder", "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 392c043f35..e2342e6dd4 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -102,8 +102,8 @@ fn line_length_angle(d: &Dialog) -> (f64, f64) { fn arc_options(d: &Dialog) -> Value { json!({ "closed": d.str("arcType").eq_ignore_ascii_case("closed"), - "lengthX": d.f64("lengthX", 100.0), - "lengthY": d.f64("lengthY", 100.0), + "lengthX": d.f64("lengthX", 100.0).abs(), + "lengthY": d.f64("lengthY", 100.0).abs(), "reference": arc_reference(d), "baseAlong": d.str("baseAlong"), "slope": d.f64("slope", 50.0), @@ -371,13 +371,11 @@ fn box_origin(d: &Dialog) -> (f64, f64) { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // Tool Options: the options the tool's next drag and click use; nothing is drawn. if d.bool(TOOL_OPTIONS) { - let r = app.run("tool.setOption", json!({"tool": d.kind, "values": tool_options(d)})); - app.ui.dialog = None; - return r; + return super::set_tool_options_and_close(app, json!({"tool": d.kind, "values": tool_options(d)})); } let count = match d.kind.as_str() { "polygon" => Some(("sides", 6.0, 3.0)), - "star" => Some(("points", 5.0, 2.0)), + "star" => Some(("points", 5.0, 3.0)), _ => None, }; let options = count @@ -454,7 +452,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // On the active plane while the perspective grid shows, sized in plane units from the click; // else along General › Constrain Angle, turned about the point the dialog places at the click // (a grid's reference point, the other shapes' top-left corner or centre). - let options = options.or_else(|| (d.kind == "spiral").then(|| params.clone())); + let options = options.or_else(|| { + (d.kind == "spiral").then(|| json!({"decay": params["decay"], "segments": params["segments"], "clockwise": params["clockwise"]})) + }); + // Options the tool would refuse leave the dialog open, before anything is drawn. + if let Some(Value::Object(o)) = &options { + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create(&d.kind).as_ref(), o)?; + } let result = match vectorcraft_engine::perspective_click(&app.session, id, ¶ms, vectorcraft_geom::Point::new(x, y)) { Some((id, params)) => run_and_close(app, &id, params), None => { diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 33d902b90e..05392bbd4f 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -6,7 +6,7 @@ use serde_json::{Map, Value, json}; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -50,7 +50,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let values: Map = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs index ef5dca5ede..e2db8b6d75 100644 --- a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs +++ b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs @@ -339,6 +339,20 @@ fn rectangular_grid_failed_creation_does_not_save_counts() { assert_eq!(app.session.doc().unwrap().history.undo.len(), before.undo); } +/// Tool Options with a width the tool refuses is an error that keeps the dialog open and sets +/// nothing. +#[test] +fn rectangular_grid_tool_options_with_a_refused_width_stay_open() { + let mut app = app(); + let before = app.session.tool_options_of(KIND); + super::shapes::open_options(&mut app, KIND).unwrap(); + set(&mut app, "width", json!(0)); + let e = super::confirm(&mut app).unwrap_err(); + assert!(e.contains("`width`"), "{e}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + assert_eq!(app.session.tool_options_of(KIND), before); +} + /// #1377: the dialog shows the tool's stored skews (sliders under their divider counts) and /// switches; OK draws with them and stores them, and the next drag uses them too. #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 0b490352e3..582bc77802 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -776,7 +776,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( crate::touch::TOGGLE_MODE, diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 29d89ebf6d..3e6625fa93 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1148,7 +1148,7 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui) { ui.label(egui::RichText::new(tl!("Expand:")).size(12.0).color(t.text)); let unit = app.session.general_unit(); if let Some(v) = widgets::num_field(ui, ("cb-tool", "expand"), opts["expand"].as_f64(), unit, 64.0) { - app.run("tool.setOption", json!({ "key": "expand", "value": v })).ok(); + app.run("tool.setOption", json!({ "key": "expand", "value": v.clamp(0.0, 1000.0) })).ok(); } let show = opts["showMesh"].as_bool().unwrap_or(true); if widgets::check(ui, "Show Mesh", show, true) { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 45f4d0141b..a32c3272df 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -921,7 +921,11 @@ Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "objec Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay when you switch tools or documents and are saved with the preferences. The Liquify tools share their Global Brush -Dimensions (`width`, `height`, `angle`, `intensity`). +Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing. Every option given is +checked before any is set: an option the tool doesn't have, a value of the wrong type, a number outside the tool's +range or an unknown choice is an error that names the tool and the option +(``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes. +The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range instead. Perspective grid: View → Perspective Grid → Define Grid… (`ui.perspectiveGridDialog`) opens the `perspectiveGrid` dialog prefilled from the grid. Its fields are those of `perspective.grid.define` (`kind`, `units`, `scale`, diff --git a/docs/mcp.md b/docs/mcp.md index 912ac32562..3901375542 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9811,10 +9811,22 @@ intensity), and the Symbolism tools one brush. Interaction state (pins, a refere desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has active the active artboard (the navigator's and the Artboards panel's). +Every option given is checked before any is set. A key that the tool's `check_option` does not take (it is unknown +to that tool), a value of the wrong type, a number outside the tool's range, an unknown choice, a `key` without a +`value`, a `values` that is not an object or a `tool` that is not a tool id is an error result that names the tool and +the option, and nothing changes: no option, no saved preference and no undo step, also when another option given with +it is good. `{}` reads the options and sets nothing. The ranges are VectorCraft's own (for example the Smooth tool's +`fidelity` takes 0.05 to 100, the Pencil's 0.01 to 100); a refused value in a Tool Options dialog keeps the dialog +open. The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range +when a number outside it is given, as their sections above say. + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"twirl","values":{"width":60,"rate":90}}}} +{"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"smooth","key":"fidelity","value":-3}}} ``` +The second call returns the error ``tool `smooth`: `fidelity` must be a number from 0.05 to 100``. + The Pencil's, the Paintbrush's and the Smooth tool's `fidelity` is in screen pixels: the tools send `path.freehand` and `path.smoothRegion` the option divided by the zoom, so a stroke keeps as many points and a Smooth drag smooths as much at any zoom. The Smooth tool's `fidelity` (0.05 to 100 px, 2.5 by default) is also the one an Alt smoothing drag with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 26681e5b7f..5ed24c7b9d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -747,6 +747,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document (a value nested past the schema's 16 levels is such a parameter error, and only a schema that is wrong in itself is an internal error); saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. - **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. +- **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. From 72082aee46c4902a8c39483f16dc8ad832b257b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:27:34 -0800 Subject: [PATCH 2/8] Tools: tool.setOption refuses non-object parameters and keeps its target tool Parameters that are not an object (true, 7, [], "x") are an error instead of an empty read; no parameters (null) still read the options. The tool an option is checked against is named before the edit in progress is finished, so a held Cmd press made by finishing it no longer sends the value to the selection tool it lends. --- crates/engine/src/tests/build.rs | 20 ++++++++++++++++++++ crates/engine/src/tooling.rs | 20 ++++++++++++-------- crates/tools/src/option_check.rs | 13 +++++++++++-- docs/control-protocol.md | 3 ++- docs/mcp.md | 3 ++- 5 files changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index cb61ac1b9e..545551f13f 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1049,6 +1049,26 @@ fn shape_builder_drops_a_press_held_during_a_merge() { } } +/// `tool.setOption` without a tool, while a Cmd press is held during a merge, sets the Shape +/// Builder's option: finishing the merge makes the press, which lends the selection tool, and the +/// value still goes to the Shape Builder it was checked against. +#[test] +fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() { + let v = ViewInfo::default(); + let mut s = session(); + s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap(); + square_row(&mut s); + click_row(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Down, 305.0, 10.0).with_mods(Mods { cmd: true, ..Default::default() }), v).unwrap(); + assert!(s.tool_editing(), "the press is held"); + let out = s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "artwork"})).unwrap(); + assert_eq!(s.tool_id(), "selection", "the held press lent the selection tool"); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder")); + assert_eq!(out["pickColorFrom"], json!("artwork")); + assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork"))); +} + /// A new revision of the document made outside a command while a merge is computed on another /// thread keeps the merge when the selected art is as it was (the next poll applies it, as the /// command computes it), and drops it when the art changed. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index df7ef4b1d8..fcbaf664d0 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1319,12 +1319,15 @@ impl Session { { return Err(format!("unknown tool `{t}`")); } - let active = tool.is_none_or(|t| t == self.tool.id()); + // The tool is named before the edit in progress is finished: finishing it can make a held + // Cmd press, which lends a selection tool and makes that the active tool. + let id = tool.unwrap_or(self.tool.id()); + let active = id == self.tool.id(); if values.is_empty() { - return Ok(self.tool_options_of(tool.unwrap_or(self.tool.id()))); + return Ok(self.tool_options_of(id)); } // Every value is checked before any is set, so an invalid one changes nothing. - vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + vectorcraft_tools::builder::check_builder_options(id, &values)?; // The Place queue is read later, by a click outside any automation scope: its files must // be readable now, under the roots of whoever sets it. if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) { @@ -1332,7 +1335,7 @@ impl Session { crate::file_access::check_read(path)?; } } - if tool.unwrap_or(self.tool_id()) == "dimension" { + if id == "dimension" { if let Some(style) = values.get("style") { vectorcraft_doc::dimension::DimensionOptions::from_params(style.clone())?; } @@ -1342,15 +1345,16 @@ impl Session { return Err("Unknown dimension mode".into()); } } - match tool.filter(|_| !active) { - Some(id) => vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?, - None => vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?, + if active { + vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?; + } else { + vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?; } // The active tool's merge being computed is applied with the options it was started with. if active { self.finish_tool_edit_later().map_err(|e| e.to_string())?; } - Ok(self.set_tool_options(tool, &values)) + Ok(self.set_tool_options(Some(id), &values)) } /// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]): diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 9c16deb9cf..9a45caeb13 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -65,9 +65,12 @@ pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { /// What `tool.setOption {tool?, key?, value?, values?}` sets: the tool named (none: the active /// tool) and the options, `key` and `value` among `values`. A parameter of the wrong type, a /// `value` without a `key` or a `key` without a `value`, and an option given both as `key` and in -/// `values` are errors. With none of `key` and `values`, the options are empty: the command reads -/// them. +/// `values` are errors, and so are parameters that are not an object. With none of `key` and +/// `values`, or with no parameters (null), the options are empty: the command reads them. pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { + if !p.is_object() && !p.is_null() { + return Err("the parameters must be an object".into()); + } let tool = match p.get("tool") { None => None, Some(t) => Some(t.as_str().ok_or("`tool` must be a tool id")?), @@ -139,6 +142,12 @@ mod tests { let empty = json!({}); let (tool, values) = set_option_params(&empty).unwrap(); assert!(tool.is_none() && values.is_empty()); + // Omitted parameters arrive as null: a read, like `{}`. + let (tool, values) = set_option_params(&Value::Null).unwrap(); + assert!(tool.is_none() && values.is_empty()); + for bad in [json!(true), json!(7), json!([]), json!("x")] { + assert_eq!(set_option_params(&bad).err(), Some("the parameters must be an object".into()), "{bad}"); + } assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a32c3272df..edd0d8f96f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -921,7 +921,8 @@ Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "objec Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay when you switch tools or documents and are saved with the preferences. The Liquify tools share their Global Brush -Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing. Every option given is +Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing; parameters that are +not an object are an error. Every option given is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes. diff --git a/docs/mcp.md b/docs/mcp.md index 3901375542..0c46157847 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9815,7 +9815,8 @@ Every option given is checked before any is set. A key that the tool's `check_op to that tool), a value of the wrong type, a number outside the tool's range, an unknown choice, a `key` without a `value`, a `values` that is not an object or a `tool` that is not a tool id is an error result that names the tool and the option, and nothing changes: no option, no saved preference and no undo step, also when another option given with -it is good. `{}` reads the options and sets nothing. The ranges are VectorCraft's own (for example the Smooth tool's +it is good. Parameters that are not an object are an error too. `{}`, or no parameters, reads the options and sets +nothing. The ranges are VectorCraft's own (for example the Smooth tool's `fidelity` takes 0.05 to 100, the Pencil's 0.01 to 100); a refused value in a Tool Options dialog keeps the dialog open. The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range when a number outside it is given, as their sections above say. From df95a67ea7879bab3dacf0347883d8976e80c556 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:10:16 -0800 Subject: [PATCH 3/8] Tools: tool.setOption reads and sets the tool that lent the Selection tool When a held Cmd press lends the Selection tool, `tool.setOption` that names the waiting tool (the Shape Builder) reads its options from that tool instead of making it again from the saved preferences, and a value set on it counts as set since the tool last started afresh. Params that are not an object now give the error the other commands give, "the params must be an object, not {got}", which the message catalogs already translate. The params text of tool.setOption in the MCP catalog, the desktop commands and the headless host says so. --- crates/engine/src/tests/build.rs | 16 ++++++++--- crates/engine/src/tests/toolsettings.rs | 5 ++++ crates/engine/src/tooling.rs | 28 ++++++++++++++----- crates/mcp/src/headless.rs | 2 +- crates/mcp/src/tests/liquify.rs | 15 +++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/option_check.rs | 36 ++++++++++++++++++++++--- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/control-protocol.md | 5 ++-- docs/mcp.md | 8 +++--- 10 files changed, 96 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 545551f13f..cca6de810f 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1049,9 +1049,9 @@ fn shape_builder_drops_a_press_held_during_a_merge() { } } -/// `tool.setOption` without a tool, while a Cmd press is held during a merge, sets the Shape -/// Builder's option: finishing the merge makes the press, which lends the selection tool, and the -/// value still goes to the Shape Builder it was checked against. +/// When `tool.setOption` names no tool, the option is set on the tool that was active when the +/// call arrived (the Shape Builder), even when finishing its merge replays a held Cmd press that +/// switches to the Selection tool. #[test] fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() { let v = ViewInfo::default(); @@ -1067,6 +1067,16 @@ fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder( assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder")); assert_eq!(out["pickColorFrom"], json!("artwork")); assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork"))); + // Named while it waits, the Shape Builder is read where it waits, not made afresh from the + // preferences. + s.lender.as_mut().unwrap().set_option("pickColorFrom", &json!("swatches")); + let read = s.set_tool_option_cmd(&json!({"tool": "shapeBuilder"})).unwrap(); + assert_eq!(read["pickColorFrom"], json!("swatches"), "read from the waiting tool"); + // A value set on it counts as set on the tool chosen. + s.tool_set_since_reset = false; + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "key": "highlightFill", "value": false})).unwrap(); + assert!(s.tool_set_since_reset(), "the tool chosen was set"); + assert_eq!(s.lender.as_ref().map(|t| t.options()["highlightFill"].clone()), Some(json!(false))); } /// A new revision of the document made outside a command while a merge is computed on another diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index eae2a16aa4..a893244021 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -370,6 +370,11 @@ fn an_empty_set_option_reads_and_saves_nothing() { let saved = s.prefs.tool_settings.clone(); assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options()); assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare")); + // No params (null) read too; params that are not an object are an error. + assert_eq!(s.set_tool_option_cmd(&serde_json::Value::Null).unwrap(), s.tool_options()); + for (bad, got) in [(json!(true), "true"), (json!([]), "[]")] { + assert_eq!(s.set_tool_option_cmd(&bad).unwrap_err(), format!("the params must be an object, not {got}")); + } assert_eq!(s.prefs.tool_settings, saved); } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index fcbaf664d0..eeb1383c3c 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1260,7 +1260,14 @@ impl Session { /// The options of tool `id`: the active tool's, or those it would have if chosen now. pub fn tool_options_of(&self, id: &str) -> Value { - if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() } + if id == self.tool.id() { + self.tool.options() + } else if let Some(lender) = self.lender.as_deref().filter(|l| l.id() == id) { + // The tool that lent a selection tool for a Cmd-drag holds its options while it waits. + lender.options() + } else { + self.make_tool(id).options() + } } /// Set options of tool `id` (default: the active tool). Another tool's persistent options are @@ -1272,7 +1279,10 @@ impl Session { self.note_place_queue_roots(); } let active = id.is_none_or(|id| id == self.tool.id()); - self.tool_set_since_reset |= active; + // The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again + // when the drag ends. + let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id)); + self.tool_set_since_reset |= active || lender; // The Place queue and a parametric shape's kind are set first: setting the queue starts // again at its first file, and a `current` given with it is an index into it; setting the // kind puts the shape's other numbers back to that kind's, and those given with it are its. @@ -1284,7 +1294,7 @@ impl Session { t.set_option(k, v); } Self::store_tool_settings(&mut self.prefs, t); - let out = t.options(); + let mut out = t.options(); if let Some(other) = other { // The tool that lent a selection tool for a Cmd-drag is kept aside, not made again when // it is back: when it is the tool set, it takes the writes too (the Rounded Rectangle's @@ -1297,6 +1307,9 @@ impl Session { } } Self::restore_tool_settings(&self.prefs, lender); + if lender.id() == other.id() { + out = lender.options(); + } } // Only the stores it shares with the tool set: the active tool's own options stay as they // are, also in the middle of a drag that Escape can cancel. @@ -1308,10 +1321,11 @@ impl Session { /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: - /// the active tool) → its options. With no option given, the options are read and nothing is - /// set. Every option given is checked first ([`vectorcraft_tools::Tool::check_option`]): an - /// unknown option, a value of the wrong type or a number out of range is an error that sets - /// none of them. + /// the tool active when the call arrives, named before the edit in progress is finished) → its + /// options. With no option given, the options are read and nothing is set. Parameters that are + /// not an object are an error; none (null) read the options. Every option given is checked + /// first ([`vectorcraft_tools::Tool::check_option`]): an unknown option, a value of the wrong + /// type or a number out of range is an error that sets none of them. pub fn set_tool_option_cmd(&mut self, p: &Value) -> std::result::Result { let (tool, values) = vectorcraft_tools::option_check::set_option_params(p)?; if let Some(t) = tool diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 69c7b5ba0e..cd08ece378 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -48,7 +48,7 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ ( "tool.setOption", "Tool Option", - "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` reads them); kept options last across tool switches", + "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` or no params reads them; params that are not an object are an error); kept options last across tool switches", ), ]; diff --git a/crates/mcp/src/tests/liquify.rs b/crates/mcp/src/tests/liquify.rs index c6d3862384..793f16efee 100644 --- a/crates/mcp/src/tests/liquify.rs +++ b/crates/mcp/src/tests/liquify.rs @@ -43,6 +43,21 @@ fn a_refused_option_value_is_an_error_result() { assert_eq!(command(&mut h, "tool.setOption", json!({})), before); } +/// `tool.setOption` with params that are not an object is an error result that sets nothing; +/// without params it reads the options, as `{}` does. +#[test] +fn set_option_params_that_are_not_an_object_are_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for params in [json!(true), json!(7), json!([]), json!("x")] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": params})); + assert!(r.is_error, "{params}: {r:?}"); + } + assert_eq!(ok(&mut h, "run_command", json!({"command": "tool.setOption"})), before); + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + #[test] fn pointer_gestures_carry_pen_pressure() { let bloat = |pressure: f64| { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 7783f72f1f..7f54d48a82 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -775,7 +775,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( "tool.toggleTouchMode", diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 9a45caeb13..8507a82184 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -69,7 +69,7 @@ pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { /// `values`, or with no parameters (null), the options are empty: the command reads them. pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { if !p.is_object() && !p.is_null() { - return Err("the parameters must be an object".into()); + return Err(format!("the params must be an object, not {}", shown(p))); } let tool = match p.get("tool") { None => None, @@ -94,6 +94,32 @@ pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map) Ok((tool, values)) } +/// The JSON text of `v` as a parameter error shows it: cut to 40 characters, with `…` when it was +/// longer. The text is written only up to the cut. +fn shown(v: &Value) -> String { + struct Cut { + text: String, + left: usize, + } + impl std::fmt::Write for Cut { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for c in s.chars() { + if self.left == 0 { + return Err(std::fmt::Error); + } + self.left -= 1; + self.text.push(c); + } + Ok(()) + } + } + let mut out = Cut { text: String::new(), left: 40 }; + if std::fmt::Write::write_fmt(&mut out, format_args!("{v}")).is_err() { + out.text.push('…'); + } + out.text +} + /// Check every one of `values` as an option of `tool` ([`Tool::check_options`]), before any is /// set: the first one the tool doesn't take is an error that names the tool. pub fn check_values(tool: &dyn Tool, values: &Map) -> Result<(), String> { @@ -145,9 +171,13 @@ mod tests { // Omitted parameters arrive as null: a read, like `{}`. let (tool, values) = set_option_params(&Value::Null).unwrap(); assert!(tool.is_none() && values.is_empty()); - for bad in [json!(true), json!(7), json!([]), json!("x")] { - assert_eq!(set_option_params(&bad).err(), Some("the parameters must be an object".into()), "{bad}"); + for (bad, got) in [(json!(true), "true"), (json!(7), "7"), (json!([]), "[]"), (json!("x"), "\"x\"")] { + assert_eq!(set_option_params(&bad).err(), Some(format!("the params must be an object, not {got}")), "{bad}"); } + // A long value is shown cut, as the other parameter errors show it. + let long = json!("a".repeat(100)); + let shown = format!("\"{}…", "a".repeat(39)); + assert_eq!(set_option_params(&long).err(), Some(format!("the params must be an object, not {shown}"))); assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 582bc77802..c419237a13 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -776,7 +776,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( crate::touch::TOGGLE_MODE, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index edd0d8f96f..0d78baca0a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -922,9 +922,8 @@ Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay when you switch tools or documents and are saved with the preferences. The Liquify tools share their Global Brush Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing; parameters that are -not an object are an error. Every option given is -checked before any is set: an option the tool doesn't have, a value of the wrong type, a number outside the tool's -range or an unknown choice is an error that names the tool and the option +not an object are an error. Every option given is checked before any is set: an option the tool doesn't have, a value +of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes. The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range instead. diff --git a/docs/mcp.md b/docs/mcp.md index 0c46157847..7ec64a52de 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9816,10 +9816,10 @@ to that tool), a value of the wrong type, a number outside the tool's range, an `value`, a `values` that is not an object or a `tool` that is not a tool id is an error result that names the tool and the option, and nothing changes: no option, no saved preference and no undo step, also when another option given with it is good. Parameters that are not an object are an error too. `{}`, or no parameters, reads the options and sets -nothing. The ranges are VectorCraft's own (for example the Smooth tool's -`fidelity` takes 0.05 to 100, the Pencil's 0.01 to 100); a refused value in a Tool Options dialog keeps the dialog -open. The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range -when a number outside it is given, as their sections above say. +nothing. The ranges are VectorCraft's own (for example the Smooth tool's `fidelity` takes 0.05 to 100, the Pencil's +0.01 to 100); a refused value in a Tool Options dialog keeps the dialog open. The Live Paint tools' `width` and the +Shape Builder's `gapLength` are set to the nearest end of their range when a number outside it is given, as their +sections above say. ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"twirl","values":{"width":60,"rate":90}}}} From 23bdbada815d4c3d9a3b1d016eff480ded25879d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:22:47 -0800 Subject: [PATCH 4/8] Tools: tool.setOption takes the Eraser's angle and roundness modes and variations The Eraser reports angleMode, roundnessMode, angleVariation and roundnessVariation, but the check before tool.setOption sent every key it did not list to the true-or-false check, so the Freehand dialog's OK for the Eraser failed. sizeMode was also limited to fixed and pressure for the Eraser, which takes every mode. The gesture tools' check now takes each mode (any of the six for the Eraser, fixed or pressure for the Blob Brush's size), the angle variation from 0 to 180 and the roundness variation from 0 to 100, and names its true-or-false options instead of defaulting to them. A new test checks that every tool in the catalog takes back the options it reports, apart from the state it reports and does not take. --- crates/tools/src/draw2/gesture.rs | 10 ++++++-- crates/tools/src/draw2/gesture/tests.rs | 14 +++++++++++ crates/tools/src/option_check.rs | 33 +++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 7276311076..0b2be462b8 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1841,8 +1841,14 @@ impl Tool for GestureTool { "angle" => c::number(key, v, -180.0, 180.0), "roundness" => c::number(key, v, if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0), "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), - "sizeMode" => c::one_of(key, v, &["fixed", "pressure"]), - _ => c::boolean(key, v), + "angleVariation" => c::number(key, v, 0.0, 180.0), + "roundnessVariation" => c::number(key, v, 0.0, 100.0), + // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size + // take any mode (`set_option`). + "sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]), + "sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)), + "fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v), + _ => Err(c::unknown(key)), } } } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 9dfbdba2de..b554cfd045 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2822,6 +2822,20 @@ fn the_eraser_tip_follows_its_variation_modes() { [&o["angleMode"], &o["angleVariation"], &o["roundnessMode"], &o["roundnessVariation"], &o["sizeMode"], &o["sizeVariation"]], [&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)] ); + // `tool.setOption` takes back what the tool reports, and refuses a mode or Variation it does + // not take. + let reported = o.as_object().unwrap().clone(); + assert_eq!(t.check_options(&reported), Ok(())); + for mode in Variation::ALL { + for k in ["sizeMode", "angleMode", "roundnessMode"] { + assert_eq!(t.check_option(k, &json!(mode.id())), Ok(()), "{k} {mode:?}"); + } + } + let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`"; + assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}"))); + assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into())); + assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into())); + assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into())); // A mode it does not have leaves the mode as it was; a Variation is kept within its range. t.set_option("angleMode", &json!("wheel")); t.set_option("roundnessVariation", &json!(500)); diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 8507a82184..8389c6c297 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -159,6 +159,39 @@ mod tests { assert!(string_or_null("prev", &json!(3)).is_err()); } + /// Every tool takes back the options it reports, each on its own and all together: a dialog's + /// OK sends every field the tool showed it. The state a tool reports and doesn't take (the + /// picked mesh points, the text being edited, the pins, the queue of files to place) is left + /// out. + #[test] + fn every_tool_takes_the_options_it_reports() { + const TYPE: &[&str] = &["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; + const READ_ONLY: &[(&[&str], &[&str])] = &[ + (&["directSelection", "groupSelection", "lasso", "mesh", "magicWand"], &["meshPoints"]), + (TYPE, &["editing"]), + (&["puppetWarp"], &["pins", "selected"]), + // With nothing queued, `current` (0) is no file's index either. + (&["place"], &["count", "current", "name", "width", "height", "names"]), + ]; + let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); + let extra = ["place", "dimension"]; + let mut refused = Vec::new(); + for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { + let tool = crate::create(id); + let Some(mut options) = tool.options().as_object().cloned() else { continue }; + options.retain(|k, _| !read_only(id, k)); + for (k, v) in &options { + if let Err(e) = tool.check_option(k, v) { + refused.push(format!("tool `{id}`, option `{k}` = {v}: {e}")); + } + } + if let Err(e) = check_values(tool.as_ref(), &options) { + refused.push(e); + } + } + assert!(refused.is_empty(), "{}", refused.join("\n")); + } + #[test] fn set_option_params_reads_the_tool_and_the_options() { let p = json!({"tool": "smooth", "key": "fidelity", "value": 2, "values": {"x": 1}}); From b1f9081feb7e78b5f6f85087a10e107ceec62f48 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:57:06 -0800 Subject: [PATCH 5/8] Tools: the Arc tool keeps its lengths at most 1e6 pt, as tool.setOption takes them The Arc tool's setter took a length of any size, while its option check takes a number above 0 and at most 1e6, so a length set past 1e6 was reported back and then refused. The setter now keeps a length within that range. The catalog test also checks what each tool reports after a number option is set past either end and after a true-or-false option is flipped. docs/mcp.md gives the range tool.setOption takes for the Eraser's sizeVariation (0 to 1000). --- crates/tools/src/draw2/family.rs | 9 +++++++-- crates/tools/src/option_check.rs | 30 ++++++++++++++++++++++++------ docs/mcp.md | 2 +- 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index ae18ccd103..76c85fa4dd 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -531,9 +531,10 @@ impl Tool for FamilyTool { } } -/// Arc segment length from a dialog or preference value. +/// Arc segment length from a dialog or preference value, at most 1e6 pt (as the option check +/// takes it). fn arc_length(v: &Value, current: f64) -> f64 { - v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().max(1e-9)) + v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().clamp(1e-9, 1e6)) } /// A grid's Default Size side from option value `v`: a finite positive length (at most 1e6 pt), @@ -1030,6 +1031,10 @@ mod tests { "fillArc": true, }) ); + // A length past 1e6 pt is kept at 1e6, which `tool.setOption` takes back. + t.set_option("lengthX", &json!(-1e9)); + assert_eq!(t.options()["lengthX"], json!(1e6)); + assert_eq!(t.check_option("lengthX", &t.options()["lengthX"]), Ok(())); } /// While an arc is dragged out, C switches it between open and closed, F switches its base diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 8389c6c297..8b8d749d64 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -176,17 +176,35 @@ mod tests { let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); let extra = ["place", "dimension"]; let mut refused = Vec::new(); - for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { - let tool = crate::create(id); - let Some(mut options) = tool.options().as_object().cloned() else { continue }; + let mut check = |id: &str, tool: &dyn Tool, after: &str| { + let Some(mut options) = tool.options().as_object().cloned() else { return }; options.retain(|k, _| !read_only(id, k)); for (k, v) in &options { if let Err(e) = tool.check_option(k, v) { - refused.push(format!("tool `{id}`, option `{k}` = {v}: {e}")); + refused.push(format!("tool `{id}`{after}, option `{k}` = {v}: {e}")); } } - if let Err(e) = check_values(tool.as_ref(), &options) { - refused.push(e); + if let Err(e) = check_values(tool, &options) { + refused.push(format!("{e}{after}")); + } + }; + for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { + let tool = crate::create(id); + check(id, tool.as_ref(), ""); + // A number set past either end, or a true-or-false option flipped, is still taken back + // as the tool then reports it. + let Some(defaults) = tool.options().as_object().cloned() else { continue }; + for (k, v) in defaults.iter().filter(|(k, _)| !read_only(id, k)) { + let tries = match v { + Value::Number(_) => vec![json!(-1e9), json!(1e9)], + Value::Bool(b) => vec![json!(!b)], + _ => continue, + }; + for value in tries { + let mut changed = crate::create(id); + changed.set_option(k, &value); + check(id, changed.as_ref(), &format!(" after setting `{k}` to {value}")); + } } } assert!(refused.is_empty(), "{}", refused.join("\n")); diff --git a/docs/mcp.md b/docs/mcp.md index 73960b0b5a..21e8369e9a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5734,7 +5734,7 @@ drag without that reading, such as a mouse drag, erases at the value itself. One Tilt, Bearing and Rotation run, and the value itself without a reading are VectorCraft's own rules. The command refuses another mode, and a variation below 0 or past its range, and erases nothing. In the desktop app the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases. -`tool.setOption {tool: "eraser"}` takes the same keys. +`tool.setOption {tool: "eraser"}` takes the same keys, with `sizeVariation` from 0 to 1000. These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, naming the key; the document does not change and no undo step is recorded: `t`, `dx` and `dy` in From 33ff9103922a4ea1236a5b24dd001ec600e178d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:40:56 -0800 Subject: [PATCH 6/8] Tools: tool.setOption takes Crop Image's and the shape tools' newer options Crop Image's ppi, reference and linked and the shape tools' anchors reached main after the option checks were written, so tool.setOption refused them as unknown. Crop Image now checks them with the ranges check_options uses (the selected image's ppi limit stays in tool.setOption), and the shape tools take anchors from 2 to 1000 and refuse other counts, which the Ellipse dialog test now expects. The test that every tool takes back the options it reports now also covers the Crop Image and Intertwine tools, which the tool catalog does not list. --- crates/tools/src/cropimage.rs | 16 +++++++++++++++- crates/tools/src/option_check.rs | 3 ++- crates/tools/src/shape.rs | 1 + crates/tools/src/shape/tests.rs | 12 ++++++++++++ crates/ui-egui/src/dialogs/shapes.rs | 8 +++++--- 5 files changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index ae96ce5f5e..2e23159e5c 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -419,8 +419,13 @@ impl Tool for CropImageTool { }; } - /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. + /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. `ppi`, + /// `reference` and `linked` take the values [`check_options`] takes (the selected image's + /// limit on `ppi` is checked by `tool.setOption`, which knows the selection). fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if matches!(key, "ppi" | "reference" | "linked") { + return check_options(&serde_json::Map::from_iter([(key.to_string(), value.clone())]), None); + } if key != "rect" { return Err(crate::option_check::unknown(key)); } @@ -648,6 +653,15 @@ mod tests { ] { assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}"); } + // The tool takes the same values on its own, without an image's limit. + let t = CropImageTool::default(); + for (k, v) in [("ppi", json!(72)), ("ppi", json!(null)), ("reference", json!(0)), ("linked", json!(true)), ("rect", json!(null))] { + assert_eq!(t.check_option(k, &v), Ok(()), "{k}: {v}"); + } + assert_eq!(t.check_option("reference", &json!(9)), Err("`reference` must be a whole number from 0 to 8, not 9".into())); + assert_eq!(t.check_option("linked", &json!(1)), Err("`linked` must be true or false, not 1".into())); + assert_eq!(t.check_option("ppi", &json!(2401)), Err("`ppi` must be a number from 1 to 2400 or null, not 2401".into())); + assert_eq!(t.check_option("size", &json!(1)), Err("unknown option `size`".into())); } /// An image's own resolution, and the most it can be cropped to. diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 8b8d749d64..e84c316261 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -174,7 +174,8 @@ mod tests { (&["place"], &["count", "current", "name", "width", "height", "names"]), ]; let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); - let extra = ["place", "dimension"]; + // Tools that `create` makes and the catalog doesn't list. + let extra = ["place", "dimension", crate::cropimage::ID, "intertwine"]; let mut refused = Vec::new(); let mut check = |id: &str, tool: &dyn Tool, after: &str| { let Some(mut options) = tool.options().as_object().cloned() else { return }; diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index ae5864f73d..e4afa964fc 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -875,6 +875,7 @@ impl Tool for ShapeTool { use crate::option_check as c; match key { "sides" | "points" => c::whole(key, v, 3, 1000), + "anchors" => c::whole(key, v, 2, 1000), "cornerRadius" => c::number(key, v, 0.0, MAX_CORNER_RADIUS), "starRatio" => c::number(key, v, 0.01, 1.0), "length" => c::number(key, v, 0.0, 1e6), diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 4e0ee1d1dc..359b96ff2d 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1119,3 +1119,15 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() { assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["matrix"][4] == json!(10.0)), "{a:?}"); assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow); } + +/// `tool.setOption` takes an ellipse's anchor count from 2 to 1000, as the tool keeps it. +#[test] +fn the_anchor_count_is_checked_against_its_range() { + let t = ShapeTool::new("ellipse"); + for n in [2, 4, 1000] { + assert_eq!(t.check_option("anchors", &json!(n)), Ok(()), "{n}"); + } + for bad in [json!(1), json!(1001), json!(4.5), json!("4")] { + assert_eq!(t.check_option("anchors", &bad), Err("`anchors` must be a whole number from 2 to 1000".into()), "{bad}"); + } +} diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index e911d3f519..fb84701016 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -701,9 +701,11 @@ mod tests { super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0); app.ui.dialog = None; - // `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps. - for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] { - app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap(); + // `tool.setOption` takes it from 2 to 1000 and refuses other counts, and the dialog opens on + // what it keeps. + for (set, want) in [(json!(1), 6.0), (json!(2000), 6.0), (json!(2), 2.0), (json!(1000), 1000.0), (json!(7), 7.0)] { + let r = app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})); + assert_eq!(r.is_ok(), set.as_u64().is_some_and(|n| (2..=1000).contains(&n)), "{set}: {r:?}"); super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}"); app.ui.dialog = None; From d62cc8af278c89449837a939585704b29afd7e6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:49:48 -0800 Subject: [PATCH 7/8] Tools: option check treats the Polygonal Lasso's meshPoints as read-only like the Lasso's The Polygonal Lasso reports the Lasso's picked mesh points under meshPoints and, like the Lasso, does not take it back through tool.setOption, so the test lists it with the other read-only meshPoints tools. --- crates/tools/src/option_check.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index e84c316261..dd26fa28f0 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -167,7 +167,7 @@ mod tests { fn every_tool_takes_the_options_it_reports() { const TYPE: &[&str] = &["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; const READ_ONLY: &[(&[&str], &[&str])] = &[ - (&["directSelection", "groupSelection", "lasso", "mesh", "magicWand"], &["meshPoints"]), + (&["directSelection", "groupSelection", "lasso", "polygonalLasso", "mesh", "magicWand"], &["meshPoints"]), (TYPE, &["editing"]), (&["puppetWarp"], &["pins", "selected"]), // With nothing queued, `current` (0) is no file's index either. From 22d44c6fae716c3501316299662c5609daff03f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 08:55:24 -0800 Subject: [PATCH 8/8] Tools: the Spiral and Arc tools refuse the values they would keep as others The Spiral tool's option check took a decay up to 150 while the tool keeps at most 99.99, so `tool.setOption` reported success with another value. It now takes 5 to 99.99. The Arc tool's lengths are checked from 1e-9 to 1e6, the lengths it keeps. The Spiral dialog sends a typed decay past 99.99 as 99.99, the decay the spiral was already drawn with. The Arc dialog test now expects OK to refuse a slope outside -100 to 100 and a Base Along other than X or Y, leaving the dialog open and the options unchanged. The Slope field and its slider keep a typed value within that range. --- crates/engine/src/tests/toolsettings.rs | 7 ++++- crates/tools/src/draw2/family.rs | 29 +++++++++++++++-- crates/ui-egui/src/dialogs/shapes.rs | 41 +++++++++++++++++-------- 3 files changed, 60 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index ee8f2aa6e7..fbde9edca7 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -246,7 +246,12 @@ fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() { let mut s = session(); for active in [false, true] { select(&mut s, if active { "spiral" } else { "selection" }); - let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap(); + // A decay past the 99.99 % a spiral draws is refused, and nothing changes. + let before = s.tool_options_of("spiral"); + let refused = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})); + assert_eq!(refused.err(), Some("tool `spiral`: `decay` must be a number from 5 to 99.99".to_string())); + assert_eq!(s.tool_options_of("spiral"), before); + let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 99.99, "segments": 4, "clockwise": false}})).unwrap(); assert_eq!(options["decay"], json!(99.99)); assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99)); assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99)); diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index e6662630d6..06b7fa7105 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -519,11 +519,12 @@ impl Tool for FamilyTool { } let skew = vectorcraft_geom::shapes::GRID_SKEW_MAX; match key { - "lengthX" | "lengthY" | "width" | "height" => c::positive(key, v, 1e6), + "lengthX" | "lengthY" => c::number(key, v, 1e-9, 1e6), + "width" | "height" => c::positive(key, v, 1e6), "reference" => c::whole(key, v, 0, 8), "baseAlong" => c::one_of(key, v, &["x", "y", "X", "Y"]), "slope" => c::number(key, v, -100.0, 100.0), - "decay" => c::number(key, v, 5.0, 150.0), + "decay" => c::number(key, v, 5.0, 99.99), "segments" => c::whole(key, v, 2, 1000), "rows" | "concentric" | "columns" | "radial" => c::whole(key, v, 0, 999), "rowSkew" | "concentricSkew" | "columnSkew" | "radialSkew" => c::number(key, v, -skew, skew), @@ -532,7 +533,7 @@ impl Tool for FamilyTool { } } -/// Arc segment length from a dialog or preference value, at most 1e6 pt (as the option check +/// Arc segment length from a dialog or preference value, from 1e-9 to 1e6 pt (as the option check /// takes it). fn arc_length(v: &Value, current: f64) -> f64 { v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().clamp(1e-9, 1e6)) @@ -580,6 +581,28 @@ mod tests { } } + /// A number `tool.setOption` takes is kept as given, and a number the tool would keep as + /// another value is refused: `decay` past 99.99 is an error. + #[test] + fn family_tools_keep_the_numbers_their_option_check_takes() { + let tries = [-1e9, -150.0, -100.0, -1.0, 0.0, 1e-12, 0.5, 1.0, 2.0, 5.0, 8.0, 99.99, 100.0, 120.0, 150.0, 999.0, 1000.0, 1e6, 1e9]; + for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] { + let defaults = FamilyTool::new(id).options(); + for (k, _) in defaults.as_object().into_iter().flatten().filter(|(_, v)| v.is_number()) { + for n in tries { + let mut t = FamilyTool::new(id); + if t.check_option(k, &json!(n)).is_ok() { + t.set_option(k, &json!(n)); + assert_eq!(t.options()[k].as_f64(), Some(n), "{id} `{k}` = {n}"); + } + } + } + } + let t = FamilyTool::new("spiral"); + assert_eq!(t.check_option("decay", &json!(120.0)).err(), Some("`decay` must be a number from 5 to 99.99".into())); + assert!(t.check_option("decay", &json!(99.99)).is_ok()); + } + #[test] fn normalized_spiral_decay_preserves_existing_capped_paths_within_roundoff() { for requested in [100.0, 150.0] { diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index be7193e978..e077ff1d26 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -270,8 +270,8 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { const ARC_PREVIEW: egui::Vec2 = egui::vec2(160.0, 120.0); const ARC_PREVIEW_MARGIN: f32 = 12.0; -/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`], kept as the tool -/// keeps them: a slope from -100 to 100, a Base Along of Y or else X), as `shape.arc` draws it +/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`]; a slope past -100 +/// or 100, which OK refuses, is drawn at that end, and a Base Along other than Y along X), as `shape.arc` draws it /// with its reference point at the origin and General › Constrain Angle `constrain` (degrees) /// turning it about that point. `None` when a length or the slope is not finite. fn arc_preview_path(d: &Dialog, constrain: f64) -> Option { @@ -523,7 +523,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { "cx": x, "cy": y, "radius": d.f64("radius", 50.0).max(0.01), - "decay": d.f64("decay", 80.0).clamp(5.0, 150.0), + "decay": d.f64("decay", 80.0).clamp(5.0, 99.99), "segments": (d.f64("segments", 10.0) as u64).clamp(2, 1000), "clockwise": d.bool("clockwise"), }), @@ -646,6 +646,15 @@ mod tests { assert!(app.ui.dialog.is_none()); assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true})); + + // A decay typed past 99.99 % draws the spiral at 99.99 %, the most a spiral draws, and + // keeps that decay. + super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("decay".into(), json!(120.0)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + assert_eq!(app.session.tool_options_of("spiral")["decay"], json!(99.99)); } #[test] @@ -731,21 +740,27 @@ mod tests { } } - /// For values the Arc tool does not keep as typed, the picture shows the arc of the options OK - /// sets: the same picture as a dialog holding those options. + /// For values the dialog reads as other values, the picture shows the arc of the options OK + /// sets: the same picture as a dialog holding those options. A slope outside -100 to 100 or a + /// Base Along other than X or Y is refused: OK leaves the dialog open and keeps the options. #[test] fn the_arc_preview_shows_the_options_ok_sets() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); - for typed in [ - json!({"slope": 140.0}), - json!({"slope": -250.0}), - json!({"slope": "steep"}), - json!({"lengthX": "wide"}), - json!({"lengthY": null}), - json!({"baseAlong": "z"}), - json!({"reference": 12}), + for (typed, error) in [ + (json!({"slope": 140.0}), "`slope` must be a number from -100 to 100"), + (json!({"slope": -250.0}), "`slope` must be a number from -100 to 100"), + (json!({"baseAlong": "z"}), "`baseAlong` must be one of"), ] { + let before = app.session.tool_options_of("arc"); + app.ui.dialog = Some(arc_dialog(typed.clone())); + let r = super::super::confirm(&mut app); + assert!(r.as_ref().is_err_and(|e| e.contains(error)), "{typed}: {r:?}"); + assert!(app.ui.dialog.is_some(), "{typed}"); + assert_eq!(app.session.tool_options_of("arc"), before, "{typed}"); + app.ui.dialog = None; + } + for typed in [json!({"slope": "steep"}), json!({"lengthX": "wide"}), json!({"lengthY": null}), json!({"reference": 12})] { let d = arc_dialog(typed.clone()); let shown = arc_preview_path(&d, 0.0).expect("an arc"); app.ui.dialog = Some(d);