diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 99ef61ef44..ac500697be 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -234,7 +234,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); a clipping group or layer left without art releases its mask in the same undo step; without ids, refused while an object of a symbol instance's art is selected", has_selection_or_guides, clear ), @@ -1312,6 +1312,20 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result { ok() } +pub(super) fn clipped_ancestors(d: &Document, ids: impl IntoIterator) -> BTreeSet { + ids.into_iter().flat_map(|id| d.ancestry(id).unwrap_or_default()).filter(|id| d.node(*id).is_some_and(Node::clips)).collect() +} + +pub(super) fn release_empty_clips(d: &mut Document, ids: BTreeSet) { + for id in ids { + if let Some(n) = d.node_mut(id) + && n.children().is_some_and(|c| c.iter().all(|n| n.is_ruler_guide())) + { + n.set_clips(false); + } + } +} + fn clear(s: &mut Session, p: &Value) -> Result { let guides = switch_or(p, "guides", false, "edit.clear")?; let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?; @@ -1348,6 +1362,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Clear", |d, sel| { + let clipped = clipped_ancestors(d, ids.iter().copied()); let parents: Vec<_> = if keep_empty { Vec::new() } else { @@ -1363,6 +1378,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { let gone = sel.guides.clone(); d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id))); } + release_empty_clips(d, clipped); if is_explicit { sel.remove_all(ids.iter().copied()); sel.prune(d); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 78febf0f18..469ff2721e 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -1001,9 +1001,32 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index); let d = &s.doc()?.doc; let n = d.node(id).ok_or(EngineError::NoNode(id))?; - if !accepts(d, parent, n) { + let compound = parent.and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + if let Some(c) = compound { + if !matches!(n.kind, NodeKind::Path { guide: false, .. }) { + return Err(bad(C, "a compound path holds only paths")); + } + // A clip group's or clipping layer's clipping path stays where it is: without it, the + // next object up would become the clipping path. + if d.position(id).is_some_and(|(from, i, _)| i == 0 && from.and_then(|f| d.node(f)).is_some_and(Node::clips)) { + return Err(bad(C, "a clipping path does not go into a compound path; release the clipping mask first")); + } + if !d.is_editable(c.id) { + return Err(bad(C, "the compound path is hidden or locked")); + } + } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } + // An empty compound path takes the paint of the first path that goes into it: the path's own, + // or the paint of the compound path it leaves, which is what painted it. + let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); + let shown = from_compound.map_or(&n.appearance, |p| &p.appearance); + let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone())); + let into = compound.map(|c| c.id); + let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned); + // A path that leaves a compound path for a layer or a group takes the compound path's paint and + // pixel alignment, as Release Compound Path gives them to its paths. + let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned)); if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } @@ -1013,6 +1036,36 @@ fn move_node(s: &mut Session, p: &Value) -> Result { let left = super::intertwine::groups_of(d, &[id]); s.edit(label, |d, sel| { d.move_node(id, parent, index)?; + if let Some((c, appearance)) = paint + && let Some(n) = d.node_mut(c) + { + n.appearance = appearance; + } + // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as + // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when + // the path was, or when the compound path it leaves was. + if let Some(c) = into { + let mut aligned = from_aligned; + if let Some(m) = d.node_mut(id) { + m.appearance = vectorcraft_doc::Appearance::default().into(); + aligned |= std::mem::take(&mut m.extras_mut().pixel_aligned); + if let NodeKind::Path { live, .. } = &mut m.kind { + *live = None; + } + } + if aligned && let Some(cn) = d.node_mut(c) { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } + } + if let Some((appearance, aligned)) = out_of + && let Some(m) = d.node_mut(id) + { + m.appearance = appearance; + if aligned { + m.extras_mut().pixel_aligned = true; + } + } super::intertwine::settle_members(d, &[(id, from)], &left)?; live_paint.finish(d, sel, &[id])?; sel.prune(d); diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index a0f292fecf..955520427c 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -105,6 +105,49 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result { Ok(json!({ "id": gid.0 })) } +/// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a +/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The +/// selection stays as it is. +pub(super) fn new_group(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.newGroup"; + // Only an omitted key takes its default; `null` is refused like any other bad value. + let compound = match p.get("compound") { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(C, "compound must be true or false"))?, + }; + let st = s.doc()?; + let parent = match p.get("parent") { + None => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?, + Some(v) => NodeId(v.as_u64().ok_or_else(|| bad(C, "parent must be a layer or group id"))?), + }; + let index = match p.get("index") { + None => usize::MAX, + Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(C, "index must be a whole number"))?, + }; + let d = &st.doc; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + let label = if compound { "Compound Path" } else { "Group" }; + let gid = s.edit(label, |d, _| { + let gid = d.alloc_id(); + let clips = d.node(parent).is_some_and(Node::clips); + let index = if clips { index.max(1) } else { index }; + let node = if compound { + Node::new(gid, NodeKind::Compound { children: Vec::new(), rule: vectorcraft_geom::FillRule::NonZero }) + } else { + Node::group(gid, Vec::new()) + }; + d.insert(Some(parent), index, node)?; + Ok(gid) + })?; + Ok(json!({ "id": gid.0 })) +} + /// Put `ids` (top-level objects, in paint order) in a new group where the front-most one was. pub(crate) fn group_nodes(d: &mut Document, ids: &[NodeId]) -> Result { if ids.is_empty() { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 3b949efd8b..bea69d1698 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -1,5 +1,5 @@ use super::align::{align, can_distribute, distribute, distribute_spacing}; -use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, send_to_current_layer, show_all, ungroup, unlock_all}; +use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, new_group, send_to_current_layer, show_all, ungroup, unlock_all}; use super::bounds::set_bounds; use super::compound::{clip_edit, clip_make, clip_release, compound_make, compound_release}; use super::pixelgrid::set_pixel_aligned; @@ -137,6 +137,15 @@ pub fn specs() -> Vec { has_selection, group ), + cmd!( + "object.newGroup", + "Group", + [], + None, + "{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is", + has_doc, + new_group + ), cmd!( "object.ungroup", "Ungroup", diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index a6f85d0c46..190c8b5810 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1921,6 +1921,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo .copied() .filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor))) .collect(); + let clipped = super::edit::clipped_ancestors(d, whole_ids.iter().chain(sel.keys()).chain(segments.keys()).copied()); // The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`. let compounds: BTreeSet = if keep_empty { BTreeSet::new() @@ -2002,6 +2003,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo d.remove(p)?; } } + super::edit::release_empty_clips(d, clipped); selection.set(survivors); for (id, next) in following { if !next.is_empty() { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 21433cf412..5f970bb568 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -346,6 +346,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.mesh.movePoints", "object.mesh.setPointColor", "object.move", + "object.newGroup", "object.nudge", "object.objectsOnPath.attach", "object.objectsOnPath.detach", diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 2abb290cf7..8728bd76fb 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -253,7 +253,17 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { h.charge_call(16 + s.id.len() as u64 + s.bytes)?; // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. - let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + // A document whose active artboard the script chose uses that choice, not the one the run + // started with. + let chosen = h.session.borrow().active().and_then(|st| { + h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?; + Some((st.uid, super::dom::active_artboard(st))) + }); + let active = match &chosen { + Some(chosen) => std::slice::from_ref(chosen), + None => h.active_artboards.as_slice(), + }; + let start = Start { active, picks: h.artboard_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 c9c2050d26..3549c5d2e4 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -18,7 +18,8 @@ //! //! Collections are counted from 0, and `pageItems` lists art topmost first, as //! reads the frontmost path as -//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName` +//! `pathItems[0]`; the `layers` module gives the order of a layer's, a group's and a compound +//! path's lists. A collection read with a name, `pageItems["name"]`, gives the object `getByName` //! gives, and a script may name the application's members without `app.`, as //! describes; here //! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active @@ -99,6 +100,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; mod clipboard; mod images; +pub(super) mod layers; mod matrix; pub mod preferences; mod print; @@ -182,6 +184,14 @@ pub(super) enum Coords { const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; +#[cfg(test)] +thread_local! { + /// How many nodes the layer lists of `Layers` objects have looked at on this thread. + pub(crate) static LAYER_SCANS: Cell = const { Cell::new(0) }; + /// How many lists of art the art collections have built on this thread. + pub(crate) static ART_SCANS: Cell = const { Cell::new(0) }; +} + /// What the object model keeps for one run: its coordinate system, the lists of page items and the /// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, /// each kept while its document is unchanged, the lists of paths, the point changes of a path not @@ -219,6 +229,21 @@ pub(super) struct State { editing: Cell>, locked: RefCell>, saving: Cell, + /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently + /// used first, each kept while its document is unchanged. + art: RefCell>, + /// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used + /// first, each kept while its document is unchanged. + layers: RefCell>, + /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. + pub(super) active_artboards: RefCell>, + /// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it. + pub(super) chosen_artboards: RefCell>, + /// Each open document's uid and the index of its active artboard when the run started. + pub(super) boards_at_start: Vec<(u64, usize)>, + /// Each document made during the run whose active artboard `setActiveArtboardIndex` chose, + /// with the index it chose the first time. + pub(super) boards_chosen_in_new: RefCell>, /// `app.userInteractionLevel` ([`save_open`]). save_options: save_open::State, /// The print option objects ([`print`]). @@ -236,9 +261,9 @@ pub(super) struct State { } impl State { - /// The state of a run whose heap is `heap_bytes`. - pub(super) fn new(heap_bytes: usize) -> Self { - Self { preset_limit: heap_bytes as u64, ..Self::default() } + /// The state of a run that starts with the documents `docs` open and whose heap is `heap_bytes`. + pub(super) fn new(docs: &[DocState], heap_bytes: usize) -> Self { + Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), preset_limit: heap_bytes as u64, ..Self::default() } } /// Whether a call's own savepoint is open: its commands take none of their own. @@ -445,7 +470,7 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document, page item, path point or text range `this` is still there. +/// the check that a document, layer, page item, path point or text range `this` is still there. /// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and /// `reflect` leaves it out. pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { @@ -458,7 +483,10 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" | "PathItem" | "TextFrame" | "PlacedItem" | "RasterItem" => { + "Layer" => { + layers::layer_of(&h, arg(&a, 0))?; + } + c if c == "PageItem" || ITEM_CLASSES.contains(&c) => { item_of(&h, arg(&a, 0))?; } "PathPoint" => { @@ -926,14 +954,27 @@ fn on_doc( keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - atomically(h, |h| on_doc_steps(h, uid, keep_selection, f)) + on_doc_layer(h, uid, keep_selection, true, f) } -/// The steps of [`on_doc`]. +/// [`on_doc`], with `keep_layer` false for `f`s that choose the current layer (`layers.add()`, +/// `activeLayer = layer`): the selection is put back, and the layer `f` left current stays current. +fn on_doc_layer( + h: &Host, + uid: u64, + keep_selection: bool, + keep_layer: bool, + f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + atomically(h, |h| on_doc_steps(h, uid, keep_selection, keep_layer, f)) +} + +/// The steps of [`on_doc_layer`]. fn on_doc_steps( h: &Host, uid: u64, keep_selection: bool, + keep_layer: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { let (index, active, before, layer, activated) = { @@ -947,6 +988,12 @@ fn on_doc_steps( command(h, "document.activate", &json!({"index": index}))?; } let r = f(h); + let layer = if keep_layer { + layer + } else { + let s = h.session.borrow(); + s.active().filter(|st| st.uid == uid).map_or(layer, |st| (st.active_layer, st.highlighted_rows())) + }; let mut restored = Ok(()); if keep_selection { let doc = { @@ -2169,22 +2216,35 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { } fn items_length(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_length(h, a); + } let doc = items_doc(h, a)?; let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?; Ok(num(float(n as u64))) } fn items_typename(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_typename(h, a); + } items_doc(h, a)?; Ok(text("PageItems")) } fn items_to_string(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + layers::scoped_typename(h, a)?; + return Ok(text("[PageItems]")); + } items_doc(h, a)?; Ok(text("[PageItems]")) } fn items_parent(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_parent(h, a); + } let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) } @@ -2204,6 +2264,9 @@ fn position(n: f64) -> Option { /// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is /// looked up as that name, giving `undefined` when no object has it. fn items_at(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_at(h, a); + } let doc = items_doc(h, a)?; match arg(a, 1) { Data::String(_) => match items_by_name(h, a) { @@ -2227,6 +2290,9 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer { } fn items_by_name(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_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())) }; items_named(h, doc, name) @@ -2243,6 +2309,9 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(n) => { @@ -2260,6 +2329,9 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { /// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, /// and so does an object on a locked artboard. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a, "PageItems") { + return layers::scoped_remove_all(h, a); + } let doc = items_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); @@ -2434,8 +2506,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer { set_props(h, a, |n| n.locked == locked, json!({"locked": locked})) } +/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four +/// decimals. +fn reported_opacity(opacity: f32) -> f64 { + (f64::from(opacity) * 100.0 * 1e4).round() / 1e4 +} + fn item_opacity(h: &Host, a: &[Data]) -> Answer { - read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4))) + read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity)))) } fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { @@ -2452,7 +2530,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { let (now, keeps_other) = with_doc(h, item.doc, |_, st| { let d = &st.doc; // Only the exact number the getter reports counts as the same opacity. - let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v); + let now = d.node(item.id).filter(|n| reported_opacity(n.opacity) == v).map(|n| f64::from(n.opacity) * 100.0); let keeps_other = crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); (now, keeps_other) @@ -2831,7 +2909,11 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s } let (parent, beside) = match how { Placement::Top | Placement::Bottom => { - if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { + if matches!(t.kind, NodeKind::Compound { .. }) { + if !d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })) { + return Err(HostError::Error("a compound path holds only paths".into())); + } + } else if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) { return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer")))); } (target, None) @@ -3089,19 +3171,6 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -fn layer_name(h: &Host, a: &[Data]) -> Answer { - let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) -} - -fn layer_typename(h: &Host, a: &[Data]) -> Answer { - layer_name(h, a)?; - Ok(text("Layer")) -} - /// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name. fn named_text(class: &str, name: Answer) -> Answer { match name? { @@ -3118,10 +3187,6 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer { named_text("Document", doc_name(h, a)) } -fn layer_to_string(h: &Host, a: &[Data]) -> Answer { - named_text("Layer", layer_name(h, a)) -} - /// `toString()` of an object without a name: `[Class]`. fn class_text(name: &'static str) -> HostMember { HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]"))))) @@ -3314,7 +3379,8 @@ fn classes(link: &Link) -> Vec { ]); document.extend(defaults::document_members(l)); document.extend(text::styles::doc_members(l)); - document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m))); + document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m))); + document.extend(layers::document_members(l)); document.extend(variables::document_members(l)); document.extend(save_open::document_members(l)); document.extend(print::document_members(l)); @@ -3353,7 +3419,7 @@ fn classes(link: &Link) -> Vec { named(vec![ ("typename", get(l, items_typename), typed("string")), ("length", get(l, items_length), typed("number")), - ("parent", get(l, items_parent), typed("Document")), + ("parent", get(l, items_parent), typed("*")), ("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])), ("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])), ("removeAll", method(l, items_remove_all), returns("undefined", &[])), @@ -3457,28 +3523,18 @@ fn classes(link: &Link) -> Vec { ), ), ]); + page_item.extend(layers::page_item_members(l)); page_item.extend( - [ - "artworkKnockout", - "isIsolated", - "layer", - "pixelAligned", - "sliced", - "uRL", - "uuid", - "wrapInside", - "wrapOffset", - "wrapped", - "bringInPerspective", - ] - .into_iter() - .map(|m| later(l, "PageItem", m)), + ["artworkKnockout", "isIsolated", "pixelAligned", "sliced", "uRL", "uuid", "wrapInside", "wrapOffset", "wrapped", "bringInPerspective"] + .into_iter() + .map(|m| later(l, "PageItem", m)), ); page_item.extend(variables::page_item_members(l)); classes.push(class("PageItem", None, page_item, None)); let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c); classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| { - let mut members = variables::item_members(l, c); + let mut members = layers::members(c, l); + members.extend(variables::item_members(l, c)); if *c == "PathItem" { members.extend(paths::path_item_members(l)); } @@ -3488,21 +3544,12 @@ fn classes(link: &Link) -> Vec { classes.extend(colors::classes(l)); classes.extend(text::classes(l)); classes.extend(variables::classes(l)); + classes.extend(layers::classes(l)); classes.extend(images::classes(l)); tracing::add_trace(&mut classes, l); classes.extend(tracing::classes(l)); classes.extend(save_open::classes(l)); classes.extend(print::classes(l)); - classes.push(class( - "Layer", - None, - named(vec![ - ("typename", get(l, layer_typename), typed("string")), - ("name", get(l, layer_name), typed("string")), - ("toString", method(l, layer_to_string), returns("string", &[])), - ]), - None, - )); classes.extend(tags::classes(l)); classes } diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index b9f0bb3a30..4de02e881b 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -39,7 +39,7 @@ const CLASSES: &[(&str, &[&str])] = &[ ("PatternColor", &[]), ]; -fn color_object(class: &str, values: &[(&str, f64)]) -> Data { +pub(super) fn color_object(class: &str, values: &[(&str, f64)]) -> Data { let mut items = vec![("typename".to_string(), text(class))]; items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v)))); Data::Object(items) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs new file mode 100644 index 0000000000..4328c1bad2 --- /dev/null +++ b/crates/engine/src/script/dom/layers.rs @@ -0,0 +1,1614 @@ +//! Layers, groups, compound paths and artboards in the script object model, as the help pages +//! , +//! , +//! , +//! , +//! , +//! and +//! describe them. +//! +//! A layer is named by its id and an artboard by its artboard id, so a handle keeps naming the same +//! one after others are added, moved or removed, and throws once it is gone. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's +//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the +//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! hold every group or compound path at any depth, in the order of the document's `pageItems`. +//! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes +//! a sublayer on top of that layer's contents. The new layer becomes the current one. +//! - `locked` true means the layer is locked. +//! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or +//! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it. +//! - A layer's `color` is an `RGBColor` object with values from 0 to 255. +//! - `CompoundPathItems.add()` makes an empty compound path. The first path a script moves into it +//! gives it its paint, as Make Compound Path takes the paint of a path it joins. +//! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a +//! document, the limit `Documents.add` uses. Two artboards may have the same name. +//! - A layer's or artboard's `name` takes a number or a boolean as `String()` writes it. +//! - `Artboard.rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down; with global +//! rulers, setting it moves the document's zero point. +//! - `setActiveArtboardIndex` changes the view's active artboard: no undo step, and the run's report +//! lists it in `activeArtboards` for the app to show. The report also lists a document whose +//! active artboard has another index at the end of the run, because artboards were inserted, +//! removed or reordered before it. + +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_parts}; + +use super::{ + Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard, + arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref, + later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity, + returns, text, typed, typename, whole, with_doc, +}; +use crate::script::{Host, Link}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error for a layer that was deleted, or that came from an earlier run. +pub const STALE_LAYER: &str = "Stale layer"; +/// The error for an artboard that was deleted, or that came from an earlier run. +pub const STALE_ARTBOARD: &str = "Stale artboard"; +/// The longest name a layer takes, in characters, as Layer Options keeps it. +pub const MAX_LAYER_NAME: usize = 512; + +type Result = std::result::Result; + +/// What a collection of art lists. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + /// Every page item. + Any, + /// Groups (`GroupItem`). + Group, + /// Compound paths (`CompoundPathItem`). + Compound, + /// Paths (`PathItem`). + Path, +} + +impl Kind { + fn class(self) -> &'static str { + match self { + Kind::Any => "PageItems", + Kind::Group => "GroupItems", + Kind::Compound => "CompoundPathItems", + Kind::Path => "PathItems", + } + } + + fn holds(self, n: &crate::doc::Node) -> bool { + match self { + Kind::Any => typename(n).is_some(), + Kind::Group => typename(n) == Some("GroupItem"), + Kind::Compound => typename(n) == Some("CompoundPathItem"), + Kind::Path => typename(n) == Some("PathItem"), + } + } +} + +fn type_error(what: &str) -> HostError { + HostError::Type(format!("this is not a {what}")) +} + +/// The whole number under `key` in a command's own result (not the script's copy, whose numbers +/// are exact only up to 2^53), such as the id of the object it made. +fn result_id(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_u64) +} + +// ---- Layer ---- + +/// The layer `d` names, which must still be a layer of its document. +pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> { + let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) }; + if handle.len() != 5 { + return Err(type_error("Layer")); + } + // A layer read before File › Revert is stale like the page items read with it. + let (doc, id) = node_of(h, &handle).ok_or_else(|| { + let reverted = matches!(handle.as_slice(), [run, uid, ..] if find_doc(h, *run, *uid).is_some()); + HostError::Error(if reverted { STALE_ITEM } else { STALE_LAYER }.into()) + })?; + let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer)); + if !ok { + return Err(HostError::Error(STALE_LAYER.into())); + } + Ok((doc, id)) +} + +fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> { + layer_of(h, arg(a, 0)) +} + +fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { + host_ref("Layer", &layer_handle(h, uid, id)) +} + +/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it. +fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] { + let [high, low] = id_parts(id); + [float(h.run), float(uid), high, low, float(reverts_of(h, uid))] +} + +/// Reads the layer `this` names with `f`. +fn read_layer(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer { + let (doc, id) = this_layer(h, a)?; + with_doc(h, doc, |_, st| match st.doc.node(id) { + Some(n) => f(st, n), + None => Err(HostError::Error(STALE_LAYER.into())), + }) +} + +/// Runs `id` with `params` and the layer's id on its document, unless `unchanged` says the layer +/// already has what they set. +fn set_layer(h: &Host, a: &[Data], command_id: &str, unchanged: impl FnOnce(&crate::doc::Node) -> bool, params: Value) -> Answer { + let (doc, id) = this_layer(h, a)?; + let same = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(unchanged)); + if !same { + let mut p = params; + if let Some(o) = p.as_object_mut() { + o.insert("ids".into(), json!([id.0])); + } + on_doc(h, doc.uid, true, |h| command(h, command_id, &p))?; + } + Ok(Data::Undefined) +} + +fn layer_flags(n: &crate::doc::Node) -> (bool, bool, Option, crate::doc::LayerColor) { + match &n.kind { + NodeKind::Layer { printable, preview, dim_images, color, .. } => (*printable, *preview, *dim_images, *color), + _ => (true, true, None, crate::doc::LayerColor::Preset(0)), + } +} + +fn layer_name(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(text(n.name.clone().unwrap_or_default()))) +} + +/// A name a script assigns: a string, or a number or boolean as `String()` writes it. +fn name_text(d: &Data) -> Result { + match d { + Data::String(s) => Ok(s.clone()), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + Data::Bool(b) => Ok(b.to_string()), + _ => Err(HostError::Type("name must be a string".into())), + } +} + +fn layer_set_name(h: &Host, a: &[Data]) -> Answer { + let name = name_text(arg(a, 1))?; + if name.trim().is_empty() { + return Err(HostError::Range("a layer's name cannot be empty".into())); + } + if name.chars().count() > MAX_LAYER_NAME { + return Err(HostError::Range(format!("a layer's name has at most {MAX_LAYER_NAME} characters"))); + } + let params = json!({"name": &name}); + set_layer(h, a, "layer.setProps", |n| n.name.as_deref() == Some(name.as_str()), params) +} + +fn layer_visible(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(n.visible))) +} + +fn layer_set_visible(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "visible")?; + set_layer(h, a, "layer.setProps", |n| n.visible == v, json!({"visible": v})) +} + +fn layer_locked(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(n.locked))) +} + +fn layer_set_locked(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "locked")?; + set_layer(h, a, "layer.setProps", |n| n.locked == v, json!({"locked": v})) +} + +fn layer_printable(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).0))) +} + +fn layer_set_printable(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "printable")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).0 == v, json!({"printable": v})) +} + +fn layer_preview(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).1))) +} + +fn layer_set_preview(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "preview")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).1 == v, json!({"preview": v})) +} + +fn layer_dim(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(Data::Bool(layer_flags(n).2.is_some()))) +} + +fn layer_set_dim(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "dimPlacedImages")?; + set_layer(h, a, "layer.setProps", |n| layer_flags(n).2.is_some() == v, json!({"dimImages": v})) +} + +fn layer_opacity(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| Ok(num(reported_opacity(n.opacity)))) +} + +fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "opacity")?; + 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| reported_opacity(n.opacity) == v, json!({"opacity": v})) +} + +fn layer_color(h: &Host, a: &[Data]) -> Answer { + read_layer(h, a, |_, n| { + let [r, g, b] = layer_flags(n).3.rgb(); + Ok(super::colors::color_object("RGBColor", &[("red", f64::from(r)), ("green", f64::from(g)), ("blue", f64::from(b))])) + }) +} + +/// `color = {red, green, blue}`: each a whole number from 0 to 255. +fn layer_set_color(h: &Host, a: &[Data]) -> Answer { + let Data::Object(o) = arg(a, 1) else { return Err(HostError::Type("color must be an object with red, green and blue".into())) }; + let mut rgb = [0u8; 3]; + for (slot, key) in rgb.iter_mut().zip(["red", "green", "blue"]) { + let v = o.iter().find(|(k, _)| k == key).map(|(_, v)| v).unwrap_or(&Data::Undefined); + let n = number(v, &format!("color.{key}"))?; + if n.fract() != 0.0 || !(0.0..=255.0).contains(&n) { + return Err(HostError::Range(format!("color.{key} must be a whole number from 0 to 255"))); + } + *slot = u8::try_from(whole(n).unwrap_or(0)).unwrap_or(0); + } + let hex = format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2]); + set_layer(h, a, "layer.setProps", |n| layer_flags(n).3.rgb() == rgb, json!({"color": hex})) +} + +fn layer_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(with_doc(h, doc, |_, st| match st.doc.parent_of(id) { + Some(p) => layer_ref(h, st.uid, p), + None => doc_ref(h, st.uid), + })) +} + +fn layer_typename(h: &Host, a: &[Data]) -> Answer { + this_layer(h, a)?; + Ok(text("Layer")) +} + +fn layer_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Layer", layer_name(h, a)) +} + +/// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is +/// not counted. +fn layer_z_position(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let at = with_doc(h, doc, |_, st| { + let parent = st.doc.parent_of(id); + let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len)); + h.charge_call(count as u64)?; + let list = layer_list(&st.doc, parent); + h.charge_call(list.len() as u64)?; + Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) + })?; + at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) +} + +fn layer_has_selected(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)))))) +} + +/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every +/// child visited, including skipped children. +fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec) -> u64 { + let mut count = 0; + for child in n.children().into_iter().flatten() { + count += 1; + if child.is_ruler_guide() || !child.visible || child.locked || child.is_template() { + continue; + } + if child.is_layer() { + count += collect_editable_art(child, out); + } else { + out.push(child.id); + } + } + count +} + +/// `hasSelectedArtwork = false` deselects the layer's art with `select.toggle`; `true` adds its +/// visible, unlocked art with `select.add`. The rest of the selection, ruler guides included, stays, +/// and no command runs when there is nothing to deselect or add. +fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "hasSelectedArtwork")?; + let (doc, id) = this_layer(h, a)?; + let (ids, over) = with_doc(h, doc, |_, st| { + let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id)); + let selected = &st.selection.objects; + h.charge_call(selected.len() as u64)?; + if !on { + return Ok::<_, HostError>((selected.iter().copied().filter(inside).collect::>(), false)); + } + let locks = st.doc.locked_artboards(); + let mut art = Vec::new(); + let count = st.doc.node(id).map_or(0, |n| collect_editable_art(n, &mut art)); + // The walk is charged by every node it looks at, hidden and locked ones included, whether + // or not anything is added. + h.charge_call(count)?; + let mut have: std::collections::HashSet = selected.iter().copied().collect(); + let mut ids = Vec::new(); + for o in art { + if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { + continue; + } + // Only art that would be added counts toward the limit. + if selected.len() + ids.len() >= MAX_LISTED { + return Ok((ids, true)); + } + have.insert(o); + ids.push(o); + } + Ok((ids, false)) + })?; + if over { + return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); + } + if ids.is_empty() { + return Ok(Data::Undefined); + } + let command_id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, doc.uid, false, |h| command(h, command_id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) +} + +fn layer_is_isolated(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(Data::Bool(with_doc(h, doc, |_, st| st.isolation == Some(id)))) +} + +fn layer_remove(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": [id.0]})))?; + Ok(Data::Undefined) +} + +/// The layers of `parent` (`None`: the top level), without its ruler guides and art. +fn art_count(d: &Document, parent: Option) -> usize { + d.children(parent).map_or(0, |c| crate::doc::Node::guide_run_start(c)) +} + +/// Moves the layer `id` to `index` of `parent` with `node.move`, unless it is there already. +fn put_layer(h: &Host, doc: Doc, id: NodeId, parent: Option, index: usize) -> Result<()> { + let now = with_doc(h, doc, |_, st| st.doc.position(id)); + if now.is_some_and(|(p, i, _)| p == parent && i == index) { + return Ok(()); + } + let parent = parent.map_or(Value::Null, |p| json!(p.0)); + on_doc(h, doc.uid, true, |h| command(h, "node.move", &json!({"id": id.0, "parent": parent, "index": index})))?; + Ok(()) +} + +/// `zOrder(method)`: the layer goes to the top or the bottom of the layers beside it, or one step. +fn layer_z_order(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let method = match arg(a, 1) { + Data::String(s) => s.as_str(), + _ => "", + }; + let (parent, index) = with_doc(h, doc, |_, st| { + let d = &st.doc; + let (parent, i, _) = d.position(id).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips)); + let count = art_count(d, parent); + let last = count.saturating_sub(1); + // One step passes the next layer beside it, and the art between them. + let layer_at = |j: &usize| d.children(parent).and_then(|c| c.get(*j)).is_some_and(|n| n.is_layer()); + let to = match method { + "ZOrderMethod.BRINGTOFRONT" => last, + "ZOrderMethod.BRINGFORWARD" => (i + 1..count).find(layer_at).unwrap_or(i), + "ZOrderMethod.SENDBACKWARD" => (floor.min(i)..i).rev().find(layer_at).unwrap_or(i), + "ZOrderMethod.SENDTOBACK" => floor.min(i), + _ => return Err(HostError::Type("zOrder needs a ZOrderMethod value".into())), + }; + Ok((parent, to)) + })?; + put_layer(h, doc, id, parent, index)?; + Ok(Data::Undefined) +} + +/// `move(relativeObject, insertionLocation?)`: the layer goes into another layer (on top of its +/// contents, or at the bottom with `PLACEATEND`), to the top level of a document, or directly +/// above or below another layer. +fn layer_move(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + let how = placement_of(arg(a, 2))?; + let target = arg(a, 1); + let parent = if let Some(handle) = handle_of(target, "Document") { + let [run, uid] = handle.as_slice() else { return Err(type_error("Document")) }; + let to = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + if to.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if matches!(how, Placement::Above | Placement::Below) { + return Err(HostError::Error("a layer goes above or below another layer, not a document".into())); + } + None + } else if handle_of(target, "Layer").is_some() { + let (to, t) = layer_of(h, target)?; + if to.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + Some(t) + } else if matches!(target, Data::Undefined) { + return Err(HostError::Type("move needs a relative object".into())); + } else { + return Err(HostError::Type("a layer's relative object must be a layer or a document".into())); + }; + let (into, index) = with_doc(h, doc, |_, st| { + let d = &st.doc; + if let Some(t) = parent + && d.ancestry(t).is_some_and(|a| a.contains(&id)) + && !(t == id && matches!(how, Placement::Above | Placement::Below)) + { + return Err(HostError::Error("a layer cannot go into itself".into())); + } + let (into, beside) = match (how, parent) { + (Placement::Above | Placement::Below, Some(t)) => (d.parent_of(t), Some(t)), + (_, p) => (p, None), + }; + if into.is_some_and(|p| !editable(d, p)) { + return Err(HostError::Error("the layer is hidden or locked".into())); + } + let from = d.position(id); + let here = |p: Option| from.is_some_and(|(q, ..)| q == p); + let count = art_count(d, into) - usize::from(here(into)); + let floor = usize::from(into.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips) && count > 0); + let index = match (how, beside) { + (Placement::Above | Placement::Below, Some(b)) => { + if b == id { + return Ok((into, from.map_or(0, |(_, i, _)| i))); + } + let (_, mut i, _) = d.position(b).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + if let Some((_, j, _)) = from + && here(into) + && j < i + { + i -= 1; + } + if how == Placement::Above { i + 1 } else { i } + } + (Placement::Bottom, _) => 0, + _ => count, + }; + Ok((into, index.max(floor))) + })?; + put_layer(h, doc, id, into, index)?; + Ok(arg(a, 0).clone()) +} + +// ---- Layers ---- + +/// The document and the layer (`None`: the top level) a `Layers` object lists. +fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + let Some(handle) = handle_of(d, "Layers") else { return Err(type_error("Layers")) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low, reverts] => { + let (doc, id) = layer_of(h, &host_ref("Layer", &[*run, *uid, *high, *low, *reverts]))?; + Ok((doc, Some(id))) + } + _ => Err(type_error("Layers")), + } +} + +/// The layers of `parent` (`None`: the top level), top first. +fn layer_list(d: &Document, parent: Option) -> Vec { + let list = match parent { + None => Some(&d.layers), + Some(p) => d.children(Some(p)), + }; + #[cfg(test)] + super::LAYER_SCANS.with(|c| c.set(c.get() + list.map_or(0, |l| l.len() as u64))); + list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect() +} + +/// 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>); + +/// 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>> { + { + 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); + if let Some(at) = at { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } + } + let looked_at = match parent { + None => st.doc.layers.len(), + Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len), + }; + h.charge_call(looked_at as u64)?; + let ids = Rc::new(layer_list(&st.doc, parent)); + let mut lists = h.dom.layers.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= ART_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), parent, ids.clone())); + Ok(ids) +} + +fn layers_of(h: &Host, a: &[Data]) -> Answer { + let (doc, id) = this_layer(h, a)?; + Ok(host_ref("Layers", &layer_handle(h, doc.uid, id))) +} + +fn layers_length(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64))) +} + +fn layers_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + Ok(parent.map_or_else(|| doc_ref(h, doc.uid), |p| layer_ref(h, doc.uid, p))) +} + +fn layers_typename(h: &Host, a: &[Data]) -> Answer { + layers_scope(h, arg(a, 0))?; + Ok(text("Layers")) +} + +/// `collection["name"]` as `getByName` reads it, or `undefined` for `"name" in collection` when +/// nothing has the name, as the document's `pageItems` does. +fn read_by_name(h: &Host, a: &[Data], by_name: fn(&Host, &[Data]) -> Answer) -> Answer { + match by_name(h, a) { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + } +} + +fn layers_at(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if let Data::String(_) = arg(a, 1) { + return read_by_name(h, a, layers_by_name); + } + 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) }; + with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) +} + +fn layers_by_name(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = layers_listed(h, st, parent)?; + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn layers_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => layers_by_name(h, a), + Data::Number(_) => match layers_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `layers.add()`: a new layer above every top-level layer, or a sublayer on top of the layer's +/// contents. → the new layer, which is the current one. +fn layers_add(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if let Some(p) = parent { + let ok = with_doc(h, doc, |_, st| editable(&st.doc, p)); + if !ok { + return Err(HostError::Error("the layer is hidden or locked".into())); + } + } + let (_, r) = on_doc_layer(h, doc.uid, true, false, |h| match parent { + None => command_value(h, "layer.new", &json!({"top": true})), + Some(p) => command_value(h, "layer.newSublayer", &json!({"parent": p.0})), + })?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the layer was not made".into()))?; + Ok(layer_ref(h, doc.uid, NodeId(id))) +} + +/// `layers.removeAll()`: deletes every layer of the collection in one command. A document keeps a +/// layer, so on the top-level layers it throws before anything is deleted. +fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, parent) = layers_scope(h, arg(a, 0))?; + if parent.is_none() { + return Err(HostError::Error("a document needs at least one layer".into())); + } + let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?; + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- GroupItems, CompoundPathItems and a container's PageItems ---- + +/// The document and the layer, group or compound path (`None`: the whole document) an art +/// collection of `class` lists. +fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { + let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low, reverts] => { + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + // A collection read before File › Revert is stale like its container. + let holds = with_doc(h, doc, |_, st| { + whole(*reverts) == Some(st.reverts) + && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. })) + }); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(type_error(class)), + } +} + +/// A document's uid, the document as it was, the [`Kind`] and the container of an art collection, +/// and the ids it listed then. +pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); + +/// How many lists of art [`super::State`] keeps at once. +pub(super) const ART_LISTS: usize = 4; + +/// The objects of `kind` in `container` (directly), topmost first, or in the whole document at any +/// depth, in the order of the document's `pageItems`. The last [`ART_LISTS`] lists are kept while +/// their documents are unchanged, so a loop over groups that reads each group's `pageItems` builds +/// each list once. Each new list is charged by the objects it looks at. +fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { + { + let mut lists = h.dom.art.borrow_mut(); + let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container); + if let Some(at) = at { + let list = lists.remove(at); + let ids = list.4.clone(); + lists.push(list); + return Ok(ids); + } + } + #[cfg(test)] + super::ART_SCANS.with(|c| c.set(c.get() + 1)); + let ids: Vec = match container { + None => { + let all = page_items(h, st)?; + h.charge_call(all.len() as u64)?; + all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() + } + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect() + } + }; + let ids = Rc::new(ids); + let mut lists = h.dom.art.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= ART_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); + Ok(ids) +} + +/// Whether a `PageItems` or `PathItems` object's handle names its container. +pub(super) fn is_scoped(a: &[Data], class: &str) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5) +} + +fn scoped_kind(a: &[Data]) -> Kind { + if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any } +} + +/// How many times File › Revert has reloaded the document with uid `uid`. +fn reverts_of(h: &Host, uid: u64) -> u64 { + h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts) +} + +fn collection(h: &Host, kind: Kind, container: Option, uid: u64) -> Data { + match container { + Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]), + None => host_ref(kind.class(), &[float(h.run), float(uid)]), + } +} + +fn art_length(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let n = with_doc(h, doc, |_, st| art_list(h, st, kind, c).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) +} + +fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + if let Data::String(_) = arg(a, 1) { + return match art_by_name(h, a, kind) { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + }; + } + 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) }; + with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = art_list(h, st, kind, c)?; + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { + match arg(a, 1) { + Data::String(_) => art_by_name(h, a, kind), + Data::Number(_) => match art_at(h, a, kind)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `removeAll()`: deletes every object the collection lists (those inside another listed one go +/// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or +/// one on a locked artboard stops it before anything is deleted, as the document's +/// `pageItems.removeAll()` is stopped. +fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { + let all = art_list(h, st, kind, c)?; + let d = &st.doc; + let listed: std::collections::HashSet = all.iter().copied().collect(); + let ids: Vec = + all.iter().copied().filter(|i| !d.ancestry(*i).is_some_and(|a| a.iter().any(|x| *x != *i && listed.contains(x)))).collect(); + let whole = |id: &NodeId| editable(d, *id) && d.node(*id).is_some_and(super::all_editable); + let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); + let locks = d.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + // A clipping path whose group or layer keeps other art would leave the next object clipping it. + let going: std::collections::HashSet = ids.iter().copied().collect(); + let masks: Vec = ids + .iter() + .filter(|i| { + d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| { + let kids = p.children().map_or(&[][..], Vec::as_slice); + p.clips() + && kids.first().is_some_and(|f| f.id == **i) + && kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) + }) + }) + .map(|i| i.0) + .take(20) + .collect(); + Ok::<_, HostError>((ids, refused, on_locked, masks)) + })?; + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); + } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } + if !masks.is_empty() { + let list = masks.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" + ))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; + } + Ok(Data::Undefined) +} + +/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]). +pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, scoped_kind(a)) +} + +pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, scoped_kind(a)) +} + +fn groups_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Group) +} +fn groups_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Group) +} +fn groups_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Group) +} +fn groups_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Group) +} +fn groups_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Group) +} +fn groups_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Group) +} +fn compounds_length(h: &Host, a: &[Data]) -> Answer { + art_length(h, a, Kind::Compound) +} +fn compounds_parent(h: &Host, a: &[Data]) -> Answer { + art_parent(h, a, Kind::Compound) +} +fn compounds_at(h: &Host, a: &[Data]) -> Answer { + art_at(h, a, Kind::Compound) +} +fn compounds_by_name(h: &Host, a: &[Data]) -> Answer { + art_by_name(h, a, Kind::Compound) +} +fn compounds_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Compound) +} +fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { + art_remove_all(h, a, Kind::Compound) +} + +fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) +} + +pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, scoped_kind(a)) +} +fn groups_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Group) +} +fn compounds_typename(h: &Host, a: &[Data]) -> Answer { + art_typename(h, a, Kind::Compound) +} + +/// `groupItems.add()` and `compoundPathItems.add()`: an empty group or compound path on top of the +/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. +/// → the new object. +fn container_add(h: &Host, a: &[Data], kind: Kind) -> Answer { + let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; + if let Some(c) = c { + let compound = with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + if compound { + return Err(HostError::Error("a compound path holds only paths".into())); + } + } + let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); + if kind == Kind::Compound + && let Some(o) = params.as_object_mut() + { + o.insert("compound".into(), json!(true)); + } + let (_, r) = on_doc(h, doc.uid, true, |h| command_value(h, "object.newGroup", ¶ms))?; + let id = result_id(&r, "id").ok_or_else(|| HostError::Error("the object was not made".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, NodeId(id))) +} + +fn groups_add(h: &Host, a: &[Data]) -> Answer { + container_add(h, a, Kind::Group) +} + +fn compounds_add(h: &Host, a: &[Data]) -> Answer { + container_add(h, a, Kind::Compound) +} + +// ---- The art collections of a document, a layer, a group and a compound path ---- + +/// The collection of `kind` the object `this` holds: a document's (`Document`), a layer's +/// (`Layer`) or a page item's. +fn held(h: &Host, a: &[Data], kind: Kind) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Document").is_some() { + let doc = doc_of(h, this, "Document")?; + return Ok(collection(h, kind, None, doc.uid)); + } + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(collection(h, kind, Some(id), doc.uid)); + } + let item = item_of(h, this)?; + Ok(collection(h, kind, Some(item.id), item.doc.uid)) +} + +fn held_page_items(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Any) +} + +fn held_paths(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Path) +} + +fn held_groups(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Group) +} + +fn held_compounds(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Compound) +} + +// ---- GroupItem and CompoundPathItem ---- + +fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { + let item = item_of(h, arg(a, 0))?; + let ok = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename) == Some(what)); + if !ok { + return Err(type_error(what)); + } + Ok(item) +} + +/// The layer the object is in. +fn item_layer(h: &Host, a: &[Data]) -> Answer { + let item = item_of(h, arg(a, 0))?; + Ok(with_doc(h, item.doc, |_, st| st.doc.layer_containing(item.id).map_or(Data::Null, |l| layer_ref(h, st.uid, l)))) +} + +fn group_clipped(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "GroupItem")?; + Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(crate::doc::Node::clips)))) +} + +/// `clipped = true`: the group's topmost object becomes its clipping path; `false` releases the +/// clipping mask. The group keeps its id either way. +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))); + if now == on { + return Ok(Data::Undefined); + } + super::refuse_protected_edit(h, item)?; + if !ok { + return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0))); + } + on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?; + Ok(Data::Undefined) +} + +/// The members `layers.rs` adds to `PageItem`'s. +pub(super) fn page_item_members(l: &Link) -> Vec { + named(vec![("layer", get(l, item_layer), typed("Layer"))]) +} + +/// The members a page item class adds to `PageItem`'s. +pub(super) fn members(class: &str, l: &Link) -> Vec { + match class { + "GroupItem" => { + let mut m = named(vec![ + ("clipped", property(l, group_clipped, group_set_clipped), typed("boolean")), + ("pageItems", get(l, held_page_items), listed("PageItems")), + ("groupItems", get(l, held_groups), listed("GroupItems")), + ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ]); + m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m + } + "CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]), + _ => Vec::new(), + } +} + +/// What `reflect` tells of a member whose value is a collection of class `data_type`. +fn listed(data_type: &str) -> MemberInfo { + MemberInfo { collection: true, ..typed(data_type) } +} + +// ---- Document ---- + +fn doc_layers(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Layers", &[float(h.run), float(doc.uid)])) +} + +fn doc_active_layer(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()).map_or(Data::Null, |l| layer_ref(h, st.uid, l)))) +} + +/// `activeLayer = layer`: the layer becomes the current one, where new art goes. +fn doc_set_active_layer(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + let (to, id) = layer_of(h, arg(a, 1))?; + if to.uid != doc.uid { + return Err(HostError::Error("the layer is in another document".into())); + } + let now = with_doc(h, doc, |_, st| st.current_layer()); + if now != Some(id) { + on_doc_layer(h, doc.uid, true, false, |h| command(h, "layer.setCurrent", &json!({"id": id.0})))?; + } + Ok(Data::Undefined) +} + +fn doc_artboards(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Artboards", &[float(h.run), float(doc.uid)])) +} + +/// The members `layers.rs` adds to `Document`'s. +pub(super) fn document_members(l: &Link) -> Vec { + named(vec![ + ("layers", get(l, doc_layers), listed("Layers")), + ("activeLayer", property(l, doc_active_layer, doc_set_active_layer), typed("Layer")), + ("groupItems", get(l, held_groups), listed("GroupItems")), + ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("artboards", get(l, doc_artboards), listed("Artboards")), + ]) +} + +// ---- Artboard and Artboards ---- + +/// The document of an artboard. +#[derive(Clone, Copy)] +struct Board { + doc: Doc, +} + +fn board_index(st: &DocState, id: u32) -> Option { + st.doc.artboards.iter().position(|a| a.id == id) +} + +fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> { + let Some(handle) = handle_of(d, "Artboard") else { return Err(type_error("Artboard")) }; + let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + // An artboard read before File › Revert is stale, as the page items read with it are. + let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts))) + .ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + Ok((Board { doc }, index)) +} + +fn board_ref(h: &Host, uid: u64, id: u32) -> Data { + host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))]) +} + +fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> { + board_of(h, arg(a, 0)) +} + +/// Reads the artboard `this` names with `f`. +fn read_board(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Artboard, usize) -> Answer) -> Answer { + let (b, i) = this_board(h, a)?; + with_doc(h, b.doc, |_, st| match st.doc.artboards.get(i) { + Some(ab) => f(st, ab, i), + None => Err(HostError::Error(STALE_ARTBOARD.into())), + }) +} + +/// Runs `artboard.setProps` with `props` for the artboard, unless `unchanged` says it has them. +fn set_board(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Artboard) -> bool, props: Value) -> Answer { + let (b, i) = this_board(h, a)?; + let same = with_doc(h, b.doc, |_, st| st.doc.artboards.get(i).is_some_and(unchanged)); + if !same { + let mut p = props; + if let Some(o) = p.as_object_mut() { + o.insert("index".into(), json!(i)); + } + on_doc(h, b.doc.uid, true, |h| command(h, "artboard.setProps", &p))?; + } + Ok(Data::Undefined) +} + +fn board_rect(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |st, ab, _| Ok(frame(st)?.bounds(h.dom.coords.get(), ab.rect))) +} + +/// A rectangle `[left, top, right, bottom]` a script gave, in document coordinates, checked: finite, +/// inside the canvas, and from 1 to [`super::MAX_SIZE`] points on each side, the sides the artboard +/// commands keep. +fn rect_arg(h: &Host, st: &DocState, d: &Data, what: &str) -> Result { + let Data::Array(v) = d else { return Err(HostError::Type(format!("{what} must be an array of four numbers"))) }; + let [l, t, r, b] = v.as_slice() else { return Err(HostError::Type(format!("{what} must be an array of four numbers"))) }; + let n = |d: &Data| super::coordinate(d, what); + let (l, t, r, b) = (n(l)?, n(t)?, n(r)?, n(b)?); + let f = frame(st)?; + let c = h.dom.coords.get(); + let p = f.to_document(c, [l, t]); + let q = f.to_document(c, [r, b]); + let rect = vectorcraft_geom::Rect::new(p.x.min(q.x), p.y.min(q.y), p.x.max(q.x), p.y.max(q.y)); + if q.x <= p.x || q.y <= p.y { + return Err(HostError::Range(format!("{what} must have its right side right of its left side and its bottom below its top"))); + } + if rect.width() < 1.0 || rect.height() < 1.0 { + return Err(HostError::Range(format!("{what} must be at least 1 point wide and tall"))); + } + if rect.width() > super::MAX_SIZE || rect.height() > super::MAX_SIZE { + return Err(HostError::Range(format!("{what} must be at most 3999856 points wide and tall"))); + } + if [rect.x0, rect.y0, rect.x1, rect.y1].iter().any(|v| v.abs() > crate::MAX_COORD) { + return Err(HostError::Range(format!("{what} is outside the canvas"))); + } + Ok(rect) +} + +fn board_set_rect(h: &Host, a: &[Data]) -> Answer { + let (b, _) = this_board(h, a)?; + let r = with_doc(h, b.doc, |_, st| rect_arg(h, st, arg(a, 1), "artboardRect"))?; + let close = |x: f64, y: f64| (x - y).abs() < 1e-9; + set_board( + h, + a, + |ab| close(ab.rect.x0, r.x0) && close(ab.rect.y0, r.y0) && close(ab.rect.x1, r.x1) && close(ab.rect.y1, r.y1), + json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height()}), + ) +} + +fn board_name(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(text(ab.name.clone()))) +} + +/// A new artboard name: at most [`MAX_TEXT_BYTES`] bytes; a number or boolean as `String()` writes +/// it. Another artboard may have the same name. → the name, trimmed as `artboard.setProps` trims +/// it; an empty one gives the artboard its default name, `Artboard N` for the Nth artboard. +fn board_name_arg(d: &Data, index: usize) -> Result { + let name = name_text(d)?; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let name = name.trim(); + Ok(if name.is_empty() { format!("Artboard {}", index + 1) } else { name.to_string() }) +} + +fn board_set_name(h: &Host, a: &[Data]) -> Answer { + let (_, i) = this_board(h, a)?; + let name = board_name_arg(arg(a, 1), i)?; + set_board(h, a, |ab| ab.name == name, json!({"name": &name})) +} + +fn board_parent(h: &Host, a: &[Data]) -> Answer { + let (b, _) = this_board(h, a)?; + Ok(doc_ref(h, b.doc.uid)) +} + +fn board_typename(h: &Host, a: &[Data]) -> Answer { + this_board(h, a)?; + Ok(text("Artboard")) +} + +fn board_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Artboard", board_name(h, a)) +} + +/// `rulerOrigin`: where the rulers measure from with this artboard active, from its top-left corner +/// with Y down. +fn board_ruler_origin(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |st, ab, i| { + let o = st.doc.ruler_origin_for(i); + Ok(super::pair([o.x - ab.rect.x0, o.y - ab.rect.y0])) + }) +} + +fn board_set_ruler_origin(h: &Host, a: &[Data]) -> Answer { + let p = super::point(arg(a, 1), "rulerOrigin")?; + let (b, i) = this_board(h, a)?; + let (to, now) = with_doc(h, b.doc, |_, st| { + let ab = &st.doc.artboards[i]; + (vectorcraft_geom::Point::new(ab.rect.x0 + p[0], ab.rect.y0 + p[1]), st.doc.ruler_origin_for(i)) + }); + if to.distance(now) > 1e-9 { + on_doc(h, b.doc.uid, false, |h| command(h, "document.setRulerOrigin", &json!({"x": to.x, "y": to.y, "artboard": i})))?; + } + Ok(Data::Undefined) +} + +fn board_par(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(num(ab.video_ruler_pixel_aspect_ratio))) +} + +fn board_set_par(h: &Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "rulerPAR")?; + if !crate::doc::VIDEO_PIXEL_ASPECT_RANGE.contains(&v) { + return Err(HostError::Range("rulerPAR must be from 0.1 to 10".into())); + } + set_board(h, a, |ab| (ab.video_ruler_pixel_aspect_ratio - v).abs() < 1e-12, json!({"videoRulerPixelAspectRatio": v})) +} + +fn board_center(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_center_mark))) +} + +fn board_set_center(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showCenter")?; + set_board(h, a, |ab| ab.show_center_mark == v, json!({"showCenterMark": v})) +} + +fn board_cross_hairs(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_cross_hairs))) +} + +fn board_set_cross_hairs(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showCrossHairs")?; + set_board(h, a, |ab| ab.show_cross_hairs == v, json!({"showCrossHairs": v})) +} + +fn board_safe_areas(h: &Host, a: &[Data]) -> Answer { + read_board(h, a, |_, ab, _| Ok(Data::Bool(ab.show_video_safe_areas))) +} + +fn board_set_safe_areas(h: &Host, a: &[Data]) -> Answer { + let v = boolean(arg(a, 1), "showSafeAreas")?; + set_board(h, a, |ab| ab.show_video_safe_areas == v, json!({"showVideoSafeAreas": v})) +} + +fn board_remove(h: &Host, a: &[Data]) -> Answer { + let (b, i) = this_board(h, a)?; + on_doc(h, b.doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + Ok(Data::Undefined) +} + +fn boards_doc(h: &Host, a: &[Data]) -> Result { + doc_of(h, arg(a, 0), "Artboards") +} + +fn boards_length(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| st.doc.artboards.len()) as u64))) +} + +fn boards_parent(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn boards_typename(h: &Host, a: &[Data]) -> Answer { + boards_doc(h, a)?; + Ok(text("Artboards")) +} + +/// `toString()` of a collection: `[Class]`, after the same checks of the collection as `typename`. +fn layers_to_string(h: &Host, a: &[Data]) -> Answer { + layers_scope(h, arg(a, 0))?; + Ok(text("[Layers]")) +} +fn groups_to_string(h: &Host, a: &[Data]) -> Answer { + art_scope(h, arg(a, 0), Kind::Group.class())?; + Ok(text("[GroupItems]")) +} +fn compounds_to_string(h: &Host, a: &[Data]) -> Answer { + art_scope(h, arg(a, 0), Kind::Compound.class())?; + Ok(text("[CompoundPathItems]")) +} +fn boards_to_string(h: &Host, a: &[Data]) -> Answer { + boards_doc(h, a)?; + Ok(text("[Artboards]")) +} + +/// An artboard index argument: a whole number below `len` (`len + 1` with `insert`). +fn board_index_arg(d: &Data, len: usize, what: &str) -> Result { + let n = number(d, what)?; + whole(n) + .and_then(|i| usize::try_from(i).ok()) + .filter(|i| *i < len) + .ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1)))) +} + +fn boards_at(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return read_by_name(h, a, boards_by_name); + } + 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) }; + Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id)))) +} + +fn boards_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = boards_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| { + h.charge_call(st.doc.artboards.len() as u64)?; + let ab = st.doc.artboards.iter().find(|ab| ab.name == *name); + ab.map(|ab| board_ref(h, st.uid, ab.id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn boards_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => boards_by_name(h, a), + Data::Number(_) => match boards_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// A new artboard at `rect` with `artboard.new`, moved to `at` (`None`: it stays last) with +/// `artboard.reorder`; when either fails, the document is as it was. → the artboard. +fn add_board(h: &Host, a: &[Data], at: Option<&Data>) -> Answer { + let doc = boards_doc(h, a)?; + let (r, len, name) = with_doc(h, doc, |_, st| { + let boards = &st.doc.artboards; + h.charge_call(boards.len() as u64)?; + // The first "Artboard N" from one past the count that no artboard has. + let name = (boards.len() + 1..).map(|n| format!("Artboard {n}")).find(|n| !boards.iter().any(|ab| ab.name == *n)).unwrap_or_default(); + Ok::<_, HostError>((rect_arg(h, st, arg(a, 1), "artboardRect")?, boards.len(), name)) + })?; + let to = at.map(|d| board_index_arg(d, len + 1, "index")).transpose()?; + let max = whole(super::MAX_ARTBOARDS).and_then(|m| usize::try_from(m).ok()).unwrap_or(0); + if len >= max { + return Err(HostError::Range(format!("a document has at most {max} artboards"))); + } + let id = super::atomically(h, |h| { + on_doc(h, doc.uid, true, |h| { + let (_, made) = command_value(h, "artboard.new", &json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "name": name}))?; + let index = result_id(&made, "index") + .and_then(|i| usize::try_from(i).ok()) + .ok_or_else(|| HostError::Error("the artboard was not made".into()))?; + if let Some(to) = to + && to != index + { + command(h, "artboard.reorder", &json!({"index": index, "to": to}))?; + } + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.doc.artboards.get(to.unwrap_or(index)).map(|ab| ab.id).ok_or_else(|| HostError::Error("the artboard was not made".into())) + }) + })?; + Ok(board_ref(h, doc.uid, id)) +} + +/// `artboards.add(artboardRect)`: a new artboard, last in the list. +fn boards_add(h: &Host, a: &[Data]) -> Answer { + add_board(h, a, None) +} + +/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → nothing. +fn boards_insert(h: &Host, a: &[Data]) -> Answer { + if matches!(arg(a, 2), Data::Undefined) { + return Err(HostError::Type("insert needs an index".into())); + } + add_board(h, a, Some(arg(a, 2)))?; + Ok(Data::Undefined) +} + +fn boards_remove(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let len = with_doc(h, doc, |_, st| st.doc.artboards.len()); + let i = board_index_arg(arg(a, 1), len, "index")?; + on_doc(h, doc.uid, true, |h| command(h, "artboard.delete", &json!({"index": i})))?; + Ok(Data::Undefined) +} + +fn boards_active(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| active_artboard(st)) as u64))) +} + +/// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the +/// document changes, and no command runs. The artboard is kept by its id even when it is already +/// active only as the fallback (no artboard chosen yet), so an artboard inserted before it later +/// in the run moves it to the next index instead of taking its place. +fn boards_set_active(h: &Host, a: &[Data]) -> Answer { + let doc = boards_doc(h, a)?; + let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st))); + let i = board_index_arg(arg(a, 1), len, "index")?; + { + let mut s = h.session.borrow_mut(); + let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id); + } + { + let mut chosen = h.dom.chosen_artboards.borrow_mut(); + let reverts = reverts_of(h, doc.uid); + if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) { + *generation = reverts; + } else { + chosen.push((doc.uid, reverts)); + } + } + // A document made during the run has no index from the start of the run, so the first choice + // records one; an artboard inserted before it later still puts it in the report. + if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) { + let mut made = h.dom.boards_chosen_in_new.borrow_mut(); + if !made.iter().any(|(uid, _)| *uid == doc.uid) { + made.push((doc.uid, i)); + } + } + if i != now { + let mut moved = h.dom.active_artboards.borrow_mut(); + if !moved.contains(&doc.uid) { + moved.push(doc.uid); + } + } + Ok(Data::Undefined) +} + +/// The documents whose active artboard the run changed, as `script.run`'s report gives them: +/// `[{document, artboard}]`, each an index, with the active artboard each document has at the end +/// of the run, or `None` when there are none. They are the documents in `moved`, then those whose +/// active artboard's index differs from the one in `start` (an artboard added, inserted, removed or +/// reordered before it). +pub(crate) fn active_artboards(moved: &[u64], start: &[(u64, usize)], docs: &[DocState]) -> Option { + let mut uids = moved.to_vec(); + for (uid, at) in start { + let shifted = docs.iter().find(|d| d.uid == *uid).is_some_and(|st| active_artboard(st) != *at); + if shifted && !uids.contains(uid) { + uids.push(*uid); + } + } + let list: Vec = uids + .iter() + .filter_map(|uid| { + let document = docs.iter().position(|d| d.uid == *uid)?; + Some(json!({"document": document, "artboard": active_artboard(&docs[document])})) + }) + .collect(); + (!list.is_empty()).then_some(Value::Array(list)) +} + +/// The classes of layers, art collections and artboards. +pub(super) fn classes(l: &Link) -> Vec { + let class = super::class; + let mut layer = named(vec![ + ("typename", get(l, layer_typename), typed("string")), + ("name", property(l, layer_name, layer_set_name), typed("string")), + ("visible", property(l, layer_visible, layer_set_visible), typed("boolean")), + ("locked", property(l, layer_locked, layer_set_locked), typed("boolean")), + ("printable", property(l, layer_printable, layer_set_printable), typed("boolean")), + ("preview", property(l, layer_preview, layer_set_preview), typed("boolean")), + ("dimPlacedImages", property(l, layer_dim, layer_set_dim), typed("boolean")), + ("opacity", property(l, layer_opacity, layer_set_opacity), typed("number")), + ("color", property(l, layer_color, layer_set_color), typed("RGBColor")), + ("parent", get(l, layer_parent), typed("*")), + ("layers", get(l, layers_of), listed("Layers")), + ("pageItems", get(l, held_page_items), listed("PageItems")), + ("groupItems", get(l, held_groups), listed("GroupItems")), + ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("zOrderPosition", get(l, layer_z_position), typed("number")), + ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")), + ("isIsolated", get(l, layer_is_isolated), typed("boolean")), + ("move", method(l, layer_move), typed("Layer")), + ("remove", method(l, layer_remove), returns("undefined", &[])), + ("zOrder", method(l, layer_z_order), typed("undefined")), + ("toString", method(l, layer_to_string), returns("string", &[])), + ]); + layer.extend( + ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] + .map(|m| later(l, "Layer", m)), + ); + vec![ + class("Layer", None, layer, None), + class( + "Layers", + None, + named(vec![ + ("typename", get(l, layers_typename), typed("string")), + ("length", get(l, layers_length), typed("number")), + ("parent", get(l, layers_parent), typed("*")), + ("index", method(l, layers_index), returns("Layer", &[("itemKey", "*")])), + ("getByName", method(l, layers_by_name), returns("Layer", &[("name", "string")])), + ("add", method(l, layers_add), returns("Layer", &[])), + ("removeAll", method(l, layers_remove_all), returns("undefined", &[])), + ("toString", method(l, layers_to_string), returns("string", &[])), + ]), + Some(super::function(l, layers_at)), + ), + class( + "GroupItems", + None, + { + let mut m = named(vec![ + ("typename", get(l, groups_typename), typed("string")), + ("length", get(l, groups_length), typed("number")), + ("parent", get(l, groups_parent), typed("*")), + ("index", method(l, groups_index), returns("GroupItem", &[("itemKey", "*")])), + ("getByName", method(l, groups_by_name), returns("GroupItem", &[("name", "string")])), + ("add", method(l, groups_add), returns("GroupItem", &[])), + ("removeAll", method(l, groups_remove_all), returns("undefined", &[])), + ("toString", method(l, groups_to_string), returns("string", &[])), + ]); + m.push(later(l, "GroupItems", "createFromFile")); + m + }, + Some(super::function(l, groups_at)), + ), + class( + "CompoundPathItems", + None, + named(vec![ + ("typename", get(l, compounds_typename), typed("string")), + ("length", get(l, compounds_length), typed("number")), + ("parent", get(l, compounds_parent), typed("*")), + ("index", method(l, compounds_index), returns("CompoundPathItem", &[("itemKey", "*")])), + ("getByName", method(l, compounds_by_name), returns("CompoundPathItem", &[("name", "string")])), + ("add", method(l, compounds_add), returns("CompoundPathItem", &[])), + ("removeAll", method(l, compounds_remove_all), returns("undefined", &[])), + ("toString", method(l, compounds_to_string), returns("string", &[])), + ]), + Some(super::function(l, compounds_at)), + ), + class( + "Artboard", + None, + named(vec![ + ("typename", get(l, board_typename), typed("string")), + ("artboardRect", property(l, board_rect, board_set_rect), typed("Array")), + ("name", property(l, board_name, board_set_name), typed("string")), + ("parent", get(l, board_parent), typed("Document")), + ("rulerOrigin", property(l, board_ruler_origin, board_set_ruler_origin), typed("Array")), + ("rulerPAR", property(l, board_par, board_set_par), typed("number")), + ("showCenter", property(l, board_center, board_set_center), typed("boolean")), + ("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs), typed("boolean")), + ("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas), typed("boolean")), + ("remove", method(l, board_remove), returns("undefined", &[])), + ("toString", method(l, board_to_string), returns("string", &[])), + ]), + None, + ), + class( + "Artboards", + None, + named(vec![ + ("typename", get(l, boards_typename), typed("string")), + ("length", get(l, boards_length), typed("number")), + ("parent", get(l, boards_parent), typed("Document")), + ("index", method(l, boards_index), returns("Artboard", &[("itemKey", "*")])), + ("getByName", method(l, boards_by_name), returns("Artboard", &[("name", "string")])), + ("add", method(l, boards_add), returns("Artboard", &[("artboardRect", "Array")])), + ("insert", method(l, boards_insert), returns("undefined", &[("artboardRect", "Array"), ("index", "number")])), + ("remove", method(l, boards_remove), returns("undefined", &[("index", "number")])), + ("getActiveArtboardIndex", method(l, boards_active), returns("number", &[])), + ("setActiveArtboardIndex", method(l, boards_set_active), returns("undefined", &[("index", "number")])), + ("toString", method(l, boards_to_string), returns("string", &[])), + ]), + Some(super::function(l, boards_at)), + ), + ] +} diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 50cd224f44..a164dd93fc 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -397,21 +397,33 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { } fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { + if super::layers::is_scoped(a, "PathItems") { + return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".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(a, "PathItems") { + return super::layers::scoped_typename(h, a); + } items_doc(h, a)?; Ok(Data::String("PathItems".into())) } fn items_length(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_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(a, "PathItems") { + return super::layers::scoped_parent(h, a); + } let doc = items_doc(h, a)?; Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) } @@ -420,6 +432,9 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { /// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is /// looked up as that name, giving `undefined` when no path has it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_at(h, a); + } let doc = items_doc(h, a)?; match arg(a, 1) { Data::String(_) => match items_by_name(h, a) { @@ -443,6 +458,9 @@ fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer { } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_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())) }; items_named(h, doc, name) @@ -459,6 +477,9 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &super::Host, a: &[Data]) -> Answer { + if super::layers::is_scoped(a, "PathItems") { + return super::layers::scoped_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(n) => { @@ -476,6 +497,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(a, "PathItems") { + return super::layers::scoped_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)?; @@ -1813,8 +1837,9 @@ pub(super) fn classes(l: &Link) -> Vec { None, named(vec![ ("typename", get(l, items_typename), typed("string")), + ("toString", super::class_text("PathItems"), returns("string", &[])), ("length", get(l, items_length), typed("number")), - ("parent", get(l, items_parent), typed("Document")), + ("parent", get(l, items_parent), typed("*")), ("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])), ("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])), ("removeAll", method(l, items_remove_all), returns("undefined", &[])), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 50a550f4db..0890a75fcd 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2431,7 +2431,7 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), - dom: dom::State::new(heap_bytes), + dom: dom::State::new(self.documents(), heap_bytes), actions: request.actions, active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), artboard_picks, @@ -2748,6 +2748,10 @@ impl Session { "hostCalls": host.calls.get(), }); host.more_written(&mut report); + let start: Vec<(u64, usize)> = host.dom.boards_at_start.iter().chain(host.dom.boards_chosen_in_new.borrow().iter()).copied().collect(); + if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) { + report["activeArtboards"] = boards; + } // The run ran a Copy or Cut, and the clipboard still holds what one put there. if host.copied.get() && self.clipboard_copied diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 1432b8671b..ea399d2fd2 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -262,6 +262,82 @@ fn steps_act_on_the_artboard_active_as_they_run() { assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); } +/// After the script makes another artboard active with `setActiveArtboardIndex`, a step that acts +/// on the active artboard acts on that one. +#[test] +fn steps_act_on_the_artboard_the_script_made_active() { + 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 was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 0); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');", &actions); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(now[0], was[0], "the artboard active as the run started is unchanged"); + assert_ne!(now[1], was[1], "the artboard the script made active is fitted"); + // Choosing the artboard that is already active, after an insert moved it, also counts. + make_active(&mut s, 0); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + log_with( + &mut s, + "var b = app.activeDocument.artboards; b.insert([300, 300, 400, 200], 0); b.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');", + &actions, + ); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_ne!(now[1], was[0], "the artboard chosen again is fitted"); +} + +#[test] +fn steps_use_the_chosen_index_when_the_chosen_artboard_is_deleted() { + 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 was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 2); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + let report = run_with( + &mut s, + "var b = app.activeDocument.artboards; b.setActiveArtboardIndex(2); b.remove(2);\ + vc.log(b.getActiveArtboardIndex()); app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\ + vc.log(app.activeDocument.selection[0].position); app.doScript('Fit', 'Set');", + &actions, + ) + .unwrap(); + assert_eq!(report["log"], json!([0, [10, 10]])); + assert_eq!(report["activeArtboards"], json!([{"document": 0, "artboard": 0}])); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(now.len(), 2); + assert_ne!(now[0], was[0], "the fallback artboard is fitted"); + assert_eq!(now[1], was[1], "the other artboard is unchanged"); +} + +#[test] +fn steps_discard_the_chosen_artboard_after_revert() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("script-actions-revert-artboard"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 2); + let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]); + log_with( + &mut s, + "app.activeDocument.artboards.setActiveArtboardIndex(0); app.activeDocument.pageItems[0].name = 'changed'; vc.run('file.revert');\ + app.activeDocument.selection = app.activeDocument.pageItems[0]; app.doScript('Fit', 'Set');", + &actions, + ); + let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(now[..2], was[..2]); + assert_ne!(now[2], was[2], "playback uses the run's original index after revert"); +} + /// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none, /// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it. #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a272404179..73e44c2af7 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -665,6 +665,23 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps + 1); } +/// An item's or a layer's opacity that differs from the reported one, however little, is set as +/// given. +#[test] +fn an_opacity_near_the_reported_one_is_still_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 0})).unwrap(); + let out = log( + &mut s, + "var q = app.activeDocument.pageItems, i = q[0].opacity === 0 ? q[0] : q[1]; i.opacity = 0.00009; vc.log(i.opacity);\ + var l = app.activeDocument.layers[0]; l.opacity = 0; l.opacity = 0.00009; vc.log(l.opacity);", + ); + assert_eq!(out, vec![json!(0.0001), json!(0.0001)]); + let d = &s.active().unwrap().doc; + assert!(d.node(a).unwrap().opacity > 0.0); + assert!(d.node(d.layer_containing(a).unwrap()).unwrap().opacity > 0.0); +} + /// `blendingMode` reads and sets the object's own blend mode as a `BlendModes` value; the mode it /// already has adds no undo step, and any other value throws and changes nothing. #[test] @@ -1563,7 +1580,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() { ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } - assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); + assert!(failure(&mut s, "app.activeDocument.swatches = 1;").contains("Document.swatches is not available yet")); // A deleted item or an earlier run's document is stale first. let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;"); assert!(e.contains("Stale page item"), "{e}"); @@ -2189,6 +2206,25 @@ fn wrappers_go_stale_after_revert() { } } +/// A layer's or group's collection and an artboard read before File › Revert are stale after it, +/// while the document's own collections follow the loaded document. +#[test] +fn scoped_collections_and_artboards_go_stale_after_revert() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-scoped"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let held = "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.layers[0].groupItems, ab = d.artboards[0], all = d.groupItems;\ + d.pageItems[0].name = 'changed'; vc.run('file.revert');"; + for (read, stale) in + [("p.length", "Stale page item"), ("g.length", "Stale page item"), ("ab.name", "Stale artboard"), ("ab.name = 'x'", "Stale artboard")] + { + let source = format!("{held} try {{ {read}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}"); + assert_eq!(log(&mut s, &source), vec![json!(stale)], "{read}"); + } + assert_eq!(log(&mut s, &format!("{held} vc.log(all.length); vc.log(d.artboards[0].name);")), vec![json!(0), json!("Artboard 1")]); +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); @@ -2276,6 +2312,64 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +/// The `removeAll()` of a layer's or group's collections, and of `groupItems` and +/// `compoundPathItems`, refuses art on a locked artboard as the document's `pageItems.removeAll()` +/// does, and deletes nothing. +#[test] +fn scoped_remove_all_refuses_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + for scope in [ + "app.activeDocument.layers[0].pageItems", + "app.activeDocument.layers[0].groupItems", + "app.activeDocument.groupItems", + "app.activeDocument.groupItems[0].pageItems", + "app.activeDocument.layers[0].compoundPathItems", + "app.activeDocument.compoundPathItems", + ] { + let err = failure(&mut s, &format!("{scope}.removeAll();")); + assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); + assert_eq!(undo_steps(&s), steps, "{scope}"); + } + lock(&mut s, false); + let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);"); + assert_eq!(out, vec![json!(0)]); +} + +/// `removeAll()` on a compound path's `pathItems` deletes its paths and keeps the compound path, +/// empty, as `remove()` on its last path does. +#[test] +fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length, app.activeDocument.compoundPathItems.length]);", + ); + assert_eq!(out, vec![json!(["CompoundPathItem", 0, 1])]); + assert!(s.active().unwrap().doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); + assert_eq!(undo_steps(&s), steps + 1); +} + /// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it /// is runs no command, also in a layer whose ruler guides are above its art. #[test] @@ -2610,7 +2704,1228 @@ fn select_tool_makes_the_named_tool_current_when_the_run_ends() { #[test] fn unsupported_members_say_so() { let (mut s, _, _) = doc(); - assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet")); + assert!(failure(&mut s, "app.activeDocument.swatches;").contains("Document.swatches is not available yet")); +} + +fn layer_names(s: &Session) -> Vec { + s.active().unwrap().doc.layers.iter().rev().map(|n| n.name.clone().unwrap_or_default()).collect() +} + +#[test] +fn layers_list_top_first_and_add_makes_the_new_layer_current() { + let (mut s, a, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers; vc.log(L.length); vc.log(L.typename); vc.log(L.parent.typename);\ + var n = L.add(); n.name = 'Top'; vc.log(L.length); vc.log(L[0].name); vc.log(d.activeLayer.name);\ + vc.log(L.getByName('Top').zOrderPosition); vc.log(L[1].zOrderPosition); vc.log(n.parent.typename);\ + var sub = L[1].layers.add(); sub.name = 'Sub'; vc.log(L[1].layers.length); vc.log(sub.parent.name);\ + vc.log(L.length); vc.log(L[5] === undefined); vc.log(L[1].pageItems.length); vc.log(L[1].pageItems[0].typename);\ + vc.log(sub.zOrderPosition);", + ); + let expected = [json!(1), json!("Layers"), json!("Document"), json!(2), json!("Top"), json!("Top"), json!(2), json!(1), json!("Document")]; + assert_eq!(out[..9], expected); + // A layer's pageItems hold its art, not its sublayers, and a sublayer's zOrderPosition counts + // only the layers beside it. + assert_eq!(out[9..], [json!(1), json!("Layer 1"), json!(2), json!(true), json!(2), json!("PathItem"), json!(1)]); + assert_eq!(layer_names(&s), ["Top", "Layer 1"]); + // One run is one undo step. + assert_eq!(undo_steps(&s), steps + 1); + let lid = s.active().unwrap().doc.layer_containing(a).unwrap(); + assert!(failure(&mut s, "app.activeDocument.layers.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.layers.getByName(5);").contains("give a name")); + assert_eq!(s.active().unwrap().doc.layer_containing(a), Some(lid)); +} + +#[test] +fn a_new_or_assigned_layer_stays_the_current_layer() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, base = d.layers[0];\ + var n = d.layers.add(); n.name = 'New'; vc.log(d.activeLayer.name);\ + d.activeLayer = base; vc.log(d.activeLayer.name);\ + d.activeLayer = n; vc.log(d.activeLayer.name);\ + var sub = base.layers.add(); sub.name = 'Sub'; vc.log(d.activeLayer.name);\ + vc.log(d.selection.length); vc.log(d.selection[0].layer.name);", + ); + assert_eq!(out, [json!("New"), json!("Layer 1"), json!("New"), json!("Sub"), json!(1), json!("Layer 1")]); + // The layer the script made current is still current after the run. + let st = s.active().unwrap(); + let current = st.current_layer().and_then(|l| st.doc.node(l)).and_then(|n| n.name.clone()); + assert_eq!(current.as_deref(), Some("Sub")); +} + +#[test] +fn a_new_layer_or_group_with_a_large_id_is_the_new_one() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The new ids, 2^53 + 1 and 2^53 + 3, are not exact as numbers. + for (id, source) in + [(1, "var l = app.activeDocument.layers.add(); l.name = 'made';"), (3, "var g = app.activeDocument.groupItems.add(); g.name = 'made';")] + { + let big = (1u64 << 53) + id; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + run(&mut s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("made"), "{source}"); + } +} + +#[test] +fn layer_properties_round_trip_and_reject_bad_values() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0];\ + l.name = 'Art'; l.printable = false; l.preview = false; l.opacity = 40; l.dimPlacedImages = true;\ + l.color = {red: 10, green: 20, blue: 30};\ + vc.log(l.name); vc.log(l.printable); vc.log(l.preview); vc.log(l.opacity); vc.log(l.dimPlacedImages);\ + var c = l.color; vc.log([c.red, c.green, c.blue]); vc.log(l.visible); vc.log(l.locked); vc.log(l.typename);\ + l.visible = false; vc.log(l.visible); l.visible = true; l.locked = true; vc.log(l.locked); l.locked = false;", + ); + let expected = [json!("Art"), json!(false), json!(false), json!(40), json!(true), json!([10, 20, 30]), json!(true), json!(false)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!("Layer"), json!(false), json!(true)]); + // Setting the values a layer has adds no undo step. + let steps = undo_steps(&s); + let same = "var l = app.activeDocument.layers[0]; l.name = 'Art'; l.opacity = 40; l.printable = false; l.color = {red: 10, green: 20, blue: 30};"; + run(&mut s, same).unwrap(); + assert_eq!(undo_steps(&s), steps); + let before = format!("{:?}", s.active().unwrap().doc.layers); + for (src, msg) in [ + ("app.activeDocument.layers[0].name = null;", "name must be a string"), + ("app.activeDocument.layers[0].name = {};", "name must be a string"), + ("app.activeDocument.layers[0].name = ' ';", "cannot be empty"), + ("app.activeDocument.layers[0].name = new Array(600).join('x');", "at most 512"), + ("app.activeDocument.layers[0].opacity = 200;", "from 0 to 100"), + ("app.activeDocument.layers[0].opacity = NaN;", "finite number"), + ("app.activeDocument.layers[0].visible = 1;", "true or false"), + ("app.activeDocument.layers[0].color = {red: 300, green: 0, blue: 0};", "color.red"), + ("app.activeDocument.layers[0].color = {red: 1.5, green: 0, blue: 0};", "color.red"), + ("app.activeDocument.layers[0].color = 'red';", "red, green and blue"), + ("app.activeDocument.layers[0].zOrder('up');", "ZOrderMethod"), + ("app.activeDocument.activeLayer = 3;", "not a Layer"), + ] { + assert!(failure(&mut s, src).contains(msg), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn layer_move_and_z_order_keep_ids() { + let (mut s, _, _) = doc(); + run(&mut s, "var L = app.activeDocument.layers; L.add().name = 'B'; L.add().name = 'C';").unwrap(); + assert_eq!(layer_names(&s), ["C", "B", "Layer 1"]); + let out = log( + &mut s, + "var L = app.activeDocument.layers, c = L[0]; c.zOrder(ZOrderMethod.SENDTOBACK); vc.log(L[2].name); vc.log(c.zOrderPosition);\ + c.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(L[1].name);\ + c.move(L.getByName('B'), ElementPlacement.PLACEBEFORE); vc.log(L[0].name);\ + c.move(L.getByName('B')); vc.log(L.length); vc.log(c.parent.name); vc.log(c.name);\ + c.move(app.activeDocument); vc.log(L.length); vc.log(L[0].name);", + ); + assert_eq!(out, [json!("C"), json!(1), json!("C"), json!("C"), json!(2), json!("B"), json!("C"), json!(3), json!("C")]); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move(L[0]);").contains("into itself")); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move(L[1].pageItems);").contains("a layer or a document")); + assert!(failure(&mut s, "var L = app.activeDocument.layers; L[0].move();").contains("relative object")); +} + +#[test] +fn sublayer_z_order_steps_past_the_next_layer_and_the_art_between() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var P = app.activeDocument.layers[0], x = P.layers.add(); x.name = 'X'; x.zOrder(ZOrderMethod.SENDTOBACK);\ + var y = P.layers.add(); y.name = 'Y'; vc.log([x.zOrderPosition, y.zOrderPosition]);\ + y.zOrder(ZOrderMethod.SENDBACKWARD); vc.log([x.zOrderPosition, y.zOrderPosition, P.layers[0].name]);\ + y.zOrder(ZOrderMethod.BRINGFORWARD); vc.log([x.zOrderPosition, y.zOrderPosition, P.layers[0].name]);\ + y.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(P.pageItems.length);", + ); + assert_eq!(out, [json!([1, 2]), json!([2, 1, "X"]), json!([1, 2, "Y"]), json!(2)]); + // The last step had no layer to pass, so Y stayed under the art. + let d = &s.active().unwrap().doc; + let p = d.layers.last().unwrap(); + let kids = d.children(Some(p.id)).unwrap(); + assert!(kids[1].is_layer() && !kids[2].is_layer() && !kids[3].is_layer()); +} + +#[test] +fn removed_layers_throw_and_the_last_layer_stays() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var L = app.activeDocument.layers, n = L.add(); n.layers.add(); n.layers.add(); vc.log(n.layers.length);\ + n.layers.removeAll(); vc.log(n.layers.length); n.remove(); vc.log(L.length);\ + try { n.name; } catch (e) { vc.log(String(e)); }", + ); + assert_eq!(out[..3], [json!(2), json!(0), json!(1)]); + assert!(out[3].as_str().unwrap().contains("Stale layer"), "{out:?}"); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(failure(&mut s, "app.activeDocument.layers[0].remove();").contains("at least one layer")); + assert!(failure(&mut s, "app.activeDocument.layers.removeAll();").contains("at least one layer")); + assert_eq!(s.active().unwrap().doc.layers.len(), 1); + assert!(failure(&mut s, "Object.getOwnPropertyDescriptor(Layer.prototype, 'name').get.call({});").contains("not a Layer")); +} + +#[test] +fn group_items_list_every_depth_and_clipped_toggles_the_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.groupItems[0]; vc.log(d.groupItems.length); vc.log(g.pageItems.length);\ + var inner = g.groupItems.add(); vc.log(inner.typename); vc.log(inner.pageItems.length);\ + vc.log(d.groupItems.length); vc.log(g.groupItems.length); vc.log(d.layers[0].groupItems.length);\ + vc.log(g.layer.name); vc.log(g.clipped); vc.log(d.compoundPathItems.length);\ + d.layers[0].groupItems.add(); vc.log(d.layers[0].groupItems.length); vc.log(g.pageItems.parent.typename);", + ); + let expected = [json!(1), json!(2), json!("GroupItem"), json!(0), json!(2), json!(1), json!(1), json!("Layer 1"), json!(false), json!(0)]; + assert_eq!(out[..10], expected); + assert_eq!(out[10..], [json!(2), json!("GroupItem")]); + // `clipped` on a group with a path on top makes the topmost path its 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 steps = undo_steps(&s); + run(&mut s, "var g = app.activeDocument.layers[0].groupItems[0]; g.clipped = false;").unwrap(); + assert_eq!(undo_steps(&s), steps); + assert_eq!(log(&mut s, "var g = app.activeDocument.layers[0].groupItems[0]; g.clipped = true; vc.log(g.clipped);"), [json!(true)]); + let st = s.active().unwrap(); + let g = st.doc.node(gid).unwrap(); + assert!(g.clips()); + assert_eq!(g.children().unwrap()[0].id, b); + assert_eq!(undo_steps(&s), steps + 1); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].clipped = 'yes';").contains("true or false")); + assert!(failure(&mut s, "app.activeDocument.groupItems.getByName('none');").contains("Not found")); +} + +#[test] +fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The layer holds, bottom to top, the compound path of `a` and the group of `b` (50 pt wide) + // and `c` (70 pt wide). + let out = log( + &mut s, + "var L = app.activeDocument.layers[0], P = L.pageItems, g = L.groupItems[0];\ + vc.log(P[0].typename); vc.log(P[1].typename); vc.log(g.pageItems[0].width); vc.log(g.pageItems[1].width);\ + var e = L.groupItems.add(); e.name = 'E'; vc.log(L.groupItems[0].name); vc.log(L.pageItems[0].name);\ + vc.log(L.compoundPathItems[0].pathItems[0].width);", + ); + assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); +} + +#[test] +fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let red = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems.add(); c.name = 'C'; vc.log(c.typename); vc.log(c.pathItems.length);\ + vc.log(d.compoundPathItems.length); vc.log(c.layer.name);", + ); + assert_eq!(out, [json!("CompoundPathItem"), json!(0), json!(1), json!("Layer 1")]); + assert_eq!(undo_steps(&s), steps + 1); + let cid = { + let d = &s.active().unwrap().doc; + let lid = d.layer_containing(a).unwrap(); + d.node(lid).unwrap().children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap().id + }; + // Paths moved into it become its members, and it takes the paint of the first one. The layer + // lists the new compound path first, then `b`, then `a`. + let source = "var d = app.activeDocument, c = d.compoundPathItems.getByName('C'), L = d.layers[0].pageItems, a = L[2], b = L[1];\ + vc.log(L[0].name); a.move(c, ElementPlacement.PLACEATBEGINNING); b.move(c, ElementPlacement.PLACEATEND);\ + vc.log(c.pathItems.length); vc.log(a.parent.typename); vc.log(b.parent.typename);"; + assert_eq!(log(&mut s, source), [json!("C"), json!(2), json!("CompoundPathItem"), json!("CompoundPathItem")]); + let c = s.active().unwrap().doc.node(cid).unwrap(); + let members: Vec = c.children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(members.len(), 2); + assert!(members.contains(&a) && members.contains(&b)); + assert_eq!(c.appearance, red); + // A group goes neither into a compound path nor beside a path inside one. + let before = format!("{:?}", s.active().unwrap().doc.layers); + for src in [ + "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C'));", + "var d = app.activeDocument, g = d.groupItems.add(); g.move(d.compoundPathItems.getByName('C').pathItems[0], ElementPlacement.PLACEBEFORE);", + "app.activeDocument.compoundPathItems.add().move(app.activeDocument.compoundPathItems.getByName('C'));", + ] { + assert!(failure(&mut s, src).contains("only paths"), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false")); +} + +/// The paint of a compound path's only path is the compound path's: moved into an empty compound +/// path, the path gives it that paint, not its own default one. +#[test] +fn a_path_moved_out_of_a_compound_path_gives_an_empty_one_the_paint_it_was_drawn_with() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let red = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, old = d.compoundPathItems[0], c = d.compoundPathItems.add(); c.name = 'C';\ + old.pathItems[0].move(c); vc.log(d.compoundPathItems.getByName('C').pathItems.length);", + ); + assert_eq!(out, [json!(1)]); + let d = &s.active().unwrap().doc; + let c = d.parent_of(a).and_then(|p| d.node(p)).unwrap(); + assert_eq!(c.name.as_deref(), Some("C")); + assert_eq!(c.appearance, red); + assert_ne!(d.node(a).unwrap().appearance, red); +} + +/// `node.move` into a compound path leaves the path without paint or pixel alignment of its own, +/// as Make Compound Path leaves its paths, and the compound path takes the alignment. +#[test] +fn node_move_into_a_compound_path_clears_the_paths_own_paint() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let painted = s.active().unwrap().doc.node(b).unwrap().appearance.clone(); + let member = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let steps = undo_steps(&s); + s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(b), Some(cid)); + let n = d.node(b).unwrap(); + assert_ne!(n.appearance, painted); + assert_eq!(n.appearance, member); + assert!(!n.extras().pixel_aligned); + assert!(d.node(cid).unwrap().extras().pixel_aligned); +} + +#[test] +fn node_move_refuses_a_guide_and_a_locked_or_hidden_compound_path() { + let (mut s, a, b) = doc(); + let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + assert!(matches!(s.active().unwrap().doc.node(cid).unwrap().kind, NodeKind::Compound { .. })); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let err = s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("only paths"), "{err}"); + for hide in ["object.lock", "object.hide"] { + s.execute("select.set", &json!({"ids": [cid.0]})).unwrap(); + s.execute(hide, &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("hidden or locked"), "{hide}: {err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +/// `node.move` refuses a clip group's clipping path for a compound path and leaves the group +/// clipped as it was; the art the group clips still goes in. +#[test] +fn node_move_refuses_a_clipping_path_for_a_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + let d = &s.active().unwrap().doc; + assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0))); + let (before, steps) = (format!("{:?}", d.layers), undo_steps(&s)); + let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("clipping path"), "{err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(cid)); + assert!(d.node(g).unwrap().clips()); + assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0))); +} + +/// `duplicate(compoundPath)` puts the copy into the compound path; an empty one takes its paint. +#[test] +fn a_path_duplicated_into_an_empty_compound_path_becomes_its_path() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let blue = s.active().unwrap().doc.node(a).unwrap().appearance.clone(); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.compoundPathItems.add(), p = d.layers[0].pageItems[2]; var q = p.duplicate(c);\ + vc.log(c.pathItems.length); vc.log(q.parent.typename); vc.log(p.parent.typename);", + ); + assert_eq!(out, [json!(1), json!("CompoundPathItem"), json!("Layer")]); + let d = &s.active().unwrap().doc; + let lid = d.layer_containing(a).unwrap(); + let c = d.node(lid).unwrap().children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); + assert_eq!(c.appearance, blue); + assert_eq!(d.node(a).unwrap().appearance, blue); + // The copy keeps no paint, live shape or pixel alignment of its own. + let q = &c.children().unwrap()[0]; + assert_ne!(q.appearance, blue); + assert!(matches!(q.kind, NodeKind::Path { live: None, .. })); + assert!(!q.extras().pixel_aligned); +} + +/// A compound path's `pathItems` list its topmost path first. +#[test] +fn a_compound_paths_path_items_list_the_topmost_path_first() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let source = "var P = app.activeDocument.compoundPathItems[0].pathItems; vc.log(P[0].width); vc.log(P[1].width);"; + // `b` (50 pt wide) on top, then `a` (30 pt wide) on top. + s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(log(&mut s, source), [json!(50), json!(30)]); + s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 1})).unwrap(); + assert_eq!(log(&mut s, source), [json!(30), json!(50)]); +} + +/// `index(i)` on a layer's `pageItems` and a compound path's `pathItems` gives the object `[i]` +/// gives, and `Not found` past the end. +#[test] +fn scoped_collections_index_by_number() { + let (mut s, a, b) = doc(); + 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, L = d.layers[0].pageItems, P = d.compoundPathItems[0].pathItems;\ + vc.log(L.index(0).typename); vc.log(P.index(1).width === P[1].width);", + ); + assert_eq!(out, vec![json!("CompoundPathItem"), json!(true)]); + let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems.index(5);"); + assert!(e.contains("Not found"), "{e}"); +} + +#[test] +fn scoped_collection_methods_reject_the_other_collection_class() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for (class, receiver) in + [("PathItems", "app.activeDocument.layers[0].pageItems"), ("PageItems", "app.activeDocument.compoundPathItems[0].pathItems")] + { + for call in ["removeAll.call(r)", "getByName.call(r, '')", "index.call(r, 0)"] { + let source = format!("var r = {receiver}; {class}.prototype.{call};"); + let error = failure(&mut s, &source); + assert!(error.contains(&format!("not a {class}")), "{source}: {error}"); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); + } + for property in ["typename", "length", "parent"] { + let source = format!("Object.getOwnPropertyDescriptor({class}.prototype, '{property}').get.call({receiver});"); + let error = failure(&mut s, &source); + assert!(error.contains(&format!("not a {class}")), "{source}: {error}"); + } + } + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn clear_releases_a_group_after_removing_its_last_compound_mask_member() { + for mode in ["whole", "anchors", "mixed"] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("edit.clear", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let other = rect(&mut s, 200.0, 20.0, 30.0, 40.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + if mode == "anchors" { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]})).unwrap(); + } else if mode == "mixed" { + s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + } + let before = s.active().unwrap().doc.clone(); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + s.execute("edit.clear", &json!({})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(compound).is_none(), "{mode}"); + assert!(d.node(other).is_some(), "{mode}"); + assert!(d.node(group).unwrap().children().unwrap().is_empty(), "{mode}"); + assert!(!d.node(group).unwrap().clips(), "{mode}"); + assert_eq!(undo_steps(&s), steps + 1, "{mode}"); + let after = d.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, before, "{mode}"); + assert_eq!(s.active().unwrap().selection, selection, "{mode}"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc, after, "{mode}"); + } +} + +/// Ruler guides left in a clipped layer do not count as other objects: `removeAll()` deletes the +/// layer's clipping compound path. +#[test] +fn scoped_remove_all_deletes_a_clipping_path_beside_ruler_guides() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let layer = s.active().unwrap().doc.parent_of(cid).unwrap(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + run(&mut s, "app.activeDocument.layers[0].compoundPathItems.removeAll();").unwrap(); + assert!(s.active().unwrap().doc.node(cid).is_none()); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); + let added = rect(&mut s, 200.0, 20.0, 30.0, 40.0); + assert_eq!(s.active().unwrap().doc.parent_of(added), Some(layer)); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(cid).is_some()); + assert!(s.active().unwrap().doc.node(layer).unwrap().clips()); + s.execute("edit.redo", &json!({})).unwrap(); + rect(&mut s, 200.0, 20.0, 30.0, 40.0); + assert!(!s.active().unwrap().doc.node(layer).unwrap().clips()); +} + +#[test] +fn scoped_remove_all_releases_an_empty_clipping_group_in_one_step() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let steps = undo_steps(&s); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);"); + assert_eq!(out, [json!(false), json!(0)]); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.pageItems.length);"); + assert_eq!(out, [json!(true), json!(2)]); +} + +#[test] +fn clipped_setter_refuses_locked_artboards_layers_and_groups() { + for target in ["artboard", "layer", "group"] { + for clipped in [false, true] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + if clipped { + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + } + let layer = s.active().unwrap().doc.layer_containing(NodeId(g)).unwrap(); + s.edit("Lock", |d, _| { + match target { + "artboard" => d.artboards[0].locked = true, + "layer" => d.node_mut(layer).unwrap().locked = true, + _ => d.node_mut(NodeId(g)).unwrap().locked = true, + } + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let src = format!( + "var g = app.activeDocument.groupItems[0]; try {{ g.clipped = {}; vc.log('changed'); }} catch (e) {{ vc.log(e.message); }} vc.log(g.clipped);", + !clipped + ); + let out = log(&mut s, &src); + assert!(out[0].as_str().unwrap().contains("locked"), "{target}: {out:?}"); + assert_eq!(out[1], json!(clipped)); + assert_eq!(undo_steps(&s), steps); + } + } +} + +#[test] +fn scoped_collections_convert_to_strings() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0], g = l.groupItems.add(), c = g.compoundPathItems.add();\ + var lists = [l.pageItems, g.pageItems, l.layers, l.groupItems, g.groupItems, l.compoundPathItems, g.compoundPathItems, c.pathItems];\ + for (var i = 0; i < lists.length; i++) { vc.log(String(lists[i])); vc.log(lists[i].toString()); }", + ); + let expected: Vec<_> = ["PageItems", "PageItems", "Layers", "GroupItems", "GroupItems", "CompoundPathItems", "CompoundPathItems", "PathItems"] + .into_iter() + .flat_map(|name| [json!(format!("[{name}]")), json!(format!("[{name}]"))]) + .collect(); + assert_eq!(out, expected); +} + +#[test] +fn layer_color_can_be_assigned_to_path_paint() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0]; l.color = {red: 10, green: 20, blue: 30};\ + var c = l.color; vc.log(c.typename); var p = l.pageItems[0]; p.fillColor = c;\ + vc.log([p.fillColor.red, p.fillColor.green, p.fillColor.blue]);", + ); + assert_eq!(out, [json!("RGBColor"), json!([10, 20, 30])]); +} + +/// `removeAll()` refuses to delete the compound path that clips a group while the group keeps +/// other art, and deletes nothing. +#[test] +fn scoped_remove_all_refuses_a_clipping_compound_path() { + let (mut s, a, b) = doc(); + let e = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.arrange.bringToFront", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [cid.0, e.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let steps = undo_steps(&s); + let err = failure(&mut s, "app.activeDocument.groupItems[0].compoundPathItems.removeAll();"); + assert!(err.contains("clipping"), "{err}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); +} + +/// A path that leaves a compound path for a layer is drawn as it was: it takes the compound +/// path's paint and pixel alignment, as Release Compound Path gives them. +#[test] +fn a_path_moved_out_of_a_compound_path_keeps_the_paint_it_was_drawn_with() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let (cid, red, lid) = { + let d = &s.active().unwrap().doc; + let cid = d.parent_of(a).unwrap(); + (cid, d.node(cid).unwrap().appearance.clone(), d.layer_containing(a).unwrap()) + }; + assert_ne!(s.active().unwrap().doc.node(a).unwrap().appearance, red); + s.execute("node.move", &json!({"id": a.0, "parent": lid.0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(lid)); + let n = d.node(a).unwrap(); + assert_eq!(n.appearance, red); + assert!(n.extras().pixel_aligned); + // The path left behind keeps none of its own. + assert_eq!(d.parent_of(b), Some(cid)); + assert_ne!(d.node(b).unwrap().appearance, red); +} + +/// A path that leaves a pixel-aligned compound path for another compound path makes that one +/// pixel-aligned, as it gives it the paint it was drawn with. +#[test] +fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(a).unwrap().extras().pixel_aligned); + let to = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap()); + assert!(!s.active().unwrap().doc.node(to).unwrap().extras().pixel_aligned); + s.execute("node.move", &json!({"id": a.0, "parent": to.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(a), Some(to)); + assert!(d.node(to).unwrap().extras().pixel_aligned); + assert!(!d.node(a).unwrap().extras().pixel_aligned); +} + +/// A path off the pixel grid that moves into a pixel-aligned compound path is snapped to the grid +/// with the compound path's other paths. +#[test] +fn a_path_moved_into_a_pixel_aligned_compound_path_is_snapped() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let to = s.active().unwrap().doc.parent_of(a).unwrap(); + let r = rect(&mut s, 200.3, 100.3, 20.4, 20.4); + s.execute("object.setPixelAligned", &json!({"ids": [r.0], "on": false})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(r).unwrap().extras().pixel_aligned); + let before = s.active().unwrap().doc.bounds_of(&[r], false).unwrap(); + assert!(before.x0.fract().abs() > 0.01, "{before:?}"); + s.execute("node.move", &json!({"id": r.0, "parent": to.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(to).unwrap().extras().pixel_aligned); + let after = d.bounds_of(&[r], false).unwrap(); + assert_ne!(after, before); + assert!(!d.node(r).unwrap().extras().pixel_aligned); + assert!([after.x0, after.y0, after.x1, after.y1].iter().all(|v| (v * 2.0).fract().abs() < 1e-9), "not snapped: {after:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.bounds_of(&[r], false).unwrap(), before); +} + +#[test] +fn a_compound_paths_path_items_are_path_items() { + let (mut s, a, b) = doc(); + 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, p = d.compoundPathItems[0].pathItems; vc.log(p.typename); vc.log(p.length);\ + vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename); vc.log(p instanceof PathItems);\ + vc.log(p instanceof PageItems); vc.log(p.parent === d.compoundPathItems[0]);\ + p[0].name = 'member'; vc.log(p.getByName('member') === p[0]); vc.log(p.index(0) === p[0]);", + ); + assert_eq!( + out, + [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems"), json!(true), json!(false), json!(true), json!(true), json!(true)] + ); + for call in ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] { + let source = format!( + "var p = app.activeDocument.compoundPathItems[0].pathItems; try {{ p.{call}; vc.log('made'); }} catch (e) {{ vc.log(e.message); }} vc.log(p.length);" + ); + let out = log(&mut s, &source); + assert!(out[0].as_str().unwrap().contains("not available yet"), "{call}: {out:?}"); + assert_eq!(out[1], json!(2)); + } + run(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length);").unwrap(); + assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none()); +} + +#[test] +fn art_collections_follow_edits_between_reads() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.groupItems; vc.log(p.length); vc.log(g.length);\ + d.layers[0].groupItems.add(); vc.log(p.length); vc.log(p[0].typename); vc.log(g.length);\ + p[0].remove(); vc.log(p.length); vc.log(p[0].typename);", + ); + assert_eq!(out, [json!(2), json!(0), json!(3), json!("GroupItem"), json!(1), json!(2), json!("PathItem")]); +} + +#[test] +fn a_loop_over_groups_and_their_items_lists_each_collection_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..5 { + let x = f64::from(i) * 20.0; + let (a, b) = (rect(&mut s, x, 0.0, 10.0, 10.0), rect(&mut s, x, 20.0, 10.0, 10.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + } + // Both scripts make the same calls. The first reads the groups and each group's items in + // turn; the second reads every group before any group's items, so it builds each list once. + let nested = "var gs = app.activeDocument.groupItems, n = 0;\ + for (var i = 0; i < gs.length; i++) { var p = gs[i].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + let in_order = "var gs = app.activeDocument.groupItems, all = [], n = 0;\ + for (var i = 0; i < gs.length; i++) { all.push(gs[i]); }\ + for (var k = 0; k < all.length; k++) { var p = all[k].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\ + vc.log(n);"; + crate::script::dom::ART_SCANS.with(|c| c.set(0)); + let a = run(&mut s, nested).unwrap(); + // The groups' list and each group's list are built once: 1 + 5 lists. + let scans = crate::script::dom::ART_SCANS.with(std::cell::Cell::get); + assert!(scans <= 6, "{scans} lists built for 5 groups"); + let b = run(&mut s, in_order).unwrap(); + assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); + assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); +} + +/// 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] +fn a_loop_over_layers_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, n = 0; for (var i = 0; i < L.length; i++) { L[i]; n++; } vc.log(n);"); + assert_eq!(out, vec![json!(n)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); +} + +/// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the +/// document's `pageItems`, also when the list was already built. +#[test] +fn scoped_name_searches_are_charged_each_time() { + let (mut s, ..) = doc(); + let calls = |s: &mut Session, list: &str, k: usize| { + let source = format!("var p = {list}; p.length; for (var i = 0; i < {k}; i++) {{ try {{ p.getByName('none'); }} catch (e) {{}} }}"); + run(s, &source).unwrap()["hostCalls"].as_u64().unwrap() + }; + let doc_cost = calls(&mut s, "app.activeDocument.pageItems", 6) - calls(&mut s, "app.activeDocument.pageItems", 1); + let layer_cost = calls(&mut s, "app.activeDocument.layers[0].pageItems", 6) - calls(&mut s, "app.activeDocument.layers[0].pageItems", 1); + assert_eq!(layer_cost, doc_cost); +} + +#[test] +fn layer_z_order_scans_are_charged_each_time() { + let (mut s, ..) = doc(); + let repeated = "var l = app.activeDocument.layers[0]; for (var i = 0; i < 512; i++) l.zOrderPosition;"; + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let small = run(&mut s, repeated); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + small.unwrap(); + for _ in 0..100 { + s.execute("layer.new", &json!({})).unwrap(); + } + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let once = run(&mut s, "var l = app.activeDocument.layers[0]; l.zOrderPosition;"); + let large = run(&mut s, repeated); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + once.unwrap(); + let error = large.unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +#[test] +fn has_selected_artwork_keeps_selected_objects_in_other_layers() { + let (mut s, a, b) = doc(); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0, other.0]})).unwrap(); + for (operation, a_selected, b_selected) in + [("vc.log(l.hasSelectedArtwork)", true, false), ("l.hasSelectedArtwork = false", false, false), ("l.hasSelectedArtwork = true", true, true)] + { + let source = format!("var l = app.activeDocument.layers.getByName('Layer 1'); {operation};"); + run(&mut s, &source).unwrap(); + assert!(s.active().unwrap().selection.objects.contains(&other), "{operation}"); + let selected = &s.active().unwrap().selection.objects; + assert_eq!((selected.contains(&a), selected.contains(&b)), (a_selected, b_selected), "{operation}"); + } +} + +#[test] +fn group_items_remove_all_refuses_locked_groups() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"ids": [g], "locked": true})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems.removeAll();").contains("hidden or locked")); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("object.setProps", &json!({"ids": [g], "locked": false})).unwrap(); + run(&mut s, "app.activeDocument.groupItems.removeAll();").unwrap(); + let d = &s.active().unwrap().doc; + assert!(d.node(NodeId(g)).is_none() && d.node(a).is_none() && d.node(b).is_some()); +} + +#[test] +fn new_group_command_checks_its_parent() { + let (mut s, a, _) = doc(); + let layer = s.active().unwrap().doc.layer_containing(a).unwrap(); + let g = s.execute("object.newGroup", &json!({"parent": layer.0, "index": 0})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.position(NodeId(g)).map(|(p, i, _)| (p, i)), Some((Some(layer), 0))); + assert!(s.execute("object.newGroup", &json!({"parent": a.0})).unwrap_err().to_string().contains("not a layer or group")); + assert!(s.execute("object.newGroup", &json!({"parent": 999_999})).unwrap_err().to_string().contains("no layer or group")); + assert!(s.execute("object.newGroup", &json!({"parent": "x"})).unwrap_err().to_string().contains("parent must be")); + assert!(s.execute("object.newGroup", &json!({"index": -1})).unwrap_err().to_string().contains("index must be")); + let before = format!("{:?}", s.active().unwrap().doc.layers); + assert!(s.execute("object.newGroup", &json!({"parent": null})).unwrap_err().to_string().contains("parent must be")); + assert!(s.execute("object.newGroup", &json!({"index": null})).unwrap_err().to_string().contains("index must be")); + assert!(s.execute("object.newGroup", &json!({"compound": null})).unwrap_err().to_string().contains("compound must be")); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + assert!(s.execute("object.newGroup", &json!({"parent": layer.0})).unwrap_err().to_string().contains("hidden or locked")); +} + +#[test] +fn artboards_add_insert_rename_and_remove() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(A.length); vc.log(A[0].artboardRect); vc.log(A.typename);\ + var b = A.add([500, 300, 700, 100]); b.name = 'Two'; vc.log(A.length); vc.log(A[1].name); vc.log(b.artboardRect);\ + A.insert([0, -100, 100, -200], 1); vc.log(A[1].artboardRect); vc.log(b.name); vc.log(A.getByName('Two').artboardRect[0]);\ + b.artboardRect = [500, 300, 650, 150]; vc.log(b.artboardRect); b.rulerPAR = 2; vc.log(b.rulerPAR);\ + b.showCenter = true; b.showCrossHairs = true; b.showSafeAreas = true; vc.log([b.showCenter, b.showCrossHairs, b.showSafeAreas]);\ + b.rulerOrigin = [10, 20]; vc.log(b.rulerOrigin); vc.log(b.parent.typename);\ + A.remove(0); vc.log(A.length); b.remove(); vc.log(A.length); try { b.name; } catch (e) { vc.log(String(e)); }", + ); + assert_eq!(out[..4], [json!(1), json!([0, 300, 400, 0]), json!("Artboards"), json!(2)]); + assert_eq!(out[4..7], [json!("Two"), json!([500, 300, 700, 100]), json!([0, -100, 100, -200])]); + assert_eq!(out[7..11], [json!("Two"), json!(500), json!([500, 300, 650, 150]), json!(2)]); + assert_eq!(out[11..16], [json!([true, true, true]), json!([10, 20]), json!("Document"), json!(2), json!(1)]); + assert!(out[16].as_str().unwrap().contains("Stale artboard"), "{out:?}"); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); +} + +#[test] +fn new_artboards_get_a_name_no_other_artboard_has() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A[0].name = 'Artboard 2';\ + vc.log(A.add([500, 300, 700, 100]).name); A.insert([0, -100, 100, -200], 0); vc.log(A[0].name);\ + vc.log(A.add([800, 300, 900, 100]).name);", + ); + assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); +} + +#[test] +fn names_take_numbers_and_booleans() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers[0];\ + L.name = 5; vc.log(L.name); vc.log(typeof L.name); L.name = 1.5; vc.log(L.name); L.name = true; vc.log(L.name);\ + d.artboards[0].name = 7; vc.log(d.artboards[0].name); vc.log(typeof d.artboards[0].name);", + ); + assert_eq!(out, [json!("5"), json!("string"), json!("1.5"), json!("true"), json!("7"), json!("string")]); +} + +#[test] +fn an_empty_artboard_name_gives_the_default_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]);\ + A[0].name = 'Front'; A[1].name = 'Back'; A[0].name = ''; A[1].name = ' ';\ + vc.log([A[0].name, A[1].name]);", + ); + assert_eq!(out, [json!(["Artboard 1", "Artboard 2"])]); +} + +#[test] +fn two_artboards_may_share_a_name() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]);\ + A[1].name = 'Same'; A[0].name = 'Same'; vc.log([A[0].name, A[1].name]); vc.log(A.getByName('Same').artboardRect[0]);", + ); + assert_eq!(out, [json!(["Same", "Same"]), json!(0)]); + let names: Vec = s.active().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect(); + assert_eq!(names, ["Same", "Same"]); +} + +#[test] +fn artboards_reject_bad_arguments_before_any_change() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]).name = 'Two';").unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.artboards); + let steps = undo_steps(&s); + for (src, msg) in [ + ("app.activeDocument.artboards.add([0, 0, 10]);", "four numbers"), + ("app.activeDocument.artboards.add('x');", "four numbers"), + ("app.activeDocument.artboards.add([10, 0, 0, 10]);", "right side"), + ("app.activeDocument.artboards.add([0, 0, NaN, -10]);", "finite number"), + ("app.activeDocument.artboards.add([0, 0, 1e300, -10]);", "outside the canvas"), + ("app.activeDocument.artboards.add([0, 0, 0.5, -10]);", "at least 1 point"), + ("app.activeDocument.artboards[0].artboardRect = [0, 0, 10, -0.25];", "at least 1 point"), + ("app.activeDocument.artboards.insert([0, 0, 10, -10], 5);", "index must be"), + ("app.activeDocument.artboards.insert([0, 0, 10, -10]);", "needs an index"), + ("app.activeDocument.artboards.remove(2);", "index must be"), + ("app.activeDocument.artboards.remove(-1);", "index must be"), + ("app.activeDocument.artboards[0].name = null;", "must be a string"), + ("app.activeDocument.artboards[0].name = new Array(5000).join('x');", "too long"), + ("app.activeDocument.artboards[0].rulerPAR = 20;", "from 0.1 to 10"), + ("app.activeDocument.artboards[0].showCenter = 'on';", "true or false"), + ("app.activeDocument.artboards.setActiveArtboardIndex(9);", "index must be"), + ("app.activeDocument.artboards.getByName('none');", "Not found"), + ] { + assert!(failure(&mut s, src).contains(msg), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.artboards), before); + assert_eq!(undo_steps(&s), steps); + run(&mut s, "app.activeDocument.artboards.remove(1);").unwrap(); + assert!(failure(&mut s, "app.activeDocument.artboards[0].remove();").to_lowercase().contains("artboard")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); +} + +#[test] +fn set_active_artboard_index_is_reported_without_an_undo_step() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]);").unwrap(); + let steps = undo_steps(&s); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(1); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert_eq!(st.active_artboard, Some(st.doc.artboards[1].id)); + // Artboard coordinates follow the active artboard. + let out = log(&mut s, "app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; vc.log(app.activeDocument.artboards[1].artboardRect);"); + assert_eq!(out, [json!([0, 0, 200, 200])]); + let r = run(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1);").unwrap(); + assert!(r.get("activeArtboards").is_none()); +} + +/// Choosing the artboard that is active only by default keeps that artboard: one inserted before it +/// moves it to the next index, and the report gives that index. +#[test] +fn choosing_the_default_active_artboard_keeps_it_when_one_is_inserted_before() { + let (mut s, _, _) = doc(); + assert_eq!(s.active().unwrap().active_artboard, None); + let first = s.active().unwrap().doc.artboards[0].id; + let r = run( + &mut s, + "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex());", + ) + .unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + assert_eq!(s.active().unwrap().active_artboard, Some(first)); +} + +/// In a document the run makes, choosing artboard 0 and then inserting one before it still puts +/// the document in the report. +#[test] +fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() { + let (mut s, _, _) = doc(); + let r = run( + &mut s, + "var d = app.documents.add(); var A = d.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\ + vc.log(A.getActiveArtboardIndex());", + ) + .unwrap(); + assert_eq!(r["log"], json!([1])); + let list = r["activeArtboards"].as_array().cloned().unwrap_or_default(); + assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}"); +} + +/// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard. +#[test] +fn artboards_insert_returns_nothing() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(typeof A.insert([0, -100, 100, -200], 0)); vc.log(A.add([500, 300, 700, 100]).typename);", + ); + assert_eq!(out, [json!("undefined"), json!("Artboard")]); +} + +/// The collections' `index` is described as giving an element, and `toString` of a collection +/// whose container is gone fails as `typename` does. +#[test] +fn collection_index_reflection_and_stale_to_string() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument; vc.log([d.layers.reflect.find('index').dataType, d.groupItems.reflect.find('index').dataType,\ + d.compoundPathItems.reflect.find('index').dataType, d.artboards.reflect.find('index').dataType]);", + ); + assert_eq!(out, [json!(["Layer", "GroupItem", "CompoundPathItem", "Artboard"])]); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let live = log(&mut s, "vc.log(app.activeDocument.groupItems[0].groupItems.toString()); vc.log(app.activeDocument.layers[0].layers.toString());"); + assert_eq!(live, [json!("[GroupItems]"), json!("[Layers]")]); + let source = "var g = app.activeDocument.groupItems[0]; var c = g.groupItems; g.remove(); c.toString();"; + let error = failure(&mut s, source); + assert!(error.contains("Stale page item"), "{error}"); + let source = "var l = app.activeDocument.layers.add(); var c = l.layers; l.remove(); c.toString();"; + let error = failure(&mut s, source); + assert!(error.contains("Stale layer"), "{error}"); +} + +/// Setting `hasSelectedArtwork = true` on a layer whose art is all selected runs no command but +/// is still charged for the art it looks at. +#[test] +fn has_selected_artwork_charges_the_walk_when_nothing_is_added() { + // `locked`: the art is locked, so nothing is selectable; otherwise it is all selected. + let repeated = |n: usize, locked: bool| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + if locked { + s.execute("object.setProps", &json!({"ids": ids, "locked": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + } + let steps = undo_steps(&s); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = true;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(undo_steps(&s), steps); + r + }; + for locked in [false, true] { + repeated(1, locked).unwrap(); + let error = repeated(200, locked).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{locked}: {error}"); + } + // `false` on an empty layer is charged for the selection held in another layer, which stays. + let deselect = |n: usize| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect(); + s.execute("layer.new", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13))); + let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = false;"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(s.active().unwrap().selection.objects.len(), n); + r + }; + deselect(1).unwrap(); + let error = deselect(200).unwrap_err().to_string(); + assert!(error.contains("passed more data"), "{error}"); +} + +#[test] +fn the_report_gives_the_active_artboard_the_run_leaves() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.add([800, 300, 900, 100]);").unwrap(); + // The chosen artboard is deleted later in the run: the report gives the one active at the end. + let r = + run(&mut s, "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(2); A.remove(2); vc.log(A.getActiveArtboardIndex());").unwrap(); + let active = r["log"][0].clone(); + assert!(active.as_u64().is_some_and(|i| i < 2), "{r}"); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": active}])); +} + +#[test] +fn the_report_gives_the_active_artboards_new_index_after_an_insert_or_remove() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; A.add([500, 300, 700, 100]); A.setActiveArtboardIndex(1);").unwrap(); + // An artboard inserted or removed before the active one moves it to another index. + let r = run(&mut s, "var A = app.activeDocument.artboards; A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([2])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 2}])); + let r = run(&mut s, "var A = app.activeDocument.artboards; A.remove(0); vc.log(A.getActiveArtboardIndex());").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}])); + // One added after it leaves its index as it was. + let r = run(&mut s, "app.activeDocument.artboards.add([1000, 300, 1100, 100]);").unwrap(); + assert!(r.get("activeArtboards").is_none(), "{r}"); +} + +#[test] +fn an_artboard_rectangle_stays_inside_the_canvas() { + let (mut s, _, _) = doc(); + let before = format!("{:?}", s.active().unwrap().doc.artboards); + let steps = undo_steps(&s); + // Each number is within the coordinate range, but the right edge is past the canvas. + for src in [ + "app.activeDocument.artboards[0].artboardRect = [3999950, 0, 4000100, -100];", + "app.activeDocument.artboards.add([-4000100, 0, -3999950, -100]);", + "app.activeDocument.artboards.insert([0, 4000600, 100, 4000500], 0);", + ] { + assert!(failure(&mut s, src).contains("outside the canvas"), "{src}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.artboards), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn has_selected_artwork_selects_and_deselects_a_layers_art() { + let (mut s, a, b) = doc(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var l = app.activeDocument.layers[0]; vc.log(l.hasSelectedArtwork); l.hasSelectedArtwork = true;\ + vc.log(app.activeDocument.selection.length); vc.log(l.hasSelectedArtwork); vc.log(l.isIsolated);", + ); + assert_eq!(out, [json!(false), json!(2), json!(true), json!(false)]); + let sel = &s.active().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b)); + run(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = false;").unwrap(); + assert!(s.active().unwrap().selection.objects.is_empty()); + assert!(failure(&mut s, "app.activeDocument.layers[0].hasSelectedArtwork = 0;").contains("true or false")); +} + +#[test] +fn has_selected_artwork_keeps_the_rest_of_the_selection() { + let (mut s, a, b) = doc(); + s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + // An empty layer has nothing to deselect or add: the selected guide stays. + let steps = undo_steps(&s); + run(&mut s, "var l = app.activeDocument.layers.add(); l.hasSelectedArtwork = false; l.hasSelectedArtwork = true;").unwrap(); + assert_eq!(s.active().unwrap().selection.guides.len(), 1); + assert_eq!(undo_steps(&s), steps + 1); + // Deselecting a layer's art leaves the guide selected, and so does adding it. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = false;").unwrap(); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.len(), sel.guides.len()), (0, 1)); + run(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").unwrap(); + let sel = &s.active().unwrap().selection; + assert!(sel.objects.contains(&a) && sel.objects.contains(&b)); + assert_eq!(sel.guides.len(), 1); +} + +/// The selection limit counts only the art an assignment would add: a layer with nothing to add +/// changes nothing beside a selection already at the limit, and one with art to add throws. +#[test] +fn has_selected_artwork_checks_the_limit_only_for_art_it_adds() { + let (mut s, a, _) = doc(); + run(&mut s, "app.activeDocument.layers.add();").unwrap(); + // A selection of 10,001 entries, as the limit counts them. + s.active_mut().unwrap().selection.objects = vec![a; 10_001]; + run(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(s.active().unwrap().selection.objects.len(), 10_001); + s.active_mut().unwrap().selection.objects = vec![a; 10_000]; + let e = failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;"); + assert!(e.contains("at most 10000"), "{e}"); +} + +#[test] +fn artboards_stop_at_one_hundred() { + let (mut s, _, _) = doc(); + run(&mut s, "var A = app.activeDocument.artboards; for (var i = 1; i < 100; i++) A.add([i * 10, -400, i * 10 + 5, -405]);").unwrap(); + assert_eq!(s.active().unwrap().doc.artboards.len(), 100); + let steps = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.artboards.add([0, -500, 10, -510]);").contains("at most 100 artboards")); + assert!(failure(&mut s, "app.activeDocument.artboards.insert([0, -500, 10, -510], 0);").contains("at most 100 artboards")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 100); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn every_page_item_has_its_layer_and_members_check_this() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\ + vc.log(p.layer.name); vc.log(d.pageItems[d.pageItems.length - 1].layer.name); vc.log(p.layer.layers.typename);\ + vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);", + ); + assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]); + for src in [ + "Object.getOwnPropertyDescriptor(Layers.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(GroupItems.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Artboard.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Artboards.prototype, 'typename').get.call({});", + "Object.getOwnPropertyDescriptor(Layer.prototype, 'pathItems').get.call({});", + ] { + assert!(failure(&mut s, src).contains("this is not a"), "{src}"); + } + let stale = "var L = app.activeDocument.layers, n = L.add(), c = n.layers, g = n.groupItems; n.remove();"; + for read in ["c.typename", "g.typename", "n.pathItems"] { + assert!(failure(&mut s, &format!("{stale} {read};")).contains("Stale"), "{read}"); + } } /// A script that names each visible selected object after its place in `app.selection`, testing @@ -2702,7 +4017,7 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('swatches'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 60483c1eb8..9a6b736535 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -96,10 +96,11 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ - DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PlacedItem \ - PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \ + "activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \ + CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ + DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \ + GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \ + PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \ selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod", ), ("Application.", "prototype"), @@ -128,14 +129,14 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= characterStyles close constructor convertCoordinate \ + "activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \ defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \ defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \ defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \ defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \ defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \ - groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems placedItems rasterItems \ - rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \ + height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \ + rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \ symbols symbols= tags textFrames toString typename views width", ), ("Views.", "prototype"), @@ -143,15 +144,48 @@ const INSIDE: &[(&str, &str)] = &[ ("View.", "prototype"), ("View.prototype.", "bounds centerPoint centerPoint= constructor parent screenMode screenMode= toString typename zoom zoom="), ("Layer.", "prototype"), - ("Layer.prototype.", "constructor name toString typename"), + ( + "Layer.prototype.", + "artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \ + dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ + locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ + preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ + textFrames= toString typename visible visible= zOrder zOrderPosition", + ), + ("Layers.", "prototype"), + ("Layers.prototype.", "add constructor getByName index length parent removeAll toString typename"), + ("GroupItem.", "prototype"), + ( + "GroupItem.prototype.", + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", + ), + ("GroupItems.", "prototype"), + ("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll toString typename"), + ("CompoundPathItem.", "prototype"), + ("CompoundPathItem.prototype.", "constructor pathItems"), + ("CompoundPathItems.", "prototype"), + ("CompoundPathItems.prototype.", "add constructor getByName index length parent removeAll toString typename"), + ("Artboard.", "prototype"), + ( + "Artboard.prototype.", + "artboardRect artboardRect= constructor name name= parent remove rulerOrigin rulerOrigin= rulerPAR rulerPAR= \ + showCenter showCenter= showCrossHairs showCrossHairs= showSafeAreas showSafeAreas= toString typename", + ), + ("Artboards.", "prototype"), + ( + "Artboards.prototype.", + "add constructor getActiveArtboardIndex getByName index insert length parent remove setActiveArtboardIndex \ + toString typename", + ), ("PageItems.", "prototype"), ("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"), ("PageItem.", "prototype"), ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ - left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ + controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer left \ + left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ position= remove resize rotate selected selected= sliced sliced= tags toString top top= transform translate \ typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", @@ -188,7 +222,10 @@ const INSIDE: &[(&str, &str)] = &[ viewVector=", ), ("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.", @@ -520,12 +557,10 @@ const INSIDE: &[(&str, &str)] = &[ ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types -/// other than `PathItem`, `PlacedItem` and `RasterItem`, the color classes and the save and export -/// option classes. -const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \ - IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem \ - cmykColor EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \ - PDFSaveOptions"; +/// that have no members of their own, the color classes, and the save and export option classes. +const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \ + MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \ + EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 669ae7caef..44ad23caee 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -997,6 +997,15 @@ fn a_host_class_constructor_called_with_new_cannot_wait() { assert_eq!(could.get(), Some(false)); } +#[test] +fn a_host_class_constructor_called_with_new_cannot_give_a_primitive() { + let mut r = realm(1_000_000); + let make: HostFunction = Rc::new(|_| Ok(Data::Number(7.0))); + with_thing(&mut r, Some(make)); + r.start("var r; try { r = new Thing(); } catch (e) { r = e instanceof TypeError; } r").unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true)); +} + #[test] fn new_on_a_host_constructor_that_gives_a_value_other_than_an_object_throws() { let mut r = realm(1_000_000); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 0c3b996aa7..74ceaab6b6 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -60,6 +60,7 @@ pub fn poll(app: &mut VectorcraftApp) { script_run::forget::(app); script_run::settle_close(app); script_window::sync(app); + let boards = result.as_ref().ok().and_then(|r| r["activeArtboards"].as_array().cloned()).unwrap_or_default(); match result { // The commands it ran are journaled now: a recording they no longer fit in names its limit. Ok(report) => { @@ -88,6 +89,29 @@ pub fn poll(app: &mut VectorcraftApp) { } startup_failures(app); app.sync_views(); + show_artboards(app, &boards); +} + +/// Makes each artboard a run's `setActiveArtboardIndex` chose the active one of its document's view +/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). The end of a run +/// starts the tool afresh, so the Artboard tool then takes the active document's active artboard as +/// its only selected one, as choosing it in the Artboards panel does. +fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) { + for b in boards { + let index = |k: &str| b[k].as_u64().and_then(|i| usize::try_from(i).ok()); + let (Some(doc), Some(board)) = (index("document"), index("artboard")) else { continue }; + let count = app.session.documents().get(doc).map_or(0, |d| d.doc.artboards.len()); + if let Some(view) = app.views.get_mut(doc) + && board < count + { + view.artboard = board; + } + } + if app.session.tool_id() == "artboard" + && let Some(n) = app.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0) + { + crate::panels::artboards::select(app, crate::panels::artboards::selected(app, n)); + } } /// The running script reads each drawn window in `Document.views`, with its last drawn area. diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 1cb41bd2f0..8eadbbaf70 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -217,6 +217,36 @@ fn stop_puts_the_document_back_and_says_so() { assert_eq!(app.ui.status, "The script was stopped and its changes were undone"); } +#[test] +fn set_active_artboard_index_shows_the_artboard_in_the_view() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.views[0].artboard = 0; + let source = "app.activeDocument.artboards.setActiveArtboardIndex(1);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.views[0].artboard, 1); +} + +#[test] +fn the_artboard_tool_follows_the_artboard_a_script_makes_active() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.run("artboard.new", json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap(); + app.select_tool("artboard"); + crate::panels::artboards::select(&mut app, 2); + // A run starts the tool afresh; it keeps the view's active artboard, then the one the script chose. + for (source, active) in [("vc.log(1);", 2), ("app.activeDocument.artboards.setActiveArtboardIndex(1);", 1)] { + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + finish(&mut app); + assert_eq!(app.views[0].artboard, active, "{source}"); + assert_eq!(app.session.tool_options()["active"], json!(active), "{source}"); + assert_eq!(app.session.tool_options()["selected"], json!([active]), "{source}"); + } +} + #[test] fn a_canceled_pick_does_not_take_a_dropped_script() { let mut app = app(); diff --git a/docs/gaps.md b/docs/gaps.md index 3a0f88a1a0..fdf8eb1dcc 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -857,9 +857,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, gradient stops and the other classes) - and the `#engine` script directive (#1183 is open). Scripts have `app`, the open - documents, new documents, each document's selection and its page items, its text frames with their text ranges and +- **Missing:** the rest of the document object model for scripts (gradient stops and the other classes) and the + `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's + selection, its page items, layers, groups, compound paths and artboards, its text frames with their text ranges and character and paragraph attributes, their links to each other and the stories they form, its character and paragraph styles, the installed fonts, each document's variables, data sets and variable libraries, and its linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, diff --git a/docs/mcp.md b/docs/mcp.md index 8507629dc6..90aefa32ce 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3133,9 +3133,9 @@ through `$`: `transform` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move` unless the object is already in the place it names. `duplicate` runs `edit.duplicate`, and with a relative object it then runs `node.move` on the copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same - document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a - group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` - directly below it. A move that leaves the object where it is runs no command. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the + document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's, a + group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE` + directly above the relative object and `PLACEAFTER` directly below it. A move that leaves the object where it is runs no command. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the @@ -3215,10 +3215,12 @@ through `$`: a position only (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` take a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, - `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). + `[Layer ]`, `[Artboard ]`, `[Application]`, `[PageItems]`, `[Layers]`, `[GroupItems]`, + `[CompoundPathItems]` and `[Artboards]` (VectorCraft's own rule). `documents[0]` is always the active document, as the same page says. VectorCraft's own rules: the other documents follow from the one active most recently to the one active longest ago, and a change a script - makes to a document in the back does not move it in the list; page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides. A document's + makes to a document in the back does not move it in the list; page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides (the layers + paragraph below gives the order of a layer's, a group's and a compound path's lists). A document's `selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates are points with Y up from the bottom-left corner of the first artboard, or, with `CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename` @@ -3228,7 +3230,12 @@ through `$`: tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was deleted, that a named engine kept from an earlier run, or whose document was reverted with `file.revert`, throws - `Stale page item`. Layer objects also become stale after their document is reverted. `remove()` on an object that + `Stale page item`. Layer objects also become stale after their document is reverted, and so do the `pageItems`, + `groupItems` and `compoundPathItems` of a layer or group, the `pathItems` of a compound path (`Stale page item`) + and `Artboard` objects (`Stale artboard`); the document's own collections list the reverted document. + `removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's + `groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group + or layer that keeps other objects. `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. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` @@ -3248,7 +3255,7 @@ through `$`: `..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined` and does not change the documents or add an undo step. In the app, the documents are drawn as they were before the run until the run ends, with or without the call. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.isIsolated`, `PageItem.bringInPerspective` and + Document and PageItem pages list, such as `Document.swatches`, `PageItem.isIsolated`, `PageItem.bringInPerspective` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the @@ -3258,6 +3265,86 @@ through `$`: strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves that this page does not describe are not defined yet and read as `undefined`. +- A document also has `layers`, `activeLayer`, `groupItems`, `compoundPathItems` and `artboards`. + `layers` (https://ai-scripting.docsforadobe.dev/jsobjref/Layers/) and a layer's own `layers` have `length`, `[i]`, + `index(key)`, `getByName(name)`, `add()` and `removeAll()`. On the document, `add()` runs `layer.new` and makes a + layer above every top-level layer; on a layer it runs `layer.newSublayer` and makes a sublayer on top of that + layer's contents. The new layer becomes the current one. `removeAll()` runs `layer.delete`; on the document's + layers it throws, since a document keeps at least one layer. Assigning a layer to `activeLayer` runs + `layer.setCurrent`. A `Layer` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/) has `typename`, `name`, + `visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`, + `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`, + `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run + `layer.setProps`, and `opacity` runs `object.setProps`. `move` and `zOrder` run `node.move`; a layer goes into + another layer, to the top level of the document, or directly above or below another layer. Every page item has + `layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has + `clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem` + (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/) has `pathItems`. `groupItems` + (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`, + `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. + `clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/) + has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new` and returns + the new artboard), `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, returns nothing; + read `artboards[index]` afterward), `remove(index)` (runs + `artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard` + (https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`, + `rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its + properties run `artboard.setProps`, and `rulerOrigin` runs `document.setRulerOrigin`. One document always keeps + one artboard. + VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. A layer's or group's + `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the objects directly in + it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any + depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers, and a compound + path's `pathItems` are `PathItems` objects with `length`, `[i]`, `index`, `getByName`, `removeAll` and string conversion. + Their path creation methods throw an error; a script can move existing paths into the compound path. + Scoped collections support `toString()` and `String()`. For `Layers`, `GroupItems`, `CompoundPathItems` and + `Artboards`, the conversion throws the same error as `typename` once the container is deleted or the document is + closed. A layer's or artboard's `name` takes a number or a boolean as + `String()` writes it. `locked` true means the layer is locked. `color` is an `RGBColor` object with `typename` and `{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; each scan counts toward the script's operation budget. + `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past + the next layer beside it and any art between them. + `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection (`select.add`), and `false` + 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. Each assignment counts the current selection toward the script's + operation budget, and `true` also counts every node of the layer it looks at, hidden and locked ones included. + `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. Changes are refused when the group or its layer is + hidden or locked, or its artboard is locked. A scoped `removeAll()` that leaves a clipping group or layer + without art releases its mask in the same undo step. `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, and `compoundPathItems.add()` + makes an empty compound path in the same place + (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). A path that `move` or `duplicate` puts into a + compound path becomes one of its paths and gives up its own paint, as Make Compound Path leaves its paths. The + compound path becomes pixel-aligned when the path was, or when the compound path it leaves was. A path moved + into an already pixel-aligned compound path is snapped to the pixel grid. An empty + compound path takes the paint the first path that goes in was drawn with: the path's own, or the paint of the + compound path it leaves. Other objects are refused. A path that `move` takes out of a compound path into a layer or + a group takes the compound path's paint and pixel alignment, as Release Compound Path gives them to its paths. + `artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is + `[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below + its top, each side from 1 to 3,999,856 points and every edge at most 4,000,000 points from the document origin. + Artboard names are trimmed, an empty name gives the artboard its default name (`Artboard N` for the Nth artboard), + and two artboards may have the same name. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one past the artboard count that no other artboard's + name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down. + `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the + change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the + run leaves it). The report also lists a document whose active artboard has another index when the run ends because + artboards were inserted, removed or reordered before it. An index outside the list throws a + `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws + `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and + `GroupItems.createFromFile` throw an error that says they are not available yet. +- `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; + default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, + index 0 puts it directly above the clipping path), as one undo step named Group, and + gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. + An omitted key takes its default (`parent`: the current layer; `index`: on top; `compound`: false). + Explicit `null` is refused for `parent`, `index` and `compound`. + The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path + gives up its own paint (a clip group's or clipping layer's clipping path is refused until its mask is released), and an empty compound path takes the paint the first path that goes in was drawn with. A + path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel + alignment. - `app.preferences` (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/) has `getBooleanPreference(key)`, `getIntegerPreference(key)`, `getRealPreference(key)`, `getStringPreference(key)`, the four matching `set…(key, value)` and `removePreference(key)`. The key `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`. @@ -3786,9 +3873,13 @@ through `$`: app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and 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 + Selected Art) and does not name one acts on the active document's active artboard. Once the script has called + `setActiveArtboardIndex` on that document, it is the artboard the script chose while that artboard exists. If it + has been deleted, playback uses the same fallback as `getActiveArtboardIndex()`, script coordinates and the view: + the saved active artboard if it still exists, otherwise index 0. File > Revert discards the script's stored choice. + If the script has not chosen an artboard on that document since its last revert, the step uses the index of its active artboard + as the run started: 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 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 @@ -4880,6 +4971,7 @@ With `ids`, `guides: true` also deletes the selected ruler guides. The command r boolean or `null`. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps it, empty, also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean or `null` is rejected. `null` for `guides`, `keepEmpty` or `keepJoined` counts as leaving the key out. +A clipping group or layer left without art releases its mask in the same undo step. Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as `path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected (the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected @@ -8165,7 +8257,8 @@ and `layerRows`, the rows highlighted in the panel. bottom layer's into the empty space under the list) places them, unless objects are copied with a top-level layer that is the target, which would put them inside it (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level - form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. A row that + form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group, and it puts + a path into a shown, unlocked compound path (see `object.newGroup` for the paint the path keeps or takes). A row that either command puts into a Live Paint group from elsewhere (inside it, or above or below one of its rows) joins the group's paths as `livePaint.merge` adds them, in one "Merge Live Paint" undo step, and the group is selected and listed in `layer.move`'s `ids` in its place; paths, compound paths, groups of them and Live Paint groups can join, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c135dc04fe..4626279dbc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1125,16 +1125,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. + - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`. - Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`. - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). - `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer` and the other classes this list does not name are not there yet. `crates/engine/src/tests/script_dom.rs`. + `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.