diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 28c98af3fc..f16cb3ada2 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -254,20 +254,30 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. // A document whose active artboard the run set with `setActiveArtboardIndex` plays on that - // artboard, and the Artboard tool's selection as the run started no longer holds for it. - let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !h.dom.active_artboards.borrow().contains(uid)); - let active: Vec<(u64, usize)> = { + // artboard, and the Artboard tool's selection as the run started no longer holds for it. One + // where `artboards.add` or `artboards.insert` moved the active artboard to another index plays + // on that artboard at its new index. The Artboard tool's selection is the artboards it held, + // at the indices they have now. + let (active, picks): (Vec<(u64, usize)>, Option<(u64, Vec)>) = { let moved = h.dom.active_artboards.borrow(); + let shifted = h.dom.boards_shifted.borrow(); let session = h.session.borrow(); - h.active_artboards + let doc = |uid: u64| session.documents().iter().find(|d| d.uid == uid); + let active = h + .active_artboards .iter() - .map(|&(uid, i)| match session.documents().iter().find(|d| d.uid == uid) { - Some(st) if moved.contains(&uid) => (uid, super::dom::active_artboard(st)), + .map(|&(uid, i)| match doc(uid) { + Some(st) if moved.contains(&uid) || shifted.contains(&uid) => (uid, super::dom::active_artboard(st)), _ => (uid, i), }) - .collect() + .collect(); + let picks = h.artboard_picks.as_ref().filter(|(uid, _)| !moved.contains(uid)).map(|(uid, ids)| { + let at = doc(*uid).map(|st| ids.iter().filter_map(|id| st.doc.artboards.iter().position(|ab| ab.id == *id)).collect()); + (*uid, at.unwrap_or_default()) + }); + (active, picks) }; - let start = Start { active: &active, picks, batch: s.artboard }; + let start = Start { active: &active, picks: picks.as_ref(), batch: s.artboard }; let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1b79fa783d..402e7c5a3f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -224,6 +224,9 @@ pub(super) struct State { layers: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, + /// The uids of the documents where `artboards.add` or `artboards.insert` gave the active + /// artboard another index. + pub(super) boards_shifted: RefCell>, /// Each open document's uid and the index of its active artboard when the run started, and for /// a document the run opened, the index before the run first added an artboard to it. pub(super) boards_at_start: RefCell>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index e27f59fd65..04debab36a 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -32,6 +32,8 @@ //! active artboard has another index at the end of the run, because artboards were inserted, //! removed or reordered before it. +use std::cell::OnceCell; +use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; @@ -65,6 +67,8 @@ enum Kind { Group, /// Compound paths (`CompoundPathItem`). Compound, + /// Paths (`PathItem`): the `pathItems` of a compound path. + Path, } impl Kind { @@ -73,6 +77,7 @@ impl Kind { Kind::Any => "PageItems", Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", + Kind::Path => "PathItems", } } @@ -81,6 +86,7 @@ impl Kind { Kind::Any => typename(n).is_some(), Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), + Kind::Path => typename(n) == Some("PathItem"), } } } @@ -227,7 +233,8 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) + // Only the exact number the getter reports counts as the same opacity, as for a page item. + set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4 == v, json!({"opacity": v})) } fn layer_color(h: &Host, a: &[Data]) -> Answer { @@ -273,13 +280,19 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer { } /// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is -/// not counted. +/// not counted. The list of the layers beside it and each one's place in it are kept as +/// [`layers_listed`] keeps the list, so a loop over the layers reads them once. fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let list = layer_list(&st.doc, st.doc.parent_of(id)); - list.iter().position(|l| *l == id).map(|i| list.len() - i) - }); + let (list, places) = layers_kept(h, st, st.doc.parent_of(id))?; + let places = places.get_or_init(|| { + #[cfg(test)] + super::LAYER_SCANS.with(|c| c.set(c.get() + list.len() as u64)); + list.iter().enumerate().map(|(i, l)| (*l, i)).collect() + }); + Ok::<_, HostError>(places.get(&id).map(|i| list.len() - i)) + })?; at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) } @@ -479,21 +492,28 @@ fn layer_list(d: &Document, parent: Option) -> Vec { } /// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top -/// level) and the layers it listed then. -pub(super) type LayerList = (u64, Arc, Option, Rc>); +/// level), the layers it listed then and, once a layer's place was asked for, each layer's index in +/// that list. +pub(super) type LayerList = (u64, Arc, Option, Rc>, Rc>>); /// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while /// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list /// is charged by the objects it looks at. fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result>> { + layers_kept(h, st, parent).map(|(ids, _)| ids) +} + +/// The list [`layers_listed`] gives, with the index of each layer in it, which is built the first +/// time it is asked for. +fn layers_kept(h: &Host, st: &DocState, parent: Option) -> Result<(Rc>, Rc>>)> { { let mut lists = h.dom.layers.borrow_mut(); - let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent); + let at = lists.iter().position(|(uid, doc, p, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent); if let Some(at) = at { let list = lists.remove(at); - let ids = list.3.clone(); + let kept = (list.3.clone(), list.4.clone()); lists.push(list); - return Ok(ids); + return Ok(kept); } } let looked_at = match parent { @@ -507,8 +527,9 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result= ART_LISTS { lists.remove(0); } - lists.push((st.uid, st.doc.clone(), parent, ids.clone())); - Ok(ids) + let places = Rc::new(OnceCell::new()); + lists.push((st.uid, st.doc.clone(), parent, ids.clone(), places.clone())); + Ok((ids, places)) } fn layers_of(h: &Host, a: &[Data]) -> Answer { @@ -781,12 +802,17 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + // A compound path whose members are cleared stays, empty, as it does after `remove()` of its last + // path. + let in_compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); if !ids.is_empty() { on_doc(h, doc.uid, true, |h| { for p in &masked { command(h, "layer.clippingMask.toggle", &json!({"id": p.0}))?; } - command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})) + let ids: Vec = ids.iter().map(|i| i.0).collect(); + let params = if in_compound { json!({"ids": ids, "keepEmpty": true}) } else { json!({"ids": ids}) }; + command(h, "edit.clear", ¶ms) })?; } Ok(Data::Undefined) @@ -852,10 +878,42 @@ fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { } fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { - let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - // A compound path's `pathItems` are its `PageItems`: it holds only paths. - let compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); - Ok(text(if compound && kind == Kind::Any { "PathItems" } else { kind.class() })) + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) +} + +/// The `PathItems` of a compound path: a `PathItems` object whose handle names the compound path. +/// `PathItems`' members hand over to the functions below when their handle names one +/// ([`is_scoped_paths`]). +fn compound_path_items(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "CompoundPathItem")?; + Ok(collection(h, Kind::Path, Some(item.id), item.doc.uid)) +} + +pub(super) fn is_scoped_paths(a: &[Data]) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PathItems" && handle.len() == 5) +} + +pub(super) fn paths_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Path) +} +pub(super) fn paths_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Path) +} +pub(super) fn paths_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Path) +} +pub(super) fn paths_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Path) +} +pub(super) fn paths_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Path) +} +pub(super) fn paths_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Path) +} +pub(super) fn paths_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Path) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { @@ -943,11 +1001,19 @@ fn group_clipped(h: &Host, a: &[Data]) -> Answer { } /// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the -/// clipping mask. The group keeps its id either way. +/// clipping mask. The group keeps its id either way. The path that becomes or stops being the +/// clipping path (the topmost object, or the bottom one while the group clips) must be shown and +/// unlocked, as the group must. fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "clipped")?; let item = this_item_of(h, a, "GroupItem")?; - let (now, ok) = with_doc(h, item.doc, |_, st| (st.doc.node(item.id).is_some_and(crate::doc::Node::clips), editable(&st.doc, item.id))); + let (now, ok, mask) = with_doc(h, item.doc, |_, st| { + let n = st.doc.node(item.id); + let now = n.is_some_and(crate::doc::Node::clips); + let children = n.and_then(|n| n.children()).map_or(&[][..], Vec::as_slice); + let mask = if now { children.first() } else { children.iter().rev().find(|c| !c.is_ruler_guide()) }; + (now, editable(&st.doc, item.id), mask.map(|m| (m.id, editable(&st.doc, m.id)))) + }); if now == on { return Ok(Data::Undefined); } @@ -955,6 +1021,12 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer { if !ok { return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); } + if let Some((mask, mask_ok)) = mask { + super::refuse_protected_edit(h, Item { doc: item.doc, id: mask })?; + if !mask_ok { + return Err(HostError::Error(format!("Cannot change GroupItem {}: its clipping path {} is hidden or locked", item.id.0, mask.0))); + } + } on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; Ok(Data::Undefined) } @@ -977,7 +1049,7 @@ pub(super) fn members(class: &str, l: &Link) -> Vec { m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } - "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items), collection_of("PathItems"))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, compound_path_items), collection_of("PathItems"))]), _ => Vec::new(), } } @@ -1333,6 +1405,14 @@ fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) }) })?; + // The active artboard keeps its id; an artboard inserted before it gives it the next index, which + // the steps `app.doScript` plays then act on. + if with_doc(h, doc, |_, st| active_artboard(st)) != active { + let mut shifted = h.dom.boards_shifted.borrow_mut(); + if !shifted.contains(&doc.uid) { + shifted.push(doc.uid); + } + } Ok(board_ref(h, doc.uid, id)) } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 03ec3812a6..8f6929e35c 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -395,27 +395,50 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) } +/// The document of a document's `PathItems`. The `PathItems` of a compound path are read through +/// [`super::layers`], and they make no paths: each method that would make one throws. fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { + if super::layers::is_scoped_paths(a) { + return Err(HostError::Error("a compound path's pathItems cannot make paths".into())); + } doc_of(h, arg(a, 0), "PathItems") } /// `typename` of the paths of a document that is still open. fn items_typename(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_typename(h, a); + } items_doc(h, a)?; Ok(Data::String("PathItems".into())) } +/// `toString()`: `[PathItems]`, a document's or a compound path's. +fn items_to_string(h: &super::Host, a: &[Data]) -> Answer { + items_typename(h, a)?; + Ok(Data::String("[PathItems]".into())) +} + fn items_length(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_length(h, a); + } let doc = items_doc(h, a)?; Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_parent(h, a); + } let doc = items_doc(h, a)?; Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } fn items_at(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_at(h, a); + } let doc = items_doc(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; @@ -423,6 +446,9 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_by_name(h, a); + } let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { @@ -434,6 +460,9 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { } fn items_index(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(_) => match items_at(h, a)? { @@ -448,6 +477,9 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before /// anything is deleted, as `PageItems.removeAll()` does. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped_paths(a) { + return super::layers::paths_remove_all(h, a); + } let doc = items_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st)?; @@ -1903,6 +1935,7 @@ pub(super) fn classes(l: &Link) -> Vec { None, named(vec![ ("typename", get(l, items_typename), typed("string")), + ("toString", method(l, items_to_string), returns("string", &[])), ("length", get(l, items_length), typed("number")), ("parent", get(l, items_parent), typed("Document")), ("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 361a7e0e00..bbd00ecebe 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -827,9 +827,10 @@ struct Host { /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. active_artboards: Vec<(u64, usize)>, /// The artboards the Artboard tool had selected in the active document as the run starts (two or - /// more), with that document's uid. The run gives the tool fresh state, which drops them, so the - /// steps `app.doScript` plays read them here. - artboard_picks: Option<(u64, Vec)>, + /// more), by artboard id, with that document's uid. The run gives the tool fresh state, which + /// drops them, so the steps `app.doScript` plays read them here, at the indices those artboards + /// have when each step runs. + artboard_picks: Option<(u64, Vec)>, /// The documents open when the run began as the person last left them, each with its own file /// and the file it was read from ([`crate::DocState::as_person_left`], /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files @@ -2235,7 +2236,10 @@ impl Session { } // The Artboard tool's selection, which the fresh tool state below drops. let picks = cmd::artboard_tool_picks(self); - let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks)); + let artboard_picks = self + .active() + .filter(|_| !picks.is_empty()) + .map(|d| (d.uid, picks.iter().filter_map(|i| d.doc.artboards.get(*i).map(|ab| ab.id)).collect())); self.reset_tool(); let open: Vec = self.docs.iter().map(|d| d.uid).collect(); self.script_high_water.retain(|uid, _| open.contains(uid)); diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 396abbab4c..32dfb781b8 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -413,3 +413,46 @@ fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { s.execute("artboard.delete", &json!({"index": 2})).unwrap(); assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); } + +/// After the script inserts an artboard before the active one, a step that names no artboard acts +/// on the artboard that was active, at its new index, not on the artboard now at the old index. +#[test] +fn steps_follow_the_active_artboard_past_an_inserted_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&s); + make_active(&mut s, 1); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + log_with(&mut s, "app.activeDocument.artboards.insert([2000, 300, 2100, 200], 0); app.doScript('Fit', 'Set');", &actions); + let after = boards(&s); + assert_eq!(after.len(), 4); + assert_eq!(after[1], was[0], "the artboard now at the old index is left as it was"); + assert_ne!(after[2], was[1], "the artboard that was active fits the selection"); + assert_eq!(after[3], was[2]); +} + +/// The Artboard tool's selection as the run started stays on the same artboards after the script +/// inserts one before them: a Fit to Artwork Bounds step fits those artboards at their new indices. +#[test] +fn the_artboard_tools_selection_follows_its_artboards_past_an_inserted_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + make_active(&mut s, 1); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToArt"})])]); + log_with(&mut s, "app.activeDocument.artboards.insert([2000, 300, 2100, 200], 0); app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards[1..], [art[0], was[1], art[2]], "the selected artboards fit their art"); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 40b9b31513..5c9488874b 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1936,11 +1936,12 @@ fn wrappers_go_stale_after_revert() { assert_eq!(log(&mut s, &source), vec![json!(stale), json!(2)], "{operation}"); } // An artboard read before the revert is stale too, although the loaded document has a board with its id. - let source = "var b = app.activeDocument.artboards[0]; b.name = 'changed'; vc.run('file.revert');\ - try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(app.activeDocument.artboards[0].name);"; + let source = "var b = app.activeDocument.artboards[0], saved = b.name; b.name = 'changed'; vc.run('file.revert');\ + try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(app.activeDocument.artboards[0].name); vc.log(saved);"; let out = log(&mut s, source); assert_eq!(out[0], json!("Stale artboard"), "{out:?}"); - assert_ne!(out[1], json!("wrong"), "{out:?}"); + assert_ne!(out[2], json!("changed"), "{out:?}"); + assert_eq!(out[1], out[2], "the revert gives the artboard the saved name: {out:?}"); } #[test] @@ -2011,12 +2012,54 @@ fn clipped_refuses_a_group_on_a_locked_artboard() { .unwrap(); let steps = undo_steps(&s); run(&mut s, "app.activeDocument.groupItems[0].clipped = false;").unwrap(); - let e = failure(&mut s, "app.activeDocument.groupItems[0].clipped = true;"); - assert!(e.contains("locked artboard"), "{e}"); + // The script reads `clipped` after the error, before the run's rollback could put a change back. + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; try { g.clipped = true; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(g.clipped);", + ); + assert!(out[0].as_str().unwrap().contains("locked artboard"), "{out:?}"); + assert_eq!(out[1], json!(false), "{out:?}"); assert!(!s.active().unwrap().doc.node(gid).unwrap().clips()); assert_eq!(undo_steps(&s), steps); } +/// `clipped` on a shown, unlocked group throws and changes nothing when the path that would become +/// the clipping path, or the clipping path it would release, is locked. +#[test] +fn clipped_refuses_a_locked_clipping_path() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 0.0, 0.0, 5.0, 5.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let top = s.active().unwrap().doc.node(gid).unwrap().children().unwrap().last().unwrap().id; + let set = |s: &mut Session, on: bool| { + let source = format!( + "var g = app.activeDocument.groupItems[0]; try {{ g.clipped = {on}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }} vc.log(g.clipped);" + ); + log(s, &source) + }; + s.execute("object.setProps", &json!({"ids": [top.0], "locked": true})).unwrap(); + let paint = format!("{:?}", s.active().unwrap().doc.node(top).unwrap()); + let steps = undo_steps(&s); + let out = set(&mut s, true); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "{out:?}"); + assert_eq!(out[1], json!(false), "{out:?}"); + let now = s.active().unwrap().doc.node(gid).unwrap(); + assert!(!now.clips()); + assert_eq!(now.children().unwrap().last().unwrap().id, top, "the locked path stays on top"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.node(top).unwrap()), paint, "the locked path keeps its paint"); + assert_eq!(undo_steps(&s), steps); + // Releasing a clipping mask whose clipping path is locked is refused too. + s.execute("object.setProps", &json!({"ids": [top.0], "locked": false})).unwrap(); + assert_eq!(set(&mut s, true), [json!("ran"), json!(true)]); + let mask = s.active().unwrap().doc.node(gid).unwrap().children().unwrap()[0].id; + s.execute("object.setProps", &json!({"ids": [mask.0], "locked": true})).unwrap(); + let out = set(&mut s, false); + assert!(out[0].as_str().unwrap().contains("hidden or locked"), "{out:?}"); + assert_eq!(out[1], json!(true), "{out:?}"); +} + /// A loop over `layers.length` and `layers[i]` lists the layers once while the document is /// unchanged, so it looks at each layer a bounded number of times. #[test] @@ -2034,6 +2077,41 @@ fn a_loop_over_layers_lists_them_once() { assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); } +/// A loop that reads each layer's `zOrderPosition` lists the layers and their places once while the +/// document is unchanged. +#[test] +fn a_loop_over_layers_z_order_positions_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log( + &mut s, + "var L = app.activeDocument.layers, z = []; for (var i = 0; i < L.length; i++) z.push(L[i].zOrderPosition); vc.log(z[0]); vc.log(z[z.length - 1]);", + ); + assert_eq!(out, vec![json!(n), json!(1)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 3 * n, "{scans} nodes looked at for {n} layers"); +} + +/// Assigning a layer an opacity its getter would read back as another number runs the command, +/// though it is within 0.0001 of the opacity the layer has; the number the getter reports is a no-op. +#[test] +fn a_layers_opacity_is_set_unless_the_getter_already_reports_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "app.activeDocument.layers[0].opacity = 0;"); + let steps = undo_steps(&s); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = l.opacity; vc.log(l.opacity);"); + assert_eq!(out, [json!(0)]); + assert_eq!(undo_steps(&s), steps, "the opacity the getter reports runs no command"); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = 0.00009; vc.log(l.opacity);"); + assert_eq!(out, [json!(0.0001)]); +} + /// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. #[test] fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { @@ -2633,6 +2711,42 @@ fn a_compound_paths_path_items_are_path_items() { assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); } +/// A compound path's `pathItems` is a `PathItems` object that lists the compound path's own paths: +/// it reads them, its `parent` is the compound path, and each method that would make a path throws +/// and makes none. +#[test] +fn a_compound_paths_path_items_list_its_paths_and_make_none() { + let (mut s, a, b) = doc(); + rect(&mut s, 200.0, 20.0, 10.0, 10.0); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "inner"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems[0], p = c.pathItems, n = d.pathItems.length;\ + vc.log(p.parent === c); vc.log(p.getByName('inner').name);\ + try { p.rectangle(10, 10, 5, 5); vc.log('made'); } catch (e) { vc.log(e.message); }\ + try { p.add(); vc.log('made'); } catch (e) { vc.log(e.message); }\ + vc.log(p.length); vc.log(d.pathItems.length === n);", + ); + let refused = json!("a compound path's pathItems cannot make paths"); + assert_eq!(out, [json!(true), json!("inner"), refused.clone(), refused, json!(2), json!(true)]); +} + +/// `compound.pathItems.removeAll()` deletes the compound path's paths and keeps the compound path, +/// empty, as `remove()` of its last path does. +#[test] +fn removing_all_of_a_compound_paths_paths_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let out = + log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length); vc.log(c.typename);"); + assert_eq!(out, [json!(0), json!("CompoundPathItem")]); + assert!(s.active().unwrap().doc.node(NodeId(c)).is_some()); + assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none()); +} + #[test] fn a_layers_and_a_compound_paths_items_answer_index_and_to_string() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f806a607d1..d0fa17f497 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -183,7 +183,10 @@ const INSIDE: &[(&str, &str)] = &[ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("PathItems.", "prototype"), - ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"), + ( + "PathItems.prototype.", + "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename", + ), ("PathItem.", "prototype"), ( "PathItem.prototype.", diff --git a/docs/mcp.md b/docs/mcp.md index 391081ce60..f4795cc55f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3158,7 +3158,9 @@ through `$`: `compoundPathItems` and a layer's or group's `pageItems` list art topmost first, as the document's `pageItems` does. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any depth, and a layer's or group's hold only the ones directly in it. A layer's `pageItems` leave out its sublayers, and a compound path's `pathItems` - list its paths, with the typename `PathItems`. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole + are a `PathItems` object that lists its paths: `length`, `[i]`, `index(key)`, `getByName(name)`, `parent` (the + compound path), `toString()` and `removeAll()`, which keeps the compound path, empty. Its methods that make a path + throw an error. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past the next layer beside it and any art between them. @@ -3166,7 +3168,8 @@ through `$`: deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer with nothing to add or deselect runs no command. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping - path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the + path; `false` releases the mask; the group keeps its id. A hidden or locked object that would become the clipping + path, or a hidden or locked clipping path that `false` would release, throws. `groupItems.add()` makes an empty group on top of the layer's or group's contents, or of the current layer's for the document's collection. `compoundPathItems.add()` throws, since a compound path holds at least one path. `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is @@ -3626,8 +3629,10 @@ through `$`: Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one - past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to - Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + past the end. After `artboards.add` or `insert` gives the active artboard another index, such a step acts on that + artboard at its new index. While the Artboard tool has several artboards selected as the run starts, a paste step + and a Fit to Artwork Bounds step act on those artboards, at the indices they have when the step runs, as in the + panel's playback. A step of a recorded `command.batch` step that names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's own rules: the action and its set are matched by their exact names, and a name that matches no action or more than one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have