diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs
index 52c6ffa271..dfab5336de 100644
--- a/crates/engine/src/tests/build.rs
+++ b/crates/engine/src/tests/build.rs
@@ -1083,6 +1083,36 @@ fn shape_builder_drops_a_press_held_during_a_merge() {
}
}
+/// 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();
+ 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")));
+ // 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
/// 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/tests/draw2.rs b/crates/engine/src/tests/draw2.rs
index 8fa31889a2..242072bdb0 100644
--- a/crates/engine/src/tests/draw2.rs
+++ b/crates/engine/src/tests/draw2.rs
@@ -6292,14 +6292,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 a9d9e3f5bd..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));
@@ -387,3 +392,110 @@ 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"));
+ // 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);
+}
+
+/// 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 90a7c001e0..794cc7a2a3 100644
--- a/crates/engine/src/tooling.rs
+++ b/crates/engine/src/tooling.rs
@@ -1321,7 +1321,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
@@ -1333,14 +1340,22 @@ 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.
+ 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);
- 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
@@ -1348,11 +1363,14 @@ 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);
}
}
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.
@@ -1364,21 +1382,28 @@ 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 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 = 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));
+ // 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(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)?;
- if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
+ vectorcraft_tools::builder::check_builder_options(id, &values)?;
+ if id == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
// The most the selected image can be cropped to, when one is selected.
let max = self.doc().ok().and_then(|st| {
@@ -1397,7 +1422,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())?;
}
@@ -1407,11 +1432,16 @@ impl Session {
return Err("Unknown dimension mode".into());
}
}
+ 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 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))
+ 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/mcp/src/headless.rs b/crates/mcp/src/headless.rs
index cbd2e8ca87..db6c51d47d 100644
--- a/crates/mcp/src/headless.rs
+++ b/crates/mcp/src/headless.rs
@@ -53,7 +53,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 4760380bc2..793f16efee 100644
--- a/crates/mcp/src/tests/liquify.rs
+++ b/crates/mcp/src/tests/liquify.rs
@@ -28,6 +28,36 @@ 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);
+}
+
+/// `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 e57af72c75..bb2c6b9927 100644
--- a/crates/mcp/src/ui_catalog.rs
+++ b/crates/mcp/src/ui_catalog.rs
@@ -851,7 +851,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 (`{}` 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/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 470795579e..05ec27b18b 100644
--- a/crates/tools/src/addons/corner_tool.rs
+++ b/crates/tools/src/addons/corner_tool.rs
@@ -382,6 +382,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 816000ac9f..e844da9130 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 33700073c7..e651f5399b 100644
--- a/crates/tools/src/addons/parametric_shape.rs
+++ b/crates/tools/src/addons/parametric_shape.rs
@@ -475,6 +475,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 43269ed580..805e015159 100644
--- a/crates/tools/src/addons/smart_pen.rs
+++ b/crates/tools/src/addons/smart_pen.rs
@@ -625,6 +625,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 ea3324dc33..77ff240f75 100644
--- a/crates/tools/src/builder.rs
+++ b/crates/tools/src/builder.rs
@@ -858,6 +858,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 caa9379308..c694240057 100644
--- a/crates/tools/src/builder/live_paint.rs
+++ b/crates/tools/src/builder/live_paint.rs
@@ -870,6 +870,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()
}
@@ -1293,4 +1297,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 13691da613..2e23159e5c 100644
--- a/crates/tools/src/cropimage.rs
+++ b/crates/tools/src/cropimage.rs
@@ -419,6 +419,24 @@ impl Tool for CropImageTool {
};
}
+ /// `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));
+ }
+ let numbers = value.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(Value::as_f64).collect::