From 4b97cc84926ee4dd9c807dcc1e2181017452d16c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:18:44 -0800 Subject: [PATCH 1/5] Scripts: a failed selection restore ends the run unless the command refused When an edit puts the selection back, the Layers panel target, symbol part, Objects on Path member, ruler guide and key object commands fall back or skip only when the command refuses with an ordinary error. An internal failure or a request to stop now ends the run instead of being treated as a refusal. --- crates/engine/src/script/dom.rs | 35 ++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b986dfcf2d..9d4acfa798 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -459,17 +459,17 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - // inside the isolated group, or a symbol's object is now hidden) changes nothing, and the // objects are selected as below. if let Some(t) = before.target.filter(keep) - && command(h, "layer.target", &json!({"id": t.0})).is_ok() + && done_unless_refused(command(h, "layer.target", &json!({"id": t.0})))? { return Ok(()); } if let Some(p) = before.symbol_part.as_ref().filter(|p| keep(&p.instance)) - && command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})).is_ok() + && done_unless_refused(command(h, "symbol.instance.selectPart", &json!({"id": p.instance.0, "path": p.path})))? { return Ok(()); } if let Some(m) = before.on_path_member.filter(keep) - && command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})).is_ok() + && done_unless_refused(command(h, "object.objectsOnPath.selectMember", &json!({"member": m.0})))? { return Ok(()); } @@ -504,7 +504,7 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - // Guides that are locked now, and a key that no longer qualifies (the objects beside it are // gone), stay unselected: those commands refuse them and change nothing. if !picked.is_empty() { - let _ = command(h, "guide.select", &json!({"indexes": picked, "toggle": true})); + done_unless_refused(command(h, "guide.select", &json!({"indexes": picked, "toggle": true})))?; } let key = if let Some((id, (p, k))) = before.key_anchor.filter(|(id, _)| keep(id)) { Some(json!({"id": id.0, "anchor": [p, k]})) @@ -514,11 +514,22 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - before.key_guide.as_ref().and_then(index).map(|g| json!({"guide": g})) }; if let Some(key) = key { - let _ = command(h, "select.key", &key); + done_unless_refused(command(h, "select.key", &key))?; } Ok(()) } +/// The result `r` of a selection command that [`restore_selection`] runs: `true` when it ran and +/// `false` when it refused (an `Error`, which changes nothing). Any other error, such as an +/// internal failure or a request to stop, is returned, so the run ends with it. +fn done_unless_refused(r: std::result::Result) -> std::result::Result { + match r { + Ok(_) => Ok(true), + Err(HostError::Error(_)) => Ok(false), + Err(e) => Err(e), + } +} + /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, @@ -1813,3 +1824,17 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn restoring_the_selection_falls_back_only_on_a_refusal() { + assert_eq!(done_unless_refused(Ok(Data::Undefined)), Ok(true)); + assert_eq!(done_unless_refused(Err(HostError::Error("refused".into()))), Ok(false)); + // An internal failure or a stop ends the run instead of being taken for a refusal. + assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); + assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); + } +} From 4bc1f7a187439606160a91b03be7add43a1cd4a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:40:55 -0800 Subject: [PATCH 2/5] Scripts: Documents.add takes the artboard spacing file.new takes artboardSpacing is refused above 100,000 points, the limit file.new applies, so a value file.new would refuse throws a RangeError that names artboardSpacing. --- crates/engine/src/cmd/newdoc.rs | 2 +- crates/engine/src/script/dom.rs | 4 ++-- crates/engine/src/tests/script_dom.rs | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index a242b1fd20..983ef4041d 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -561,7 +561,7 @@ pub(crate) fn side_error(cmd: &str, units: Unit) -> crate::EngineError { bad(cmd, format!("width and height must be more than 0 and at most {limit}")) } /// Largest artboard spacing, points. -const MAX_SPACING: f64 = 1.0e5; +pub(crate) const MAX_SPACING: f64 = 1.0e5; pub fn color_mode_id(m: ColorMode) -> &'static str { match m { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9d4acfa798..55073e70ec 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -763,8 +763,8 @@ impl NewDoc<'_> { } if let Some(d) = self.spacing { let v = number(d, "artboardSpacing")?; - if !(0.0..=MAX_SIZE).contains(&v) { - return Err(HostError::Range("artboardSpacing must be from 0 to 3999856 points".into())); + if !(0.0..=crate::cmd::newdoc::MAX_SPACING).contains(&v) { + return Err(HostError::Range("artboardSpacing must be from 0 to 100000 points".into())); } layout.insert("spacing".into(), json!(v)); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 67bd373e2d..0324e81339 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -62,6 +62,9 @@ fn app_documents_track_active_tab_and_new_document() { assert!(failure(&mut s, "app.documents.add(DocumentColorSpace.RGB, -5);").contains("width")); assert!(failure(&mut s, "app.documents.add('RGB');").contains("colorSpace")); assert!(failure(&mut s, "app.documents.add(undefined, 10, 10, 101);").contains("numArtBoards")); + // The spacing is refused at file.new's limit, with the script's own name for it. + let spacing = "app.documents.add(undefined, 10, 10, 2, DocumentArtboardLayout.Row, 100001);"; + assert!(failure(&mut s, spacing).contains("artboardSpacing must be from 0 to 100000 points")); assert!(failure(&mut s, "app.documents.index('none');").contains("Not found")); assert_eq!(s.documents().len(), 3); } From a8d1b297664811f37ec5ab206824dea1ed77aeb2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:46:08 -0800 Subject: [PATCH 3/5] Tests: the script corpus failure test reads an undefined name Scripts now have an app object, so app.activeDocument no longer throws a ReferenceError. The test reads a name the host does not define instead. --- crates/engine/tests/script_corpus.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index 870bfbabc2..c2ca9a38f6 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -89,9 +89,9 @@ fn a_script_that_ends_well_passes() { fn a_failure_gives_its_kind_and_place() { let r = result(&mut session(), &source("var a = 1;\nvar = ;")); assert_eq!((r["ok"].clone(), r["kind"].clone(), r["line"].clone()), (json!(false), json!("syntax"), json!(2))); - let r = result(&mut session(), &source("var d = app.activeDocument;")); + let r = result(&mut session(), &source("var d = undefinedHost.activeDocument;")); assert_eq!(r["kind"], "thrown"); - assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: app"), "{r}"); + assert!(r["message"].as_str().unwrap().starts_with("ReferenceError: undefinedHost"), "{r}"); let r = result(&mut session(), &source("while (true) {}")); assert_eq!(r["kind"], "limit"); assert!(r["fuelUsed"].as_u64().unwrap() <= FUEL); From 76aee609f1458c53e0c32c8ae3f53d849469d24b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:21:32 -0800 Subject: [PATCH 4/5] Tests: page item width and height setters give the page-aligned size on rotated objects A rotated rectangle given a width and then a height through the scripting object model reads back the values set, its geometric bounds have that size, and other objects stay as they were. The resize doc comment names the page's axes. --- crates/engine/src/script/dom.rs | 4 +++- crates/engine/src/tests/script_dom.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 55073e70ec..fb72785a23 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1392,7 +1392,9 @@ fn item_set_top(h: &Host, a: &[Data]) -> Answer { move_to(h, a, None, Some(y)) } -/// Scales the item about its top-left corner to `size` points wide (`width`) or tall. +/// Scales the item about its top-left corner along the page's axes to `size` points wide (`width`) +/// or tall, so the page-aligned bounds that `width` and `height` read have that size, rotated +/// objects included. fn resize(h: &Host, a: &[Data], width: bool) -> Answer { let what = if width { "width" } else { "height" }; let size = number(arg(a, 1), what)?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0324e81339..3c5a2f4df0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -118,6 +118,27 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +#[test] +fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + let other = format!("{:?}", s.active().unwrap().doc.node(b)); + let out = log( + &mut s, + "var i = app.activeDocument.selection[0], h = i.height;\ + i.width = 80; vc.log([i.width, i.height - h]);\ + i.height = 90; vc.log([i.width, i.height]);\ + var g = i.geometricBounds; vc.log([g[2] - g[0], g[1] - g[3]]);", + ); + let pairs: Vec<[f64; 2]> = out.iter().map(|v| [v[0].as_f64().unwrap(), v[1].as_f64().unwrap()]).collect(); + for (got, want) in pairs.iter().zip([[80.0, 0.0], [80.0, 90.0], [80.0, 90.0]]) { + assert!((got[0] - want[0]).abs() < 1e-6 && (got[1] - want[1]).abs() < 1e-6, "{out:?}"); + } + assert_eq!(pairs.len(), 3, "{out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); +} + #[test] fn convert_coordinate_pair_is_inverse_and_y_up() { let mut s = Session::new(); From f33e0cb16d13ed6f2c934e1a63074b7fabf2c94c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:37:34 -0800 Subject: [PATCH 5/5] Scripts: PageItem.remove refuses hidden or locked art as removeAll does remove() on an object that is hidden or locked, sits in a hidden or locked layer or group, or is a group holding such an object now throws and deletes nothing, the same rule pageItems.removeAll() applies. docs/mcp.md states both rules and that width and height scale along the page's axes. --- crates/engine/src/script/dom.rs | 6 ++++++ crates/engine/src/tests/script_dom.rs | 25 +++++++++++++++++++++++++ docs/mcp.md | 6 +++++- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index fb72785a23..241720f786 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1437,8 +1437,14 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { at.map(|i| num(float(i as u64 + 1))).ok_or_else(|| HostError::Error(STALE_ITEM.into())) } +/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or +/// group, or a group holding one is refused, as [`items_remove_all`] refuses it. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; + let whole = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable)); + if !whole { + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); + } edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 3c5a2f4df0..795161ac1c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -870,6 +870,31 @@ fn remove_all_refuses_locked_art_before_deleting_anything() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + s.execute("object.setProps", &on).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); + assert!(e.contains(&format!("cannot delete hidden or locked objects: {}", b.0)), "{on}: {e}"); + assert!(s.active().unwrap().doc.node(b).is_some(), "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + // A group that holds a locked object is refused too. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(e.contains(&g.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(b).is_some()); + s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].remove();"); + assert!(s.active().unwrap().doc.node(b).is_none()); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index c305916f6f..9bc2be8efc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2665,7 +2665,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine - kept from an earlier run, throws `Stale page item`; `index` and `getByName` throw `Not found`; and + kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a + hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw + `cannot delete hidden or locked objects` and delete nothing. Setting `width` or `height` scales the object along + the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw + `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path,