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.
This commit is contained in:
dotCooCoo
2026-11-13 17:25:12 -08:00
parent 0b29b2b1f6
commit a315b7ef6b
53 changed files with 796 additions and 46 deletions
+11 -5
View File
@@ -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}");
}
}
+102
View File
@@ -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": "<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": "<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");
}
}
+20 -8
View File
@@ -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<Value, String> {
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))
+15
View File
@@ -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| {
+1 -1
View File
@@ -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",
+10
View File
@@ -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)]
+29
View File
@@ -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)),
}
}
}
+9
View File
@@ -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()
}
+10
View File
@@ -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::<CornerKind>(v.clone()).is_ok() => Ok(()),
"kind" => Err("`kind` must be one of `round`, `invertedRound`, `chamfer`".into()),
_ => Err(c::unknown(key)),
}
}
}
#[cfg(test)]
+8
View File
@@ -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)]
@@ -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<String, Value>) -> 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)]
+10
View File
@@ -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)]
+4
View File
@@ -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)]
+3
View File
@@ -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
+8
View File
@@ -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())]))
}
}
+13
View File
@@ -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::<Option<Vec<_>>>());
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<Action> {
self.reset();
vec![]
+9
View File
@@ -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)]
+7
View File
@@ -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<Action> {
self.at = ev.pos;
self.shift = ev.mods.shift;
+19
View File
@@ -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()
+9
View File
@@ -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()
}
+19
View File
@@ -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.
+20
View File
@@ -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)]
+12
View File
@@ -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.
+4
View File
@@ -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
}
+13
View File
@@ -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<String, Value>) -> 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
+9
View File
@@ -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()
}
+154
View File
@@ -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<String> = 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, Value>), 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<String, Value>) -> 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());
}
}
+56
View File
@@ -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<String, Value>) -> 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<Action> {
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<usize, String> {
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::*;
+14
View File
@@ -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)]
+12
View File
@@ -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()
}
+19
View File
@@ -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::<Vec<TextRun>>(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<Overlay> {
let mut o = self.snap.guides().to_vec();
if let (Some((_, s)), Some(d)) = (self.press, self.drag) {
+12
View File
@@ -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, .. }))
+10
View File
@@ -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<Action> {
self.text_selection.after_command(cx)
+9
View File
@@ -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<Action> {
self.quad = None;
self.guides.clear();
+9
View File
@@ -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<Action> {
if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] }
}
+5 -2
View File
@@ -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<Value, String> {
let tool = d.str("__tool");
let values: Map<String, Value> = 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
}
+10
View File
@@ -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";
+9 -6
View File
@@ -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]
+2 -2
View File
@@ -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<Value, String> {
let values: Map<String, Value> = 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)]
@@ -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] {
+2 -2
View File
@@ -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<Value, String> {
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)]
@@ -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<Value, String> {
checked(&d.str("color"))?;
}
let values: Map<String, Value> = 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)]
@@ -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<Value, String> {
checked(&d.str("color"))?;
}
let values: Map<String, Value> = 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)]
@@ -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<Value, String> {
let values: Map<String, Value> = ["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)]
@@ -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<Value, String> {
checked(&d.str("highlightColor"))?;
}
let values: Map<String, Value> = 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)]
+11 -7
View File
@@ -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<Value, String> {
// 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<Value, String> {
// 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, &params, vectorcraft_geom::Point::new(x, y)) {
Some((id, params)) => run_and_close(app, &id, params),
None => {
@@ -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<String, Value> = 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)]
@@ -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]
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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) {
+5 -1
View File
@@ -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`,
+12
View File
@@ -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
+1
View File
@@ -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.