diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 96b9e51f99..1793f17d5c 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -199,14 +199,11 @@ pub fn specs() -> Vec { // ---------- helpers ---------- -/// Number param that also accepts strings like `"10 pt"`. +/// Number param that also accepts a string when all of it is a number (`"10"`, not `"10abc"`). pub(crate) fn num_param(p: &Value, key: &str) -> Option { match p.get(key)? { Value::Number(n) => n.as_f64(), - Value::String(s) => { - let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect(); - t.parse().ok() - } + Value::String(s) => whole_number(s), _ => None, } .filter(|v: &f64| v.is_finite()) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 0d75061bee..3af85a8265 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -11,8 +11,8 @@ use super::menucmds::whole_or; use super::stroke::StrokeChange; use super::typecmd::refresh_bounds; use super::{ - CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index, - number_or, object_param, point_param, str_param, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, finite_numbers, has_doc, has_selection, + index, number_or, object_param, str_param, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Area / Path Type", [], None, - "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", + "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point; anything but two numbers: an error), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", has_doc, create_in_path ), @@ -255,9 +255,15 @@ fn byte_param(p: &Value, k: &str) -> Option { /// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any /// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result { + Ok(offset_given(p, k, cmd)?.unwrap_or(default)) +} + +/// The byte offset that `p` gives for `k`, or `None` when `p` leaves it out or gives null. Any +/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. +fn offset_given(p: &Value, k: &str, cmd: &str) -> Result> { match p.get(k) { - None | Some(Value::Null) => Ok(default), - Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)), + None | Some(Value::Null) => Ok(None), + Some(_) => Ok(Some(index(whole_or(p, k, 0, cmd)?))), } } @@ -280,7 +286,7 @@ pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?), }; - let insert = str_param(p, "insert").unwrap_or("").to_string(); + let insert = text_param(p, "insert", C)?.unwrap_or("").to_string(); let clear = clear_param(s, p, id, C)?; let caret = s.edit("Typing", |d, _| { for other in &clear { @@ -1313,8 +1319,7 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve /// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error /// when there is no character there, it is an inline graphic, or its font is not available. fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range, std::sync::Arc)> { - check_numbers(p, &["start"], c)?; - let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; + let start = offset_given(p, "start", c)?.ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; let mut at = 0; for run in &t.runs { let end = at + run.text.len(); @@ -1558,8 +1563,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result { fn touch_type(s: &mut Session, p: &Value) -> Result { const C: &str = "text.touchType"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; - check_numbers(p, &["start"], C)?; - let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; + let start = offset_given(p, "start", C)?.ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "nothing to change: give dx, dy, hScale, vScale or rotation")); } @@ -1797,7 +1801,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { fn create_in_path(s: &mut Session, p: &Value) -> Result { const C: &str = "text.createInPath"; let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?; - let on_path = match str_param(p, "mode").unwrap_or("area") { + let on_path = match text_param(p, "mode", C)?.unwrap_or("area") { "area" => false, "onPath" | "path" => true, o => return Err(bad(C, format!("mode must be area|onPath, got {o}"))), @@ -1815,8 +1819,12 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { check_switches(p, &["vertical", "placeholder"], C)?; super::color_param(p, "color", C)?; let style = super::create::new_type_style(s, p, C)?; - let text = str_param(p, "text").unwrap_or("").to_string(); - let start = match point_param(p, "at") { + let text = text_param(p, "text", C)?.unwrap_or("").to_string(); + let at = match p.get("at").filter(|v| !v.is_null()) { + None => None, + Some(v) => Some(finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be a point: [x, y]"))?), + }; + let start = match at { Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0), _ => 0.0, }; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 185baf734f..2a62a46374 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -13,7 +13,7 @@ use super::edit::selected_roots; use super::pathops::{length_given, number_given, shape_node}; use super::{ CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or, - object_param, ok, str_param, switch_or, targets, text_param, + object_param, ok, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -873,7 +873,7 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option, mut f: i } fn set_text(s: &mut Session, p: &Value) -> Result { - let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); + let text = text_param(p, "text", "text.setText")?.ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); let ids = text_targets(s, p, "text.setText")?; // The text the type already has is no undo step. edit_if_nodes_changed(s, "Typing", &ids, |d| { diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index feb71e40ad..6bd92225db 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1736,11 +1736,17 @@ fn pathfinder_options_round_trip_and_refuse_bad_values() { assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set); let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap(); assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}"); + for (given, want) in [("10 pt", 10.0), ("0.25", 0.25)] { + let r = s.execute("object.pathfinder.options", &json!({"precision": given})).unwrap(); + assert_eq!(r["precision"], json!(want), "{given}"); + } s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap(); for bad in [ json!({"precision": 0}), json!({"precision": 11}), json!({"precision": "x"}), + json!({"precision": "1abc"}), + json!({"precision": "0.5 extra"}), json!({"precision": -1}), json!({"removeRedundantPoints": "yes"}), json!({"removeUnpainted": 1}), diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 8857378855..d49b18b031 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -671,6 +671,48 @@ fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() { s.execute("text.setPathHandle", &handle(Value::Null)).unwrap(); } +/// Range edits, Set Text, area and on-path type and the glyph commands refuse a param of the wrong +/// type with an error naming the param, and leave the document and the undo history as they were: +/// text that is not a string, a byte offset that is fractional or negative, and a point that is not +/// two numbers. Null counts as a param left out, which keeps its default. +#[test] +fn text_edits_refuse_a_param_of_the_wrong_type() { + use crate::tests::not_refused; + let mut s = session(); + let id = text(&mut s, "abc"); + let frame = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 100, "height": 50})).unwrap()["id"].clone(); + let line = s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 400}, {"x": 400, "y": 400}]})).unwrap()["id"].clone(); + let string = |k: &str| format!("`{k}` must be a string"); + let whole = "`start` must be a whole number".to_string(); + let point = "`at` must be a point: [x, y]".to_string(); + let calls: Vec<(String, Value, String)> = [ + ("text.editRange", json!({"id": id.0, "start": 0, "end": 1, "insert": 5}), string("insert")), + ("text.editRange", json!({"id": id.0, "start": 0, "end": 3, "insert": ["x"]}), string("insert")), + ("text.setText", json!({"ids": [id.0], "text": true}), string("text")), + ("text.createInPath", json!({"path": frame, "mode": 1}), string("mode")), + ("text.createInPath", json!({"path": frame, "text": true}), string("text")), + ("text.createInPath", json!({"path": line, "mode": "onPath", "text": "a", "at": [1, "y"]}), point.clone()), + ("text.createInPath", json!({"path": line, "mode": "onPath", "at": [100]}), point.clone()), + ("text.createInPath", json!({"path": frame, "text": "a", "at": "start"}), point), + ("text.touchType", json!({"id": id.0, "start": 1.5, "dy": 2}), whole.clone()), + ("text.touchType", json!({"id": id.0, "start": -1, "dy": 2}), whole.clone()), + ("text.glyphAlternates", json!({"id": id.0, "start": 1.5}), whole.clone()), + ("text.setGlyphAlternate", json!({"id": id.0, "start": -1, "gid": null}), whole), + ] + .into_iter() + .map(|(cmd, p, msg)| (cmd.to_string(), p, msg)) + .collect(); + let wrong = not_refused(&mut s, &calls); + assert!(wrong.is_empty(), "not refused: {wrong:#?}"); + // Null keeps each default: nothing inserted, area type with no text, no start point. + s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 1, "insert": null})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "bc"); + let r = s.execute("text.createInPath", &json!({"path": frame, "mode": null, "text": null, "at": null})).unwrap(); + let t = obj(&s, NodeId(r["id"].as_u64().unwrap())); + assert!(matches!(t.kind, TextKind::Area { .. }) && t.plain_text().is_empty(), "{:?}", t.kind); + s.execute("text.createInPath", &json!({"path": line, "mode": "onPath", "text": "a", "at": [100, 400]})).unwrap(); +} + /// Where each glyph of type object `id` is drawn from (its origin in font units), document space. fn glyph_pens(s: &Session, id: NodeId) -> Vec<(usize, Point)> { let t = obj(s, id); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..6848635a23 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2430,11 +2430,15 @@ with `` `font` must be a string ``, and a `features` list with an entry that is `text.setStyle` and `text.setRangeStyle` refuse a `size` outside 0.1 to 1,296 pt with `` `size` must be from 0.1 to 1296 `` and change nothing. `type.ruby` refuses a `text`, `position` or `align` that is not a string, and `text.setPathHandle` refuses a `which` other than `in` or `out` with -`` `which` must be one of in, out ``. Each leaves the document, the selection and the undo history as they were, also -when the call gives another param it could apply. A null is read as a key left out. +`` `which` must be one of in, out ``. `text.editRange` refuses an `insert` that is not a string, `text.setText` a `text` +that is not a string, and `text.createInPath` a `mode` or `text` that is not a string, each with +`` `insert` must be a string ``, naming the key; `text.createInPath` refuses an `at` that is not two numbers with +`` `at` must be a point: [x, y] ``, in area mode too. Each leaves the document, the selection and the undo history as +they were, also when the call gives another param it could apply. A null is read as a key left out. A byte offset must be a whole number of at least 0. `at` in `text.startList`, and `start` and `end` in -`text.editRange`, `text.getRange` and `text.setRangeStyle`, and in `type.step` and `addon.type.textTweaker` given an `id`, +`text.editRange`, `text.getRange` and `text.setRangeStyle`, `start` in `text.touchType`, `text.glyphAlternates` and +`text.setGlyphAlternate`, and `start` and `end` in `type.step` and `addon.type.textTweaker` given an `id`, refuse a negative or fractional number with `` `at` must be a whole number ``, naming the key, and change nothing. `2.0` is read as `2`, and a null as the key left out. @@ -6207,7 +6211,8 @@ editing the pattern first". While a mask is edited, `object.pattern.edit` and `o Pathfinder Options: `object.pathfinder.options {precision?, removeRedundantPoints?, removeUnpainted?}` (or `prefs.get`/`prefs.set` with key `pathfinder`) reads and sets the options every later Shape Mode and Pathfinder -operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit also reads) is how closely results follow +operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit or a string that is all one number also reads, and +any other string, such as `"1abc"`, is an error) is how closely results follow the paths (they are refit to within it and pieces thinner than it are dropped), `removeRedundantPoints` takes the anchors that don't change a result's shape off it, and `removeUnpainted` makes Divide and Outline leave out the pieces of objects with no fill (or only hidden fills). Both default to false; `{}` reads the options. Each Shape Mode and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..c4508481b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -946,6 +946,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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`. +- **Text command parameter errors:** `text.editRange`'s `insert`, `text.setText`'s `text` and `text.createInPath`'s `mode` and `text` must be strings, `text.createInPath`'s `at` must be two numbers, and `start` in `text.touchType`, `text.glyphAlternates` and `text.setGlyphAlternate` must be a whole number of at least 0. A wrong value is an error naming the parameter, and the document and undo history do not change; null is read as the parameter left out. Pathfinder `precision` takes a number, a string that is all one number or a length with a unit, and refuses a string such as `"1abc"`. This is VectorCraft's own rule; no score changes. Tests: `tests::textedit::text_edits_refuse_a_param_of_the_wrong_type` and `tests::pathops::pathfinder_options_round_trip_and_refuse_bad_values` in `vectorcraft-engine`. - **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.