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 c33b3cd47f..456d9d88b1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -502,17 +502,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(()); } @@ -547,7 +547,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]})) @@ -557,11 +557,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, @@ -795,8 +806,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)); } @@ -1424,7 +1435,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)?; @@ -1467,8 +1480,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) } @@ -1862,3 +1881,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()))); + } +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index fc2cd6ce67..774ff2b165 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); } @@ -115,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(); @@ -848,6 +872,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/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); diff --git a/docs/mcp.md b/docs/mcp.md index 6c5e64789d..7d1ff6defe 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,