diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c600cc84c4..e8d0cc404a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -102,8 +102,10 @@ pub(super) struct State { coords: Cell, items: RefCell>, locked: RefCell>, - /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. - paths: RefCell>, + /// The last [`paths::PATH_LISTS`] lists of paths a document's, a layer's or a group's + /// `pathItems` gave ([`paths`]), least recently used first, each kept while its document is + /// unchanged. + paths: RefCell>, /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3fafaf684b..23e4d58170 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,8 +12,8 @@ //! //! 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` +//! `pageItems`, `groupItems`, `compoundPathItems` and `pathItems`, 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. @@ -114,7 +114,7 @@ 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 { +pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { let [high, low] = id_parts(id); host_ref("Layer", &[float(h.run), float(uid), high, low]) } @@ -845,6 +845,17 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +/// A layer's or group's `pathItems`: the paths directly in it ([`super::paths`]). +fn held_paths(h: &Host, a: &[Data]) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(super::paths::held_path_items(h, doc.uid, id)); + } + let item = this_item_of(h, a, "GroupItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -897,8 +908,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("pathItems", get(l, held_paths)), ]); - m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), @@ -1320,6 +1332,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("pathItems", get(l, held_paths)), ("zOrderPosition", get(l, layer_z_position)), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)), ("isIsolated", get(l, layer_is_isolated)), @@ -1328,8 +1341,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("zOrder", method(l, layer_z_order)), ]); layer.extend( - ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] - .map(|m| later(l, "Layer", m)), + ["textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), ); vec![ class("Layer", None, layer, None), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 32401db1d0..87287c5c27 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -13,7 +13,9 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside -//! groups and compound paths included. +//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in +//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden +//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, throws `Cannot edit` with nothing changed. //! - A path in a compound path or compound shape reads that owner's paint, which the paint @@ -23,8 +25,8 @@ //! fill or stroke only. //! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes //! them all. -//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever -//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's +//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. @@ -56,8 +58,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, - float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, edit_item, editable, find_doc, float, + frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -263,21 +265,48 @@ fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { r } -// ---- Document.pathItems ---- +// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ---- -/// The ids of a document's paths, in the order of its page items. -fn path_items(h: &super::Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.paths.borrow() - && *uid == st.uid - && std::sync::Arc::ptr_eq(doc, &st.doc) +/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the +/// document's), and the ids it listed then. +pub(super) type PathList = (u64, Arc, Option, Rc>); + +/// How many lists of paths [`super::State`] keeps at once. +pub(super) const PATH_LISTS: usize = 4; + +/// The ids of a document's paths, in the order of its page items, or of the paths directly in the +/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their +/// documents are unchanged, so a loop over a collection builds its list once. A new list of a +/// container is charged by the objects it looks at. +fn path_items(h: &super::Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { { - return ids.clone(); + let mut lists = h.dom.paths.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } } - let all = super::page_items(h, st); - let ids: Rc> = - Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); - *h.dom.paths.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); - ids + let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. }); + let ids: Rc> = match container { + 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)?; + Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect()) + } + None => { + let all = super::page_items(h, st); + Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect()) + } + }; + let mut lists = h.dom.paths.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= PATH_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), container, ids.clone())); + Ok(ids) } pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { @@ -285,32 +314,57 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) } -fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "PathItems") +/// The `pathItems` of the layer or group `id` in the document `uid`. +pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { + let [high, low] = id_parts(id); + host_ref("PathItems", &[float(h.run), float(uid), high, low]) +} + +/// The document of a `PathItems` object, and the layer or group it lists the paths of, if any. +fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low] => { + 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()))?; + let holds = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }))); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(HostError::Type("this is not a PathItems".into())), + } } fn items_length(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) + let (doc, c) = items_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) + let (doc, c) = items_scope(h, a)?; + Ok(match c { + None => host_ref("Document", &[float(h.run), float(doc.uid)]), + Some(c) => with_doc(h, doc, |_, st| { + if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) } + }), + }) } fn items_at(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(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| { - let ids = path_items(h, st); + let ids = path_items(h, st, 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| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -328,15 +382,15 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } } -/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or +/// locked path, or one in a hidden or locked layer or group, stops it before anything is deleted. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st, c)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) - }); + Ok::<_, HostError>((ids, refused)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); @@ -356,19 +410,53 @@ fn made_id(r: &Data) -> std::result::Result { id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } -/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, -/// and reverses the new path's direction when `reversed`. → the new path. -fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { - let made = on_doc(h, doc.uid, true, |h| { +/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or +/// locked layer or group. +pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group"; + +/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the +/// selection and the current layer kept. With a layer or group `container`, the container's layer +/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made +/// outside the container then moves on top of its contents in the same step; a container that is +/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`] +/// before anything is made. → the new path. +fn make_in( + h: &super::Host, + doc: Doc, + container: Option, + make: impl FnOnce(&super::Host) -> std::result::Result, +) -> Answer { + if let Some(c) = container + && !with_doc(h, doc, |_, st| editable(&st.doc, c)) + { + return Err(HostError::Error(CONTAINER_LOCKED.into())); + } + let made = match container { + None => on_doc(h, doc.uid, true, make)?, + Some(c) => super::atomically(h, |h| { + let id = on_doc(h, doc.uid, true, |h| { + command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?; + make(h) + })?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?, + }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(super::item_ref(h, st, made)) +} + +/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s +/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path. +fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { + make_in(h, doc, container, |h| { let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } Ok(id) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } /// Argument `i`, or `default` when it is left out. @@ -409,13 +497,13 @@ fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result /// `rectangle(top, left, width, height, reversed?)`. fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); let reversed = flag(a, 5, "reversed")?; let p = corner(h, doc, left, top)?; - make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the @@ -455,7 +543,7 @@ fn rounded(r: Rect, rx: f64, ry: f64) -> Vec { /// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, /// reversed = false)`: a closed path with `path.create`. fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); @@ -463,12 +551,12 @@ fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { let reversed = flag(a, 7, "reversed")?; let p = corner(h, doc, left, top)?; let anchors: Vec = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect(); - make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) + make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) } /// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`. fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?; let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?; let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?); @@ -477,7 +565,7 @@ fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Error("ellipse with inscribed true is not available yet".into())); } let p = corner(h, doc, left, top)?; - make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The center of a polygon or star, in document coordinates. @@ -489,32 +577,33 @@ fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r = size(a, 3, Some(50.0), "radius")?; let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?; let reversed = flag(a, 5, "reversed")?; - make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) + make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) } /// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed = /// false)`. fn items_star(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r1 = size(a, 3, Some(50.0), "radius")?; let r2 = size(a, 4, Some(20.0), "innerRadius")?; let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?; let reversed = flag(a, 6, "reversed")?; - make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) + make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) } -/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with -/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open -/// path is set back to none in the same step. +/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or +/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art. +/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set +/// back to none in the same step. fn items_add(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - let made = on_doc(h, doc.uid, true, |h| { + let (doc, into) = items_scope(h, a)?; + make_in(h, doc, into, |h| { let unpainted = { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() @@ -524,10 +613,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } Ok(id) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } // ---- PathItem geometry ---- diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ea3e0ac497..fb7239394a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1597,6 +1597,123 @@ fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); } +#[test] +fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost_first() { + let (mut s, _, 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.none", &json!({})).unwrap(); + // The layer holds `a` (30 pt wide) and a group of `b` (50 pt wide) and `c` (70 pt wide); the + // document's list holds all three, the layer's only `a`, and a sublayer's path is its own. + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers[0], g = L.groupItems[0], P = L.pathItems, G = g.pathItems;\ + vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ + vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ + var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ + vc.log(G.getByName === undefined); vc.log(P[1] === undefined);", + ); + let expected = + [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; + assert_eq!(out[..11], expected); + assert_eq!(out[11..], [json!(false), json!(true)]); +} + +#[test] +fn a_loop_over_a_groups_path_items_builds_the_list_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..1000).map(|i| rect(&mut s, f64::from(i % 40) * 10.0, 10.0, 5.0, 5.0).0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + // Reading `length` and `[i]` 1,000 times each stays within 512 KiB of data only when the list + // of 1,000 paths is not built again for each read. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 19))); + let r = run(&mut s, "var P = app.activeDocument.groupItems[0].pathItems, n = 0; for (var i = 0; i < P.length; i++) if (P[i]) n++; vc.log(n);"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(r.unwrap()["log"], json!([1000])); +} + +#[test] +fn a_layers_path_items_make_their_paths_on_top_of_that_layer() { + let (mut s, ..) = doc(); + let bottom = s.active().unwrap().doc.layers[0].id; + let selected = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + // A new layer becomes the current one; each creator of the first layer's `pathItems` still + // puts its path on top of that layer. + let out = log( + &mut s, + "var d = app.activeDocument, top = d.layers.add(), L = d.layers[1], P = L.pathItems;\ + var make = [function () { return P.rectangle(100, 100, 20, 10); }, function () { return P.roundedRectangle(100, 100, 20, 10); },\ + function () { return P.ellipse(); }, function () { return P.polygon(); }, function () { return P.star(); }, function () { return P.add(); }];\ + for (var i = 0; i < make.length; i++) { var p = make[i](); p.name = 'm' + i; vc.log(p.layer.name === L.name); vc.log(L.pageItems[0].name); }\ + vc.log(d.activeLayer.name === top.name); vc.log(top.pageItems.length); vc.log(P.length);", + ); + let mut expected = Vec::new(); + for i in 0..6 { + expected.extend([json!(true), json!(format!("m{i}"))]); + } + expected.extend([json!(true), json!(0), json!(8)]); + assert_eq!(out, expected); + assert_eq!(undo_steps(&s), steps + 1); + let st = s.active().unwrap(); + let kids = st.doc.node(bottom).unwrap().children().unwrap(); + assert_eq!(kids.last().unwrap().name.as_deref(), Some("m5")); + assert!(st.selection == selected); +} + +#[test] +fn a_groups_path_items_add_puts_the_path_in_the_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0], n = g.pathItems.add(); n.name = 'N';\ + vc.log(n.parent.typename); vc.log(g.pageItems[0].name); vc.log(n.pathPoints.length);\ + var r = g.pathItems.rectangle(50, 50, 10, 10); r.name = 'R'; vc.log(g.pathItems[0].name); vc.log(g.pathItems.length);", + ); + assert_eq!(out, [json!("GroupItem"), json!("N"), json!(0), json!("R"), json!(4)]); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + let top: Vec> = d.node(gid).unwrap().children().unwrap().iter().rev().take(2).map(|n| n.name.as_deref()).collect(); + assert_eq!(top, [Some("R"), Some("N")]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +#[test] +fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { + const REFUSED: &str = "Cannot add a path to a hidden or locked layer or group"; + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let lid = s.active().unwrap().doc.layers[0].id; + let before = format!("{:?}", s.active().unwrap().doc.layers); + s.execute("layer.setProps", &json!({"id": lid.0, "locked": true})).unwrap(); + let locked = format!("{:?}", s.active().unwrap().doc.layers); + for src in ["app.activeDocument.layers[0].pathItems.rectangle(10, 10, 5, 5);", "app.activeDocument.layers[0].pathItems.add();"] { + assert!(failure(&mut s, src).contains(REFUSED), "{src}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); + } + s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap(); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap(); + let hidden = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].pathItems.ellipse();").contains(REFUSED)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), hidden); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": true})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // A group's `pathItems` read after the group is gone throw. + let msg = failure(&mut s, "var g = app.activeDocument.groupItems[0], P = g.pathItems; g.remove(); P.length;"); + assert!(msg.contains("Stale page item"), "{msg}"); +} + #[test] fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 563f23db6f..cc604a7bc4 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -108,7 +108,7 @@ const INSIDE: &[(&str, &str)] = &[ "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 \ + locked= move name name= opacity opacity= pageItems parent pathItems placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ textFrames= typename visible visible= zOrder zOrderPosition", ), @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ ("GroupItem.", "prototype"), ( "GroupItem.prototype.", - "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems placedItems placedItems= \ rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", ), ("GroupItems.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 6a58f9712c..899b7f5563 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2707,12 +2707,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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 + `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `pathItems`, `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` + `clipped`, `pageItems`, `groupItems`, `compoundPathItems` and `pathItems`, 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`. @@ -2757,8 +2757,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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. + `Stale artboard`. `Layer.blendingMode`, `artworkKnockout` and `sliced` 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 @@ -2777,7 +2777,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing - mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + mode, which stays as it was. A layer's and a group's `pathItems` + (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) + have the same members, and their `parent` is that layer or group. Their `add()` and shape creators put the new path + on top of that layer's or group's contents, with the current layer left as it was: the path is made with the + container's layer as the current one (`layer.setCurrent`) and, for a group, moved into it with `node.move`, in the + run's one undo step. VectorCraft's own rules: a layer's or group's `pathItems` list the paths directly in it, + topmost first, leaving out paths in its groups, compound paths and sublayers; a layer or group that is hidden or + locked, or that is in a hidden or locked layer or group, throws `Cannot add a path to a hidden or locked layer or + group` and no path is made. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3796a198aa..3339695f64 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.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`). Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.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 `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.