mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 12:38:18 +00:00
Merge pull request #7366 from dotCooCoo/fix/tool-set-option-errors
Tools: setting a tool option with a bad value returns an error
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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": "<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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<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));
|
||||
// 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`]):
|
||||
|
||||
@@ -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",
|
||||
),
|
||||
];
|
||||
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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::<CornerKind>(v.clone()).is_ok() => Ok(()),
|
||||
"kind" => Err("`kind` must be one of `round`, `invertedRound`, `chamfer`".into()),
|
||||
_ => Err(c::unknown(key)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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<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)]
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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())]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::<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![]
|
||||
@@ -635,6 +653,15 @@ mod tests {
|
||||
] {
|
||||
assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}");
|
||||
}
|
||||
// The tool takes the same values on its own, without an image's limit.
|
||||
let t = CropImageTool::default();
|
||||
for (k, v) in [("ppi", json!(72)), ("ppi", json!(null)), ("reference", json!(0)), ("linked", json!(true)), ("rect", json!(null))] {
|
||||
assert_eq!(t.check_option(k, &v), Ok(()), "{k}: {v}");
|
||||
}
|
||||
assert_eq!(t.check_option("reference", &json!(9)), Err("`reference` must be a whole number from 0 to 8, not 9".into()));
|
||||
assert_eq!(t.check_option("linked", &json!(1)), Err("`linked` must be true or false, not 1".into()));
|
||||
assert_eq!(t.check_option("ppi", &json!(2401)), Err("`ppi` must be a number from 1 to 2400 or null, not 2401".into()));
|
||||
assert_eq!(t.check_option("size", &json!(1)), Err("unknown option `size`".into()));
|
||||
}
|
||||
|
||||
/// An image's own resolution, and the most it can be cropped to.
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -579,6 +579,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;
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -529,11 +529,32 @@ 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" => c::number(key, v, 1e-9, 1e6),
|
||||
"width" | "height" => c::positive(key, v, 1e6),
|
||||
"reference" => c::whole(key, v, 0, 8),
|
||||
"baseAlong" => c::one_of(key, v, &["x", "y", "X", "Y"]),
|
||||
"slope" => c::number(key, v, -100.0, 100.0),
|
||||
"decay" => c::number(key, v, 5.0, 99.99),
|
||||
"segments" => c::whole(key, v, 2, 1000),
|
||||
"rows" | "concentric" | "columns" | "radial" => c::whole(key, v, 0, 999),
|
||||
"rowSkew" | "concentricSkew" | "columnSkew" | "radialSkew" => c::number(key, v, -skew, skew),
|
||||
_ => c::boolean(key, v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Arc segment length from a dialog or preference value.
|
||||
/// Arc segment length from a dialog or preference value, from 1e-9 to 1e6 pt (as the option check
|
||||
/// takes it).
|
||||
fn arc_length(v: &Value, current: f64) -> f64 {
|
||||
v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().max(1e-9))
|
||||
v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().clamp(1e-9, 1e6))
|
||||
}
|
||||
|
||||
/// A grid's Default Size side from option value `v`: a finite positive length (at most 1e6 pt),
|
||||
@@ -578,6 +599,28 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A number `tool.setOption` takes is kept as given, and a number the tool would keep as
|
||||
/// another value is refused: `decay` past 99.99 is an error.
|
||||
#[test]
|
||||
fn family_tools_keep_the_numbers_their_option_check_takes() {
|
||||
let tries = [-1e9, -150.0, -100.0, -1.0, 0.0, 1e-12, 0.5, 1.0, 2.0, 5.0, 8.0, 99.99, 100.0, 120.0, 150.0, 999.0, 1000.0, 1e6, 1e9];
|
||||
for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] {
|
||||
let defaults = FamilyTool::new(id).options();
|
||||
for (k, _) in defaults.as_object().into_iter().flatten().filter(|(_, v)| v.is_number()) {
|
||||
for n in tries {
|
||||
let mut t = FamilyTool::new(id);
|
||||
if t.check_option(k, &json!(n)).is_ok() {
|
||||
t.set_option(k, &json!(n));
|
||||
assert_eq!(t.options()[k].as_f64(), Some(n), "{id} `{k}` = {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let t = FamilyTool::new("spiral");
|
||||
assert_eq!(t.check_option("decay", &json!(120.0)).err(), Some("`decay` must be a number from 5 to 99.99".into()));
|
||||
assert!(t.check_option("decay", &json!(99.99)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalized_spiral_decay_preserves_existing_capped_paths_within_roundoff() {
|
||||
for requested in [100.0, 150.0] {
|
||||
@@ -1067,6 +1110,10 @@ mod tests {
|
||||
"fillArc": true,
|
||||
})
|
||||
);
|
||||
// A length past 1e6 pt is kept at 1e6, which `tool.setOption` takes back.
|
||||
t.set_option("lengthX", &json!(-1e9));
|
||||
assert_eq!(t.options()["lengthX"], json!(1e6));
|
||||
assert_eq!(t.check_option("lengthX", &t.options()["lengthX"]), Ok(()));
|
||||
}
|
||||
|
||||
/// While an arc is dragged out, C switches it between open and closed, F switches its base
|
||||
|
||||
@@ -2059,6 +2059,32 @@ 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),
|
||||
"angleVariation" => c::number(key, v, 0.0, 180.0),
|
||||
"roundnessVariation" => c::number(key, v, 0.0, 100.0),
|
||||
// The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size
|
||||
// take any mode (`set_option`).
|
||||
"sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]),
|
||||
"sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)),
|
||||
"fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v),
|
||||
_ => Err(c::unknown(key)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -3087,6 +3087,20 @@ fn the_eraser_tip_follows_its_variation_modes() {
|
||||
[&o["angleMode"], &o["angleVariation"], &o["roundnessMode"], &o["roundnessVariation"], &o["sizeMode"], &o["sizeVariation"]],
|
||||
[&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)]
|
||||
);
|
||||
// `tool.setOption` takes back what the tool reports, and refuses a mode or Variation it does
|
||||
// not take.
|
||||
let reported = o.as_object().unwrap().clone();
|
||||
assert_eq!(t.check_options(&reported), Ok(()));
|
||||
for mode in Variation::ALL {
|
||||
for k in ["sizeMode", "angleMode", "roundnessMode"] {
|
||||
assert_eq!(t.check_option(k, &json!(mode.id())), Ok(()), "{k} {mode:?}");
|
||||
}
|
||||
}
|
||||
let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`";
|
||||
assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}")));
|
||||
assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into()));
|
||||
assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into()));
|
||||
assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into()));
|
||||
// A mode it does not have leaves the mode as it was; a Variation is kept within its range.
|
||||
t.set_option("angleMode", &json!("wheel"));
|
||||
t.set_option("roundnessVariation", &json!(500));
|
||||
|
||||
@@ -400,6 +400,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.
|
||||
|
||||
@@ -364,6 +364,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
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -160,6 +161,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
|
||||
|
||||
@@ -1106,6 +1106,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()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! 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, and so are parameters that are not an object. With none of `key` and
|
||||
/// `values`, or with no parameters (null), the options are empty: the command reads them.
|
||||
pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map<String, Value>), String> {
|
||||
if !p.is_object() && !p.is_null() {
|
||||
return Err(format!("the params must be an object, not {}", shown(p)));
|
||||
}
|
||||
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))
|
||||
}
|
||||
|
||||
/// The JSON text of `v` as a parameter error shows it: cut to 40 characters, with `…` when it was
|
||||
/// longer. The text is written only up to the cut.
|
||||
fn shown(v: &Value) -> String {
|
||||
struct Cut {
|
||||
text: String,
|
||||
left: usize,
|
||||
}
|
||||
impl std::fmt::Write for Cut {
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
for c in s.chars() {
|
||||
if self.left == 0 {
|
||||
return Err(std::fmt::Error);
|
||||
}
|
||||
self.left -= 1;
|
||||
self.text.push(c);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let mut out = Cut { text: String::new(), left: 40 };
|
||||
if std::fmt::Write::write_fmt(&mut out, format_args!("{v}")).is_err() {
|
||||
out.text.push('…');
|
||||
}
|
||||
out.text
|
||||
}
|
||||
|
||||
/// Check every one of `values` as an option of `tool` ([`Tool::check_options`]), before any is
|
||||
/// set: the first one the tool doesn't take is an error that names the tool.
|
||||
pub fn check_values(tool: &dyn Tool, values: &Map<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());
|
||||
}
|
||||
|
||||
/// Every tool takes back the options it reports, each on its own and all together: a dialog's
|
||||
/// OK sends every field the tool showed it. The state a tool reports and doesn't take (the
|
||||
/// picked mesh points, the text being edited, the pins, the queue of files to place) is left
|
||||
/// out.
|
||||
#[test]
|
||||
fn every_tool_takes_the_options_it_reports() {
|
||||
const TYPE: &[&str] = &["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"];
|
||||
const READ_ONLY: &[(&[&str], &[&str])] = &[
|
||||
(&["directSelection", "groupSelection", "lasso", "polygonalLasso", "mesh", "magicWand"], &["meshPoints"]),
|
||||
(TYPE, &["editing"]),
|
||||
(&["puppetWarp"], &["pins", "selected"]),
|
||||
// With nothing queued, `current` (0) is no file's index either.
|
||||
(&["place"], &["count", "current", "name", "width", "height", "names"]),
|
||||
];
|
||||
let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k));
|
||||
// Tools that `create` makes and the catalog doesn't list.
|
||||
let extra = ["place", "dimension", crate::cropimage::ID, "intertwine"];
|
||||
let mut refused = Vec::new();
|
||||
let mut check = |id: &str, tool: &dyn Tool, after: &str| {
|
||||
let Some(mut options) = tool.options().as_object().cloned() else { return };
|
||||
options.retain(|k, _| !read_only(id, k));
|
||||
for (k, v) in &options {
|
||||
if let Err(e) = tool.check_option(k, v) {
|
||||
refused.push(format!("tool `{id}`{after}, option `{k}` = {v}: {e}"));
|
||||
}
|
||||
}
|
||||
if let Err(e) = check_values(tool, &options) {
|
||||
refused.push(format!("{e}{after}"));
|
||||
}
|
||||
};
|
||||
for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) {
|
||||
let tool = crate::create(id);
|
||||
check(id, tool.as_ref(), "");
|
||||
// A number set past either end, or a true-or-false option flipped, is still taken back
|
||||
// as the tool then reports it.
|
||||
let Some(defaults) = tool.options().as_object().cloned() else { continue };
|
||||
for (k, v) in defaults.iter().filter(|(k, _)| !read_only(id, k)) {
|
||||
let tries = match v {
|
||||
Value::Number(_) => vec![json!(-1e9), json!(1e9)],
|
||||
Value::Bool(b) => vec![json!(!b)],
|
||||
_ => continue,
|
||||
};
|
||||
for value in tries {
|
||||
let mut changed = crate::create(id);
|
||||
changed.set_option(k, &value);
|
||||
check(id, changed.as_ref(), &format!(" after setting `{k}` to {value}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(refused.is_empty(), "{}", refused.join("\n"));
|
||||
}
|
||||
|
||||
#[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());
|
||||
// Omitted parameters arrive as null: a read, like `{}`.
|
||||
let (tool, values) = set_option_params(&Value::Null).unwrap();
|
||||
assert!(tool.is_none() && values.is_empty());
|
||||
for (bad, got) in [(json!(true), "true"), (json!(7), "7"), (json!([]), "[]"), (json!("x"), "\"x\"")] {
|
||||
assert_eq!(set_option_params(&bad).err(), Some(format!("the params must be an object, not {got}")), "{bad}");
|
||||
}
|
||||
// A long value is shown cut, as the other parameter errors show it.
|
||||
let long = json!("a".repeat(100));
|
||||
let shown = format!("\"{}…", "a".repeat(39));
|
||||
assert_eq!(set_option_params(&long).err(), Some(format!("the params must be an object, not {shown}")));
|
||||
assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into()));
|
||||
assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into()));
|
||||
assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into()));
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,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();
|
||||
@@ -196,6 +223,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::*;
|
||||
|
||||
@@ -1088,6 +1088,21 @@ 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),
|
||||
"anchors" => c::whole(key, v, 2, 1000),
|
||||
"cornerRadius" => c::number(key, v, 0.0, MAX_CORNER_RADIUS),
|
||||
"starRatio" => c::number(key, v, 0.01, 1.0),
|
||||
"length" => c::number(key, v, 0.0, 1e6),
|
||||
"angle" => c::finite(key, v),
|
||||
"fillLine" => c::boolean(key, v),
|
||||
_ => Err(c::unknown(key)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1659,6 +1659,18 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() {
|
||||
assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow);
|
||||
}
|
||||
|
||||
/// `tool.setOption` takes an ellipse's anchor count from 2 to 1000, as the tool keeps it.
|
||||
#[test]
|
||||
fn the_anchor_count_is_checked_against_its_range() {
|
||||
let t = ShapeTool::new("ellipse");
|
||||
for n in [2, 4, 1000] {
|
||||
assert_eq!(t.check_option("anchors", &json!(n)), Ok(()), "{n}");
|
||||
}
|
||||
for bad in [json!(1), json!(1001), json!(4.5), json!("4")] {
|
||||
assert_eq!(t.check_option("anchors", &bad), Err("`anchors` must be a whole number from 2 to 1000".into()), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A drag event to `(x, y)` with Backtick held or not.
|
||||
fn quote_drag(x: f64, y: f64, held: bool) -> PointerEvent {
|
||||
PointerEvent { backquote: held, ..PointerEvent::new(PointerKind::Drag, x, y) }
|
||||
|
||||
@@ -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.
|
||||
@@ -293,6 +302,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()
|
||||
}
|
||||
|
||||
@@ -609,6 +609,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) {
|
||||
|
||||
@@ -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, .. }))
|
||||
|
||||
@@ -593,6 +593,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)
|
||||
|
||||
@@ -387,6 +387,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();
|
||||
|
||||
@@ -432,6 +432,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![] }
|
||||
}
|
||||
|
||||
@@ -246,12 +246,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
|
||||
}
|
||||
|
||||
|
||||
@@ -652,6 +652,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";
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -155,12 +155,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 }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,10 +314,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]
|
||||
|
||||
@@ -21,7 +21,7 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_brush::Variation;
|
||||
|
||||
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};
|
||||
@@ -391,7 +391,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] {
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -15,7 +15,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};
|
||||
|
||||
@@ -86,7 +86,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};
|
||||
|
||||
@@ -73,7 +73,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)]
|
||||
|
||||
@@ -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),
|
||||
@@ -270,8 +270,8 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
|
||||
const ARC_PREVIEW: egui::Vec2 = egui::vec2(160.0, 120.0);
|
||||
const ARC_PREVIEW_MARGIN: f32 = 12.0;
|
||||
|
||||
/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`], kept as the tool
|
||||
/// keeps them: a slope from -100 to 100, a Base Along of Y or else X), as `shape.arc` draws it
|
||||
/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`]; a slope past -100
|
||||
/// or 100, which OK refuses, is drawn at that end, and a Base Along other than Y along X), as `shape.arc` draws it
|
||||
/// with its reference point at the origin and General › Constrain Angle `constrain` (degrees)
|
||||
/// turning it about that point. `None` when a length or the slope is not finite.
|
||||
fn arc_preview_path(d: &Dialog, constrain: f64) -> Option<vectorcraft_geom::path::PathData> {
|
||||
@@ -554,13 +554,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
|
||||
@@ -590,7 +588,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
"cx": x,
|
||||
"cy": y,
|
||||
"radius": d.f64("radius", 50.0).max(0.01),
|
||||
"decay": d.f64("decay", 80.0).clamp(5.0, 150.0),
|
||||
"decay": d.f64("decay", 80.0).clamp(5.0, 99.99),
|
||||
"segments": (d.f64("segments", 10.0) as u64).clamp(2, 1000),
|
||||
"clockwise": d.bool("clockwise"),
|
||||
}),
|
||||
@@ -648,7 +646,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, ¶ms, vectorcraft_geom::Point::new(x, y)) {
|
||||
Some((id, params)) => run_and_close(app, &id, params),
|
||||
None => {
|
||||
@@ -707,6 +711,15 @@ mod tests {
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1);
|
||||
assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true}));
|
||||
|
||||
// A decay typed past 99.99 % draws the spiral at 99.99 %, the most a spiral draws, and
|
||||
// keeps that decay.
|
||||
super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0}));
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("decay".into(), json!(120.0));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
|
||||
assert_eq!(app.session.tool_options_of("spiral")["decay"], json!(99.99));
|
||||
}
|
||||
|
||||
/// With General › Constrain Angle at 90°, the Spiral dialog's spiral starts straight up from the
|
||||
@@ -812,21 +825,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// For values the Arc tool does not keep as typed, the picture shows the arc of the options OK
|
||||
/// sets: the same picture as a dialog holding those options.
|
||||
/// For values the dialog reads as other values, the picture shows the arc of the options OK
|
||||
/// sets: the same picture as a dialog holding those options. A slope outside -100 to 100 or a
|
||||
/// Base Along other than X or Y is refused: OK leaves the dialog open and keeps the options.
|
||||
#[test]
|
||||
fn the_arc_preview_shows_the_options_ok_sets() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
for typed in [
|
||||
json!({"slope": 140.0}),
|
||||
json!({"slope": -250.0}),
|
||||
json!({"slope": "steep"}),
|
||||
json!({"lengthX": "wide"}),
|
||||
json!({"lengthY": null}),
|
||||
json!({"baseAlong": "z"}),
|
||||
json!({"reference": 12}),
|
||||
for (typed, error) in [
|
||||
(json!({"slope": 140.0}), "`slope` must be a number from -100 to 100"),
|
||||
(json!({"slope": -250.0}), "`slope` must be a number from -100 to 100"),
|
||||
(json!({"baseAlong": "z"}), "`baseAlong` must be one of"),
|
||||
] {
|
||||
let before = app.session.tool_options_of("arc");
|
||||
app.ui.dialog = Some(arc_dialog(typed.clone()));
|
||||
let r = super::super::confirm(&mut app);
|
||||
assert!(r.as_ref().is_err_and(|e| e.contains(error)), "{typed}: {r:?}");
|
||||
assert!(app.ui.dialog.is_some(), "{typed}");
|
||||
assert_eq!(app.session.tool_options_of("arc"), before, "{typed}");
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
for typed in [json!({"slope": "steep"}), json!({"lengthX": "wide"}), json!({"lengthY": null}), json!({"reference": 12})] {
|
||||
let d = arc_dialog(typed.clone());
|
||||
let shown = arc_preview_path(&d, 0.0).expect("an arc");
|
||||
app.ui.dialog = Some(d);
|
||||
@@ -1112,9 +1131,11 @@ mod tests {
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0);
|
||||
app.ui.dialog = None;
|
||||
// `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps.
|
||||
for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] {
|
||||
app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap();
|
||||
// `tool.setOption` takes it from 2 to 1000 and refuses other counts, and the dialog opens on
|
||||
// what it keeps.
|
||||
for (set, want) in [(json!(1), 6.0), (json!(2000), 6.0), (json!(2), 2.0), (json!(1000), 1000.0), (json!(7), 7.0)] {
|
||||
let r = app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}}));
|
||||
assert_eq!(r.is_ok(), set.as_u64().is_some_and(|n| (2..=1000).contains(&n)), "{set}: {r:?}");
|
||||
super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0}));
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}");
|
||||
app.ui.dialog = None;
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -852,7 +852,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",
|
||||
),
|
||||
(
|
||||
crate::touch::TOGGLE_MODE,
|
||||
|
||||
@@ -1211,7 +1211,7 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) {
|
||||
ui.label(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);
|
||||
|
||||
@@ -971,7 +971,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; parameters that are
|
||||
not an object are an error. Every option given is checked before any is set: an option the tool doesn't have, a value
|
||||
of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option
|
||||
(``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes.
|
||||
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`,
|
||||
|
||||
+14
-1
@@ -6318,7 +6318,7 @@ The command refuses another mode, and a variation below 0 or past its range, and
|
||||
the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases, and the
|
||||
outline of the area a drag covers takes, at each step, the tip the pen's readings give halfway along it. A Random
|
||||
value shows as the value itself there, since the release draws it.
|
||||
`tool.setOption {tool: "eraser"}` takes the same keys.
|
||||
`tool.setOption {tool: "eraser"}` takes the same keys, with `sizeVariation` from 0 to 1000.
|
||||
|
||||
`path.eraseRegion {rect: [x, y, width, height]}` takes a rectangle in place of `points` and erases everything inside
|
||||
it from the paths (selected, or all), as an Alt-drag with the Eraser does ([Eraser tool
|
||||
@@ -11938,10 +11938,23 @@ 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. Parameters that are not an object are an error too. `{}`, or no parameters, reads the options and sets
|
||||
nothing. The ranges are VectorCraft's own (for example the Smooth tool's `fidelity` takes 0.05 to 100, the Pencil's
|
||||
0.01 to 100); a refused value in a Tool Options dialog keeps the dialog open. The Live Paint tools' `width` and the
|
||||
Shape Builder's `gapLength` are set to the nearest end of their range when a number outside it is given, as their
|
||||
sections above say.
|
||||
|
||||
```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
|
||||
|
||||
@@ -850,6 +850,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.
|
||||
|
||||
Reference in New Issue
Block a user