diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3a52534ac8..ca4a9d7022 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; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; 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", + "{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; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard (unless it is new art there that is still selected), 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 ), @@ -1051,7 +1051,8 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } // 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. + // the path was, or when the compound path it leaves was. A compound path that is + // pixel-aligned snaps the path it takes in. if let Some(c) = into { let mut aligned = from_aligned; if let Some(m) = d.node_mut(id) { @@ -1061,9 +1062,12 @@ fn move_node(s: &mut Session, p: &Value) -> Result { *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(cn) = d.node_mut(c) { + aligned |= cn.extras().pixel_aligned; + if aligned { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } } } if let Some((appearance, aligned)) = out_of diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c8aab4149c..a2a2bd695e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,7 +38,8 @@ //! - After `documents[0]`, documents are listed from the one active most recently to the one //! active longest ago. A change a script makes to a document in the back does not move it. //! - `pageItems` lists every object, with the objects inside groups and compound paths after the -//! group or compound path, and leaves out layers and ruler guides. An index out of range gives +//! group or compound path, and leaves out layers and ruler guides. The `layers` module gives the +//! order of a layer's, a group's and a compound path's lists. An index out of range gives //! `undefined`; `index` and `getByName` throw `Not found` when nothing matches. //! - Script coordinates are points with Y up from the bottom of the first artboard //! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of @@ -120,6 +121,8 @@ mod variables; pub(super) use colors::of_color as color_data; #[cfg(test)] pub(crate) use paths::POINT_LOOKS; +#[cfg(test)] +pub(crate) use paths::index_builds; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; @@ -202,14 +205,18 @@ thread_local! { /// written yet, how many times each path's points went stale and each path as the run last saw its /// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each /// `DocumentPreset` the run made, with the size of the values they hold now and the most they may -/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool +/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, the lists of art and +/// layers its layers and groups gave, the active artboard of each document, and the tool /// `app.selectTool` chose last. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, - /// The last list of each document's paths ([`paths`]), kept while that document is unchanged. - paths: RefCell>, + locked: 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)>>, @@ -228,14 +235,13 @@ pub(super) struct State { /// The item the object model is changing ([`edit_item`]), whose points stay valid through the /// change. 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 last [`layers::LAYER_LISTS`] lists of layers `layers` gave, least recently used first, + /// each kept while its document is unchanged. + layer_lists: 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. @@ -325,24 +331,6 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); -/// The most documents whose lists [`State`] keeps at once, the least recently listed going first. -const KEPT_LISTS: usize = 8; - -/// The list kept in `lists` for the document `st`, while that document is unchanged. -fn kept_list(lists: &RefCell>, st: &DocState) -> Option>> { - lists.borrow().iter().find(|(uid, doc, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc)).map(|(_, _, ids)| ids.clone()) -} - -/// Keeps `ids` in `lists` as the list of the document `st`, in place of the one it had. -fn keep_list(lists: &RefCell>, st: &DocState, ids: &Rc>) { - let mut l = lists.borrow_mut(); - l.retain(|(uid, ..)| *uid != st.uid); - if l.len() >= KEPT_LISTS { - l.remove(0); - } - l.push((st.uid, st.doc.clone(), ids.clone())); -} - /// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for /// each object of a layer or sublayer asked about then, whether it was on a locked artboard. type LockedList = (u64, Arc, Arc>, HashMap); @@ -624,6 +612,15 @@ fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [f64; 5] { [float(h.run), float(st.uid), high, low, float(st.reverts)] } +/// The handle of a collection that lists the art of the layer, group or compound path `id` in the +/// document `uid`, with the document's revert count as [`node_handle`] gives it, so that a +/// collection read before File > Revert is stale. +fn scoped_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] { + let [high, low] = id_parts(id); + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); + [float(h.run), float(uid), high, low, float(reverts)] +} + fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> { let &[run, uid, high, low, reverts] = handle else { return None }; let doc = find_doc(h, run, uid)?; @@ -692,7 +689,7 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { host_ref("PluginItem", &node_handle(h, st, tracing::origin(h, st.uid, id))) } Some(t) => host_ref(t, &node_handle(h, st, id)), - None => host_ref("Layer", &node_handle(h, st, id)), + None => layers::layer_ref(h, st.uid, id), }, None => Data::Null, } @@ -867,7 +864,9 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::>()}))?; } else { // One `select.anchorsMany` selects every object in its order: a partly selected path with - // its anchors, a whole path with all of them and any other object with none. + // its anchors, a whole path with all of them and any other object with none. A path with + // only segments selected gets no anchors here, so `select.segments` below selects it with + // just those segments. let items: Vec = kept .iter() .map(|i| { @@ -1167,8 +1166,14 @@ fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer { /// with a drive letter) takes `\` and `/` alike and letters in one case. On other systems `\` is a /// character of a file name, so `/work/a\b.ai` and `/work/a/b.ai` are different files. fn path_key(p: &str) -> String { + path_key_on(p, cfg!(windows)) +} + +/// [`path_key`] treating every path as a Windows path when `windows`, else only one that starts +/// with a drive letter. +pub(crate) fn path_key_on(p: &str, windows: bool) -> String { let b = p.as_bytes(); - let windows = cfg!(windows) || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'); + let windows = windows || (b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'); if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() } } @@ -1622,9 +1627,17 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { // Letter) with `presetSettings` over it, given in full so that a saved preset of the same name // does not stand in for it. Settings the built-in preset refuses are an error. let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); + let mut shadowed_by = None; if let Some(first) = first { - p.insert("preset".into(), json!(first.name)); - let full = first.with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?; + let full = first.clone().with_params(&Value::Object(p.clone()), "file.new").map_err(|e| HostError::Error(e.to_string()))?; + let shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim())); + if shadowed { + // `file.new` would find the saved preset of that name first, so the name is left out + // and the built-in preset's settings, with `presetSettings` over them, go as params. + shadowed_by = Some(first.clone()); + } else { + p.insert("preset".into(), json!(first.name)); + } if let Value::Object(settings) = full.to_json() { for key in BUILT_IN_SETTINGS { if let Some(v) = settings.get(*key) { @@ -1643,6 +1656,15 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { let reason = e["reason"].as_str().unwrap_or_default(); return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); } + // The built-in preset's settings went as params: Recent keeps its name, as `file.new` + // keeps a preset's name, unless its size changed (turning it doesn't count). + if let Some(first) = &shadowed_by { + let sorted = |d: &crate::cmd::newdoc::DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); + let mut s = h.session.borrow_mut(); + if let Some(r) = s.prefs.recent_new_docs.first_mut().filter(|r| sorted(r) == sorted(first)) { + r.name.clone_from(&first.name); + } + } // Each warning from reading the profile's file goes to the console. for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut)); @@ -2230,7 +2252,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result { } fn items_length(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_length(h, a); } let doc = items_doc(h, a)?; @@ -2239,7 +2261,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer { } fn items_typename(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_typename(h, a); } items_doc(h, a)?; @@ -2247,7 +2269,7 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer { } fn items_to_string(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { layers::scoped_typename(h, a)?; return Ok(text("[PageItems]")); } @@ -2256,7 +2278,7 @@ fn items_to_string(h: &Host, a: &[Data]) -> Answer { } fn items_parent(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_parent(h, a); } let doc = items_doc(h, a)?; @@ -2269,30 +2291,55 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } +/// The answer of an indexer called with a name, from `found`, the collection's `getByName`: a +/// name nothing has gives `undefined` for `name in collection` ([`probing`]) and throws otherwise. +fn by_name_or_probe(a: &[Data], found: Answer) -> Answer { + match found { + Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), + r => r, + } +} + /// The position an indexer key names when it is an array index, 0 to 2^32 - 2. fn position(n: f64) -> Option { whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) } +/// The arguments of an indexer called with a number that is not an array index, such as `-1` or +/// `1.5`, with that key given as the text of the number, the name it is looked up by: a key such +/// as `"-1"` reaches an indexer as a number. +fn number_named(a: &[Data]) -> Option> { + let Data::Number(n) = arg(a, 1) else { return None }; + if position(*n).is_some() { + return None; + } + let mut named = a.to_vec(); + named[1] = text(vectorcraft_js::number_to_string(*n)); + Some(named) +} + +/// The answer of an indexer for a number key looked up as a name ([`number_named`]), from `found`, +/// the collection's `getByName`: `undefined` when nothing has the name. +fn named_or_undefined(found: Answer) -> Answer { + match found { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + } +} + /// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a /// 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") { + if layers::is_scoped(a) { return layers::scoped_at(h, a); } let doc = items_doc(h, a)?; match arg(a, 1) { - Data::String(_) => match items_by_name(h, a) { - Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), - r => r, - }, + Data::String(_) => by_name_or_probe(a, items_by_name(h, a)), Data::Number(n) => match position(*n) { Some(i) => item_at(h, doc, i), - None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { - Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), - r => r, - }, + None => named_or_undefined(items_named(h, doc, &vectorcraft_js::number_to_string(*n))), }, _ => Ok(Data::Undefined), } @@ -2304,7 +2351,7 @@ 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") { + if layers::is_scoped(a) { return layers::scoped_by_name(h, a); } let doc = items_doc(h, a)?; @@ -2323,7 +2370,7 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &Host, a: &[Data]) -> Answer { - if layers::is_scoped(a, "PageItems") { + if layers::is_scoped(a) { return layers::scoped_index(h, a); } match arg(a, 1) { @@ -2343,7 +2390,7 @@ 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") { + if layers::is_scoped(a) { return layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; @@ -2675,8 +2722,8 @@ fn item_control(h: &Host, a: &[Data]) -> Answer { /// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and /// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as -/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping -/// path's. +/// the visible bounds leave them out, a clip group or clipping layer gives only its clipping +/// path's, and the source art a Shaper Group or a tracing keeps is left out. fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect { *steps += 1; if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { @@ -2686,7 +2733,7 @@ fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect { *steps += 1; r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out); } - let children = n.children().map_or(&[][..], Vec::as_slice); + let children = n.editing_children(); let children = if n.clips() { &children[..children.len().min(1)] } else { children }; for c in children { r = take_in_handles(c, r, steps); @@ -3289,7 +3336,7 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer { } /// `toString()` of an object without a name: `[Class]`. -fn class_text(name: &'static str) -> HostMember { +pub(super) fn class_text(name: &'static str) -> HostMember { HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]"))))) } diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 6a4c0e1d08..95ef993284 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,7 +12,7 @@ //! //! 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`, `compoundPathItems` and `textFrames`, and a compound path's +//! `pageItems`, `groupItems`, `compoundPathItems`, `pathItems` and `textFrames`, 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 @@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_ 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, + arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref, later, method, + named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, returns, text, typed, typename, + whole, with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -66,8 +66,6 @@ enum Kind { Group, /// Compound paths (`CompoundPathItem`). Compound, - /// Paths (`PathItem`). - Path, /// Type (`TextFrame`), whose collection's other members are in `text.rs`. Text, } @@ -78,7 +76,6 @@ impl Kind { Kind::Any => "PageItems", Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", - Kind::Path => "PathItems", Kind::Text => "TextFrames", } } @@ -88,7 +85,6 @@ impl Kind { Kind::Any => typename(n).is_some(), Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), - Kind::Path => typename(n) == Some("PathItem"), Kind::Text => typename(n) == Some("TextFrame"), } } @@ -109,14 +105,16 @@ fn result_id(v: &Value, key: &str) -> Option { /// 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 [run, uid, high, low, _] = handle.as_slice() else { return Err(type_error("Layer")) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + // A layer read before its document was reverted is stale as the page items read then are. + let (doc, id) = super::node_of(h, &handle).filter(|(d, _)| d.uid == doc.uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + held_layer(h, doc, id) +} + +/// The layer `id` of `doc`, which must still be a layer of the document. +fn held_layer(h: &Host, doc: Doc, id: NodeId) -> Result<(Doc, NodeId)> { 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())); @@ -128,14 +126,12 @@ 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))] +pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { + let s = h.session.borrow(); + match s.documents().iter().find(|d| d.uid == uid) { + Some(st) => host_ref("Layer", &super::node_handle(h, st, id)), + None => Data::Null, + } } /// Reads the layer `this` names with `f`. @@ -285,22 +281,23 @@ fn layer_parent(h: &Host, a: &[Data]) -> Answer { })) } +fn layer_to_string(h: &Host, a: &[Data]) -> Answer { + named_text("Layer", layer_name(h, a)) +} + 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. The list comes from [`layers_listed`], so reading it for each layer of a loop +/// not counted. The list comes from [`layer_ids`], so reading it for each layer of a loop /// lists the layers once. Each read is still charged for the search through the list. fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let list = layers_listed(h, st, st.doc.parent_of(id))?; + let list = layer_ids(h, st, st.doc.parent_of(id))?; + // The scan is charged by itself: a list kept from an earlier read was charged once. h.charge_call(list.len() as u64)?; Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) })?; @@ -535,8 +532,9 @@ 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]))?; + [_, _, _, _, _] => { + // A collection read before its document was reverted is stale, as its layer is. + let (doc, id) = layer_of(h, &host_ref("Layer", &handle))?; Ok((doc, Some(id))) } _ => Err(type_error("Layers")), @@ -554,33 +552,33 @@ fn layer_list(d: &Document, parent: Option) -> Vec { 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. +/// A document's uid, the document as it was, a parent layer (`None`: the top level) and its layers. 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>> { +/// How many lists of layers [`super::State`] keeps at once. +pub(super) const LAYER_LISTS: usize = 4; + +/// [`layer_list`], kept while the document is unchanged for the last [`LAYER_LISTS`] parents, so a +/// loop over `layers` builds the list once. Each new list is charged by the objects it looks at. +fn layer_ids(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 mut lists = h.dom.layer_lists.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent) { let list = lists.remove(at); let ids = list.3.clone(); lists.push(list); return Ok(ids); } } - let looked_at = match parent { + let looked = 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)?; + h.charge_call(looked as u64)?; let ids = Rc::new(layer_list(&st.doc, parent)); - let mut lists = h.dom.layers.borrow_mut(); + let mut lists = h.dom.layer_lists.borrow_mut(); lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); - if lists.len() >= ART_LISTS { + if lists.len() >= LAYER_LISTS { lists.remove(0); } lists.push((st.uid, st.doc.clone(), parent, ids.clone())); @@ -589,12 +587,12 @@ fn layers_listed(h: &Host, st: &DocState, parent: Option) -> Result Answer { let (doc, id) = this_layer(h, a)?; - Ok(host_ref("Layers", &layer_handle(h, doc.uid, id))) + Ok(host_ref("Layers", &super::scoped_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))) + Ok(num(float(with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))? as u64))) } fn layers_parent(h: &Host, a: &[Data]) -> Answer { @@ -607,30 +605,26 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer { 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, - } -} - +/// `layers[i]`, and `layers["name"]` as `getByName` reads it. A number key that is not an array +/// index, such as `-1`, is looked up as a name, as `pageItems` looks it up. 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); + return super::by_name_or_probe(a, layers_by_name(h, a)); + } + if let Some(named) = super::number_named(a) { + return super::named_or_undefined(layers_by_name(h, &named)); } 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)))) + let Some(i) = super::position(*n) else { return Ok(Data::Undefined) }; + with_doc(h, doc, |_, st| Ok(layer_ids(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)?; + let ids = layer_ids(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())) @@ -640,6 +634,8 @@ fn layers_by_name(h: &Host, a: &[Data]) -> Answer { fn layers_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => layers_by_name(h, a), + // A number is a position here, never a name ([`layers_at`]). + Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())), Data::Number(_) => match layers_at(h, a)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -673,7 +669,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer { 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))?; + let ids = with_doc(h, doc, |_, st| layer_ids(h, st, parent))?; // `layer.delete` takes at most this many rows; more is refused before anything is deleted. if ids.len() > crate::cmd::layer::MAX_ROWS { return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS))); @@ -692,13 +688,11 @@ 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. + [_, _, _, _, _] => { + // A collection read before its document was reverted is stale, as its container is. + let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; 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 { .. })) + 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())); @@ -755,23 +749,15 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R 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) +/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle +/// names the container. +pub(super) fn is_scoped(a: &[Data]) -> bool { + host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5) } 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))]), + Some(c) => host_ref(kind.class(), &super::scoped_handle(h, uid, c)), None => host_ref(kind.class(), &[float(h.run), float(uid)]), } } @@ -787,26 +773,19 @@ fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer { Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) } +/// `collection[i]`, and `collection["name"]` as `getByName` reads it. A number key that is not an +/// array index, such as `-1`, is looked up as a name, as the document's `pageItems` looks it up. 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, - }; + return super::by_name_or_probe(a, art_by_name(h, a, kind)); + } + if let Some(named) = super::number_named(a) { + return super::named_or_undefined(art_by_name(h, &named, kind)); } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) { - Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))), - // The text of a number that is not an array index is looked up as a name. - None => with_doc(h, doc, |_, st| { - let ids = art_list(h, st, kind, c)?; - h.charge_call(ids.len() as u64)?; - let name = vectorcraft_js::number_to_string(*n); - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); - Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id))) - }), - } + let Some(i) = super::position(*n) 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 { @@ -814,6 +793,7 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { 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)?; + // The scan is charged by itself: a list kept from an earlier read was charged once. 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())) @@ -823,8 +803,9 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { match arg(a, 1) { Data::String(_) => art_by_name(h, a, kind), - // A number is a position only. A stale collection throws its stale error first. - Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => { + // A number is a position here, never a name ([`art_at`]). A stale collection throws its + // stale error first. + Data::Number(n) if super::position(*n).is_none() => { art_scope(h, arg(a, 0), kind.class())?; Err(HostError::Error(NOT_FOUND.into())) } @@ -853,36 +834,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { 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. - // Deleting every path of a compound path would leave it empty, so a compound path that - // clips counts as deleted too. - let mut going: std::collections::HashSet = ids.iter().copied().collect(); - let mut seen = std::collections::HashSet::new(); - let mut emptied: Vec = Vec::new(); - for p in ids.iter().filter_map(|i| d.parent_of(*i)) { - if going.contains(&p) || !seen.insert(p) { - continue; - } - let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id))); - if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) { - emptied.push(p); - } - } - going.extend(emptied.iter().copied()); - let masks: Vec = ids - .iter() - .chain(&emptied) - .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(); + let masks = kept_clipping_paths(d, &ids); Ok::<_, HostError>((ids, refused, on_locked, masks)) })?; if !refused.is_empty() { @@ -893,12 +845,7 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } - 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}" - ))); - } + refuse_kept_clipping_paths(&masks)?; // Deleting the objects above an image in an ordinary group named as a tracing would make it one. if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) { return Err(HostError::Error(super::NOT_A_TRACING.into())); @@ -909,29 +856,75 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { Ok(Data::Undefined) } -/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]). +/// The ids (at most 20) among `ids` that are the clipping path of a group or layer that keeps other +/// objects once `ids` are deleted. Deleting one would leave the next object clipping the rest. +/// Deleting every path of a compound path would leave it empty, so a compound path that clips +/// counts as deleted too. +pub(super) fn kept_clipping_paths(d: &Document, ids: &[NodeId]) -> Vec { + let mut going: std::collections::HashSet = ids.iter().copied().collect(); + let mut seen = std::collections::HashSet::new(); + let mut emptied: Vec = Vec::new(); + for p in ids.iter().filter_map(|i| d.parent_of(*i)) { + if going.contains(&p) || !seen.insert(p) { + continue; + } + let all_go = |n: &crate::doc::Node| n.children().is_some_and(|k| k.iter().all(|k| going.contains(&k.id))); + if d.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && all_go(n)) { + emptied.push(p); + } + } + going.extend(emptied.iter().copied()); + ids.iter() + .chain(&emptied) + .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() +} + +/// The error of a `removeAll()` that would delete the clipping paths `masks`, or `Ok` when there +/// are none. +pub(super) fn refuse_kept_clipping_paths(masks: &[u64]) -> std::result::Result<(), HostError> { + if masks.is_empty() { + return Ok(()); + } + let list = masks.iter().map(u64::to_string).collect::>().join(", "); + Err(HostError::Error(format!( + "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" + ))) +} + +/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their +/// handle names one ([`is_scoped`]). pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer { - art_length(h, a, scoped_kind(a)) + art_length(h, a, Kind::Any) } pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer { - art_parent(h, a, scoped_kind(a)) + art_parent(h, a, Kind::Any) } pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { - art_at(h, a, scoped_kind(a)) + art_at(h, a, Kind::Any) } pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { - art_by_name(h, a, scoped_kind(a)) + art_by_name(h, a, Kind::Any) } pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer { - art_index(h, a, scoped_kind(a)) + art_index(h, a, Kind::Any) } pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer { - art_remove_all(h, a, scoped_kind(a)) + art_remove_all(h, a, Kind::Any) } fn groups_length(h: &Host, a: &[Data]) -> Answer { @@ -977,7 +970,7 @@ fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { - art_typename(h, a, scoped_kind(a)) + art_typename(h, a, Kind::Any) } fn groups_typename(h: &Host, a: &[Data]) -> Answer { art_typename(h, a, Kind::Group) @@ -987,15 +980,20 @@ fn compounds_typename(h: &Host, a: &[Data]) -> Answer { } /// `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. +/// layer's or group's contents (the document's: the current layer's), with `object.newGroup`. A +/// Live Paint group takes none. → 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 { .. }))); + let (compound, live) = with_doc(h, doc, |_, st| { + (st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })), super::paths::is_live_paint_group(st, c)) + }); if compound { return Err(HostError::Error("a compound path holds only paths".into())); } + if live { + return Err(HostError::Error(super::paths::LIVE_PAINT_CONTAINER.into())); + } } let mut params = c.map_or_else(|| json!({}), |c| json!({"parent": c.0})); if kind == Kind::Compound @@ -1040,10 +1038,6 @@ 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) } @@ -1052,6 +1046,24 @@ 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)) +} + +/// A compound path's `pathItems`: its paths, which `add()` and the shape methods make inside it +/// ([`super::paths`]). +fn compound_paths(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "CompoundPathItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + fn held_text(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Text) } @@ -1127,12 +1139,13 @@ pub(super) fn members(class: &str, l: &Link) -> Vec { ("pageItems", get(l, held_page_items), listed("PageItems")), ("groupItems", get(l, held_groups), listed("GroupItems")), ("compoundPathItems", get(l, held_compounds), listed("CompoundPathItems")), + ("pathItems", get(l, held_paths), listed("PathItems")), ("textFrames", get(l, held_text), listed("TextFrames")), ]); - m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } - "CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, compound_paths), listed("PathItems"))]), _ => Vec::new(), } } @@ -1196,19 +1209,22 @@ fn board_index(st: &DocState, id: u32) -> Option { st.doc.artboards.iter().position(|a| a.id == id) } +/// The artboard `d` names. An artboard read before its document was reverted is stale, as a page +/// item is: the loaded document's artboard with the same id is another artboard. 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)) } +/// An `Artboard` for the artboard `id` of the document `uid`, with the document's revert count. 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))]) + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); + host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts)]) } fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> { @@ -1435,13 +1451,18 @@ fn board_index_arg(d: &Data, len: usize, what: &str) -> Result { .ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 0 to {}", len.saturating_sub(1)))) } +/// `artboards[i]`, and `artboards["name"]` as `getByName` reads it. A number key that is not an +/// array index, such as `-1`, is looked up as a name, as `pageItems` looks it up. 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); + return super::by_name_or_probe(a, boards_by_name(h, a)); + } + if let Some(named) = super::number_named(a) { + return super::named_or_undefined(boards_by_name(h, &named)); } 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) }; + let Some(i) = super::position(*n) 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)))) } @@ -1458,6 +1479,8 @@ fn boards_by_name(h: &Host, a: &[Data]) -> Answer { fn boards_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => boards_by_name(h, a), + // A number is a position here, never a name ([`boards_at`]). + Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())), Data::Number(_) => match boards_at(h, a)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -1543,7 +1566,7 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { } { let mut chosen = h.dom.chosen_artboards.borrow_mut(); - let reverts = reverts_of(h, doc.uid); + let reverts = with_doc(h, doc, |_, st| st.reverts); if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) { *generation = reverts; } else { @@ -1601,13 +1624,14 @@ pub(super) fn classes(l: &Link) -> Vec { ("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")), + ("opacity", property(l, layer_opacity, layer_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..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")), + ("pathItems", get(l, held_paths), listed("PathItems")), ("textFrames", get(l, held_text), listed("TextFrames")), ("zOrderPosition", get(l, layer_z_position), typed("number")), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected), typed("boolean")), @@ -1617,9 +1641,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("zOrder", method(l, layer_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ("toString", method(l, layer_to_string), returns("string", &[])), ]); - layer.extend( - ["pathItems", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), - ); + layer.extend(["symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m))); vec![ class("Layer", None, layer, None), class( @@ -1680,7 +1702,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("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")), + ("rulerPAR", property(l, board_par, board_set_par), MemberInfo { min: Some(0.1), max: Some(10.0), ..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")), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 1aa8615574..cc1cbe6a62 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, or that is on a locked artboard, throws `Cannot edit` with nothing //! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked @@ -26,8 +28,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. @@ -68,9 +70,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, - edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point, - point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, + Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, class_text, colors, command, + coordinate, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -168,6 +170,12 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &handle) } +#[cfg(test)] +thread_local! { + /// How many times [`point_starts`] counted the points of a path on this thread. + static INDEX_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The index of the first point of each subpath of `subs`, followed by the number of points. fn starts(subs: &[SubPath]) -> Vec { #[cfg(test)] @@ -208,6 +216,8 @@ fn point_starts(h: &super::Host, item: Item) -> std::result::Result std::result::Result std::result::Result u64 { + INDEX_BUILDS.with(std::cell::Cell::get) +} + /// The subpath and the place in it of point `i`, among the subpaths `subs`. fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { for (s, sp) in subs.iter().enumerate() { @@ -267,7 +285,20 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its /// points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { - forget_waiting_starts(h); + edit_points_keeping(h, item, false, f) +} + +/// [`edit_points`]. With `counts_kept`, `f` leaves the number of subpaths and of points in each as +/// they are, so the [`starts`] of the waiting changes stay kept. +fn edit_points_keeping( + h: &super::Host, + item: Item, + counts_kept: bool, + f: impl FnOnce(&mut Vec) -> T, +) -> std::result::Result { + if !counts_kept { + forget_waiting_starts(h); + } if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { @@ -308,7 +339,7 @@ fn forget_waiting_starts(h: &super::Host) { fn edit_anchor(h: &super::Host, item: Item, i: usize, f: impl FnOnce(&mut Anchor)) -> std::result::Result<(), HostError> { let counted = point_starts(h, item)?; let at = locate_at(&counted, i); - edit_points(h, item, |subs| { + edit_points_keeping(h, item, true, |subs| { if let Some((s, j)) = at && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { @@ -454,19 +485,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. Building the list again counts -/// the page items it looks through against the run's host-call allowance. -fn path_items(h: &super::Host, st: &DocState) -> Result>, HostError> { - if let Some(ids) = super::kept_list(&h.dom.paths, st) { - return Ok(ids); +/// 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 is +/// charged by the objects it looks at. +fn path_items(h: &super::Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { + { + 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)?; - h.charge_call(all.len() as u64)?; - let ids: Rc> = - Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); - super::keep_list(&h.dom.paths, st, &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)?; + h.charge_call(all.len() as u64)?; + 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) } @@ -475,54 +535,66 @@ 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 { - 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())); +/// 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 { + host_ref("PathItems", &super::scoped_handle(h, uid, id)) +} + +/// The document of a `PathItems` object, and the layer, group or compound path 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)), + [_, _, _, _, _] => { + // A collection read before its document was reverted is stale, as its container is. + let (doc, id) = super::node_of(h, &handle).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 { .. } | NodeKind::Compound { .. })) + }); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(HostError::Type("this is not a PathItems".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)?; + items_scope(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))) + 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 { - 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)])) + 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) } + }), + }) } /// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a /// 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)?; + let (doc, c) = items_scope(h, a)?; match arg(a, 1) { Data::String(_) => match items_by_name(h, a) { Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined), r => r, }, Data::Number(n) => match super::position(*n) { - Some(i) => item_at(h, doc, i), - None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Some(i) => item_at(h, doc, c, i), + None => match items_named(h, doc, c, &vectorcraft_js::number_to_string(*n)) { Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), r => r, }, @@ -532,23 +604,20 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { } /// The path at position `i` of `pathItems`, or `undefined` past the end. -fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer { - with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) +fn item_at(h: &super::Host, doc: Doc, c: Option, i: usize) -> Answer { + 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 { - if super::layers::is_scoped(a, "PathItems") { - return super::layers::scoped_by_name(h, a); - } - 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())) }; - items_named(h, doc, name) + items_named(h, doc, c, name) } /// The first path of `pathItems` named `name`, or `Not found`. -fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { +fn items_named(h: &super::Host, doc: Doc, c: Option, name: &str) -> Answer { 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)); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -556,14 +625,11 @@ 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) => { - let doc = items_doc(h, a)?; - match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? { + let (doc, c) = items_scope(h, a)?; + match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, c, i)).transpose()? { Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())), Some(d) => Ok(d), } @@ -572,18 +638,17 @@ 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, 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. So does the clipping path of a group or -/// layer that keeps other objects, or a compound path or group that clips one and would be left -/// with no visible path or visible type that lays out glyphs to clip by. +/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or +/// locked 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. A compound path's +/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does. +/// It also throws and deletes nothing when it would delete the clipping path of a group or layer +/// that keeps other objects, or leave a compound path or group that clips one with no visible path +/// or visible type that lays out glyphs to clip by. 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, masks) = with_doc(h, doc, |_, st| { - let ids = path_items(h, st)?; + let (doc, c) = items_scope(h, a)?; + let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| { + let ids = path_items(h, st, c)?; let d = &st.doc; if h.session.borrow().menu.guides_locked && let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) @@ -625,8 +690,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let mut masks = Vec::new(); for n in nodes.into_iter().rev() { let kids = n.children().map_or(&[][..], Vec::as_slice); - // Clear removes compound paths emptied of direct members, but keeps empty groups. - if matches!(n.kind, NodeKind::Compound { .. }) + // Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps + // empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty. + if c.is_none() + && matches!(n.kind, NodeKind::Compound { .. }) && !kids.is_empty() && kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id)) { @@ -659,7 +726,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { masks.push(mask.id.0); } } - Ok::<_, HostError>((ids, refused, on_locked, masks)) + let going: Vec = going.into_iter().collect(); + // Deleting the objects above an image in an ordinary group named as a tracing would make it one. + let tracing = super::removal_makes_tracing(d, &going); + Ok::<_, HostError>((ids, refused, on_locked, masks, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -669,14 +739,13 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { 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}" - ))); + super::layers::refuse_kept_clipping_paths(&masks)?; + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + let params = json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": c.is_some()}); + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", ¶ms))?; } Ok(Data::Undefined) } @@ -687,13 +756,66 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { r.1.get("id").and_then(Value::as_u64).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. Selecting the new path -/// and putting the selection back load the selected objects' paint and stroke width into new art, -/// so new art's paint from before, the defaults a script set included, is put back. -fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { - let made = keeping_paint(h, || { - 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"; + +/// The error of an object made in a Live Paint group, which would join the group's paths instead +/// of staying in the group's own list. +pub const LIVE_PAINT_CONTAINER: &str = "Cannot add an object to a Live Paint group"; + +/// Whether `id` is a Live Paint group, which takes no new objects from the object model. +pub(super) fn is_live_paint_group(st: &DocState, id: NodeId) -> bool { + st.doc.node(id).is_some_and(vectorcraft_tools::builder::is_live_paint) +} + +/// 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, and a Live Paint group throws [`LIVE_PAINT_CONTAINER`]. → 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 { + let (open, live) = with_doc(h, doc, |_, st| (editable(&st.doc, c), is_live_paint_group(st, c))); + if !open { + return Err(HostError::Error(CONTAINER_LOCKED.into())); + } + if live { + return Err(HostError::Error(LIVE_PAINT_CONTAINER.into())); + } + } + let made = match container { + // Making a path can take more than one command (a stroke, a reversal): a failure of a later + // one undoes the path too. + None => super::atomically(h, |h| 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. +/// Selecting the new path and putting the selection back load the selected objects' paint and +/// stroke width into new art, so new art's paint from before, the defaults a script set included, +/// is put back. +fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { + keeping_paint(h, || { + make_in(h, doc, container, |h| { let parent = with_doc(h, doc, |_, st| new_path_layer(st)); let id = made_id(&drawing_normally(h, parent, id, params)?)?; if reversed { @@ -701,10 +823,7 @@ fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> } 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. @@ -745,13 +864,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 @@ -791,7 +910,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")?); @@ -799,12 +918,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")?); @@ -813,7 +932,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. @@ -825,37 +944,38 @@ 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, and new art keeps the paint it had before. +/// `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, and new art keeps the paint it had before. fn items_add(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; // New art's paint is read with the document active, since activating a document can load its // selection's appearance into new art. Selecting the new path loads its temporary stroke into // new art, and putting the selection back does not undo that, so new art's paint from before // the path is put back. - let made = keeping_paint(h, || { - on_doc(h, doc.uid, true, |h| { + keeping_paint(h, || { + 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() @@ -867,10 +987,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { } 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 ---- @@ -889,13 +1006,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| { - if subs.is_empty() && closed { - subs.push(SubPath::new(Vec::new(), closed)); - } else { - subs.iter_mut().for_each(|sp| sp.closed = closed); - } - })?; + // A path with no subpath gets an empty closed one to keep the value in; any other change keeps + // the number of points, so the kept starts of the waiting changes stay valid. + if closed && read_points(h, item, |subs| subs.is_empty())? { + edit_points(h, item, |subs| subs.push(SubPath::new(Vec::new(), closed)))?; + } else { + edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + } Ok(Data::Undefined) } @@ -2125,6 +2242,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("index", point_method(l, points_index), returns("PathPoint", &[("itemKey", "*")])), ("add", point_method(l, points_add), returns("PathPoint", &[])), ("removeAll", point_method(l, points_remove_all), returns("undefined", &[])), + ("toString", class_text("PathPoints"), returns("string", &[])), ]), Some(super::point_function(l, points_at)), ), @@ -2144,6 +2262,7 @@ pub(super) fn classes(l: &Link) -> Vec { typed("PathPointSelection"), ), ("remove", point_method(l, pt_remove), returns("undefined", &[])), + ("toString", class_text("PathPoint"), returns("string", &[])), ]), None, ), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 285c338a2a..b50ee6b858 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2644,11 +2644,10 @@ impl Session { RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; return Some(self.script_failed(job, &e)); } - // One more allowance may still leave the growth past it: the person is asked again - // while they may be, and past that the run ends unkept. - if let Err(HostError::Abort(message)) = job.host.charge_growth(0, 0) { - let e = RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false }; - return Some(self.script_failed(job, &e)); + // What the script added must fit the allowance the last answer gave: past it, the + // person is asked again, as a running script is at its next charge. + if let Err(e) = job.host.charge_growth(0, 0) { + return Some(self.script_failed(job, &end_flush_error(e))); } if job.host.waiting.get() { JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); @@ -2682,14 +2681,24 @@ impl Session { self.script_key = Some(key); None } - // The point changes written as the script ended went past the growth allowance. - Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => { - job.finished = true; - JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); - self.script_key = Some(key); - None + Ok(Ok(Progress::Done(_))) => { + // What the script added must fit the allowance the last answer gave, which one + // answer can leave short of what the script had already added. + if !job.host.waiting.get() + && let Err(e) = job.host.charge_growth(0, 0) + { + return Some(self.script_failed(job, &end_flush_error(e))); + } + // The point changes written as the script ended, or what it added before, went past + // the growth allowance. + if job.host.waiting.get() { + job.finished = true; + JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); + self.script_key = Some(key); + return None; + } + Some(self.script_ended(job)) } - Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)), } } diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 21cc4af602..6da71137fd 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -558,6 +558,22 @@ fn align_new_objects_to_pixel_grid_follows_the_preset() { assert!(!align(&old)); } +#[test] +fn saved_rows_past_the_limit_read_as_the_limit_and_others_stay() { + let mut s = Session::new(); + let saved = json!({"newDocPresets": [ + {"name": "Many", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 1001}, + {"name": "Four", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 4}, + ]}); + s.apply_prefs(serde_json::from_value(saved).unwrap()); + for (name, rows) in [("Many", 1000), ("Four", 4)] { + let layout = presets(&mut s, "Saved").iter().find(|p| p["name"] == name).unwrap()["artboardLayout"].clone(); + assert_eq!(layout["rows"], json!(rows), "{name}"); + // `file.new` takes the layout `file.newPresets` lists. + s.execute("file.new", &json!({"preset": name, "artboardLayout": layout})).unwrap(); + } +} + #[test] fn rearrange_keeps_its_grid() { let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index c99f58359f..d1ae98e29a 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -1136,6 +1136,30 @@ fn new_art_on_a_locked_artboard_stays_editable_until_the_selection_leaves_it() { batches_and_isolation_keep_new_art_protected(&mut s, pasted); } +/// A compound path pasted onto a locked artboard takes a path through node.move while it is still +/// selected, and is refused as a destination once the selection leaves it out. +#[test] +fn node_move_into_new_compound_path_on_a_locked_artboard() { + let mut s = session(); + let p = rect(&mut s); + let q = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let c = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let e = NodeId(s.execute("shape.rectangle", &json!({"x": 340, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + let pasted = ids(&s.execute("edit.paste", &json!({"center": [1200, 200]})).unwrap()["ids"]); + assert_eq!(pasted.len(), 2); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(s.doc().unwrap().selection.objects.iter().map(|id| id.0).collect::>(), [compound], "the new compound path is selected"); + s.execute("node.move", &json!({"id": p.0, "parent": compound, "index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(p), Some(NodeId(compound)), "new art takes the path"); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("node.move", &json!({"id": q.0, "parent": compound, "index": 0})).is_err(), "no longer new art"); + assert_ne!(s.doc().unwrap().doc.parent_of(q), Some(NodeId(compound))); +} + /// The batch, isolation and group cases of [`new_art_on_a_locked_artboard_stays_editable_until_the_selection_leaves_it`], /// with the pasted art `pasted` selected. fn batches_and_isolation_keep_new_art_protected(s: &mut Session, pasted: Vec) { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 1af3310d61..54926e1659 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1878,6 +1878,32 @@ fn a_page_item_with_a_large_id_keeps_its_id() { assert!(s.active().unwrap().doc.node(a).is_none()); } +/// A path the script makes keeps its id when the id is past 2^53, where the script's numbers round. +#[test] +fn a_path_made_with_a_large_id_keeps_its_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(10, 10, 20, 20); p.name = 'big'; vc.log(p.name);"); + assert_eq!(out, vec![json!("big")]); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big")); +} + +/// Assigning `undefined` to the selection, as a lookup past the end of a list gives, throws and +/// leaves the selection as it was; `null` still clears it. +#[test] +fn assigning_undefined_to_the_selection_throws() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];"); + assert!(e.contains("TypeError") || e.contains("not undefined"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + log(&mut s, "app.activeDocument.selection = null;"); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn only_class_constructors_construct() { let (mut s, _, _) = doc(); @@ -2023,14 +2049,41 @@ fn note_is_the_attributes_note() { assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); } +#[test] +fn add_document_starts_from_the_built_in_preset_when_a_saved_one_has_its_name() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "colorMode": "rgb"})).unwrap(); + let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);"); + assert_eq!(out[0], json!([612, 792, "DocumentColorSpace.CMYK"])); + // Recent keeps the built-in preset's name, as it does when no saved preset has it. + assert_eq!(s.prefs.recent_new_docs[0].name, "Letter"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var e = app.documents.addDocument('Print', p); vc.log([e.width, e.height]);"); + assert_eq!(out[0], json!([300, 792])); + assert_eq!(s.prefs.recent_new_docs[0].name, "Custom"); +} + #[test] fn a_profile_starts_from_its_built_in_preset_and_not_a_saved_one_of_the_same_name() { let mut s = Session::new(); - s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb"})).unwrap(); + s.execute( + "file.newPresets.save", + &json!({"name": "Letter", "width": 100, "height": 50, "units": "Millimeters", "colorMode": "rgb", "artboardLayout": "row"}), + ) + .unwrap(); let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);"); assert_eq!(out, vec![json!([612, 792, "DocumentColorSpace.CMYK"])]); let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var d = app.documents.addDocument('Print', p); vc.log([d.width, d.height]);"); assert_eq!(out, vec![json!([300, 792])], "presetSettings goes over the built-in preset"); + // Several artboards are laid out as the built-in preset lays them out when no saved preset + // has its name, and the title is kept. + let three = "var p = new DocumentPreset(); p.numArtboards = 3; p.title = 'Three';\ + p.artboardLayout = undefined; p.artboardRowsOrCols = undefined; p.artboardSpacing = undefined; var d = app.documents.addDocument('Print', p);\ + var r = []; for (var i = 0; i < d.artboards.length; i++) r.push(d.artboards[i].artboardRect); vc.log([d.name, r]);"; + let out = log(&mut s, three); + let unshadowed = log(&mut Session::new(), three); + assert_eq!(out[0][0], json!("Three")); + assert_eq!(out[0][1].as_array().map(Vec::len), Some(3), "{out:?}"); + assert_eq!(out, unshadowed, "the saved preset changes nothing"); } #[test] @@ -2511,6 +2564,57 @@ fn wrappers_go_stale_after_revert() { } } +/// A layer's collections read before File › Revert do not list the loaded document's art, even +/// where the loaded layer has the same id. +#[test] +fn a_layers_collections_read_before_a_revert_are_stale() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-lists"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for list in ["pathItems", "pageItems", "groupItems", "compoundPathItems", "layers"] { + let source = format!( + "var d = app.activeDocument, c = d.layers[0].{list}; vc.log(c.length >= 0); d.pageItems[0].name = 'changed'; vc.run('file.revert');\ + try {{ c.length; vc.log('ran'); }} catch (e) {{ vc.log('stale'); }} vc.log(d.layers[0].{list}.length >= 0);" + ); + assert_eq!(log(&mut s, &source), vec![json!(true), json!("stale"), json!(true)], "{list}"); + } +} + +/// An artboard read before File › Revert is stale, even though the loaded artboard has the same +/// id; the document's `artboards` read before it lists the loaded ones. +#[test] +fn an_artboard_read_before_a_revert_is_stale() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-artboard"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, bs = d.artboards, b = bs[0], saved = b.name; b.name = 'changed'; vc.run('file.revert');\ + try { b.name = 'wrong'; vc.log('ran'); } catch (e) { vc.log(e.message); } vc.log(bs[0].name == saved);", + ); + assert_eq!(out, vec![json!("Stale artboard"), json!(true)]); +} + +/// A key that is the text of a number but not an array index reaches an indexer as a number, and +/// a layer's collections and `artboards` look it up as a name, as the document's `pageItems` does. +/// `index()` still takes a number as a position. +#[test] +fn scoped_collections_find_names_that_are_numbers() { + let (mut s, ..) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, l = d.layers[0], i = l.pageItems[0]; i.name = '-1'; l.layers.add().name = '1.5';\ + d.artboards[0].name = '-1';\ + vc.log(l.pageItems['-1'] === i); vc.log(l.pathItems['-1'] === i); vc.log(l.layers['1.5'].name);\ + vc.log(d.artboards['-1'].name); vc.log(l.pageItems['-2'] === undefined); vc.log(l.pageItems.index(0) === i);\ + try { l.pageItems.index(-1); vc.log('ran'); } catch (e) { vc.log(e.message); }\ + try { d.artboards.index(-1); vc.log('ran'); } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out, vec![json!(true), json!(true), json!("1.5"), json!("-1"), json!(true), json!(true), json!("Not found"), json!("Not found")]); +} + /// A layer's or group's `pageItems` reads a name, `index` and `toString` as the document's does. #[test] fn a_layers_page_items_read_names_as_the_documents_do() { @@ -2697,6 +2801,9 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { "app.activeDocument.groupItems.getByName('locked').pageItems", "app.activeDocument.layers[0].compoundPathItems", "app.activeDocument.compoundPathItems", + "app.activeDocument.pathItems", + "app.activeDocument.groupItems.getByName('locked').pathItems", + "app.activeDocument.compoundPathItems[0].pathItems", ] { // The error is caught, so the run keeps whatever `removeAll()` did before it threw. let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);")); @@ -3021,6 +3128,18 @@ fn an_unknown_menu_command_throws_and_names_it() { assert!(failure(&mut s, "app.executeMenuCommand('acmeNoSuchMenu');").contains("acmeNoSuchMenu")); } +/// `getIsFileOpen` folds `\` into `/` and letter case only by Windows' rules: on macOS and Linux a +/// `\` is part of a file name, so `a\b.svg` is not the file `b.svg` in the folder `a`. +#[test] +fn get_is_file_open_compares_paths_by_the_platform_s_rules() { + use crate::script::dom::path_key_on; + assert_ne!(path_key_on("/tmp/work/a\\b.svg", false), path_key_on("/tmp/work/a/b.svg", false)); + assert_ne!(path_key_on("/tmp/work/A.svg", false), path_key_on("/tmp/work/a.svg", false)); + assert_eq!(path_key_on("/tmp/work/", false), path_key_on("/tmp/work", false)); + assert_eq!(path_key_on("C:\\Work\\A.svg", true), path_key_on("c:/work/a.svg", true)); + assert_eq!(path_key_on("C:\\Work\\", true), path_key_on("c:/work", true)); +} + #[test] fn hostile_dom_values_do_not_reenter_or_exceed_limits() { let (mut s, _, _) = doc(); @@ -3312,6 +3431,202 @@ 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);\ + sub.pathItems[0].name = 'B'; P[0].name = 'B'; G[1].name = 'B'; G[0].name = 'B';\ + vc.log(G.getByName('B') === G[0]); vc.log(G.index('B') === G[0]); vc.log(P.getByName('B') === P[0]); 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); + // With the sublayer's path above the group, the layer's own path and both of the group's paths + // named `B`, each collection's named lookups give its own topmost path. + assert_eq!(out[11..], [json!(true), json!(true), json!(true), 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); + } + // Caught inside the script, each refusal leaves both collections as they were, and the group, + // shown and unlocked itself, is refused for its locked layer. + let out = log( + &mut s, + "var L = app.activeDocument.layers[0], g = app.activeDocument.groupItems[0], m = [];\ + var n = [L.pathItems.length, g.pathItems.length];\ + try { L.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\ + try { g.pathItems.add(); } catch (e) { m.push(e.message); }\ + try { g.pathItems.ellipse(); } catch (e) { m.push(e.message); }\ + vc.log(m); vc.log([L.pathItems.length, g.pathItems.length]); vc.log(n);", + ); + let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(refused.len(), 3, "{out:?}"); + assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}"); + assert_eq!(out[1], out[2], "the collections are unchanged inside the script"); + 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}"); +} + +/// A collection read with a name gives what its `getByName` gives, in a layer's or a group's +/// collections as in the document's, and a name nothing has is not `in` it. +#[test] +fn collections_read_with_a_name_give_the_named_object() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.groupItems[0], r = g.pageItems[0]; r.name = 'Logo'; g.name = 'G';\ + vc.log([g.pageItems['Logo'] === r, g.pathItems['Logo'] === r, d.pathItems['Logo'] === r, d.groupItems['G'] === g,\ + d.layers[0].groupItems['G'] === g, d.layers['Layer 1'] === d.layers[0], d.artboards[d.artboards[0].name] === d.artboards[0]]);\ + vc.log(['Logo' in g.pageItems, 'missing' in g.pageItems, 'missing' in g.pathItems, 'missing' in d.layers, 'missing' in d.artboards]);\ + var m = ''; try { g.pageItems['missing']; } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out[0], json!([true, true, true, true, true, true, true]), "{out:?}"); + assert_eq!(out[1], json!([true, false, false, false, false]), "{out:?}"); + assert_eq!(out[2], json!("Not found"), "{out:?}"); +} + +/// A compound path's `pathItems.removeAll()` leaves it, empty, as `remove()` of its last path +/// does. +#[test] +fn clearing_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 out = log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length]);"); + assert_eq!(out, vec![json!(["CompoundPathItem", 0])]); + let d = &s.active().unwrap().doc; + assert!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty"); +} + +/// A Live Paint group's collections make nothing in it: what they made would join the group's +/// paths instead of being one of its objects. +#[test] +fn collections_of_a_live_paint_group_make_nothing() { + const REFUSED: &str = "Cannot add an object to a Live Paint group"; + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let out = log( + &mut s, + "var g = app.activeDocument.pageItems[0], m = [];\ + try { g.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\ + try { g.pathItems.add(); } catch (e) { m.push(e.message); }\ + try { g.groupItems.add(); } catch (e) { m.push(e.message); }\ + try { g.compoundPathItems.add(); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(refused.len(), 4, "{out:?}"); + assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + #[test] fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { let (mut s, a, b) = doc(); @@ -3353,6 +3668,18 @@ fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { assert!(failure(&mut s, src).contains("only paths"), "{src}"); } assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // Caught inside the run, the refused move leaves the object where it was and the compound + // path's members as they were. + for (make, to) in + [("d.groupItems.add()", "C"), ("d.groupItems.add()", "C.pathItems[0], ElementPlacement.PLACEBEFORE"), ("d.compoundPathItems.add()", "C")] + { + let src = format!( + "var d = app.activeDocument, C = d.compoundPathItems.getByName('C'), o = {make};\ + try {{ o.move({to}); vc.log('moved'); }} catch (e) {{ vc.log(String(e).indexOf('only paths') >= 0); }}\ + vc.log(o.parent.typename); vc.log(C.pathItems.length); vc.log(C.pathItems[0].parent.typename);" + ); + assert_eq!(log(&mut s, &src), [json!(true), json!("Layer"), json!(2), json!("CompoundPathItem")], "{src}"); + } assert!(s.execute("object.newGroup", &json!({"compound": 1})).unwrap_err().to_string().contains("true or false")); } @@ -4143,6 +4470,29 @@ fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() { assert!(!d.node(a).unwrap().extras().pixel_aligned); } +/// A pixel-aligned compound path snaps a path that was not aligned when it takes it in. +#[test] +fn a_pixel_aligned_compound_path_snaps_a_path_moved_into_it() { + 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 cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let loose = rect(&mut s, 200.25, 20.5, 30.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(loose).unwrap().extras().pixel_aligned); + s.execute("node.move", &json!({"id": loose.0, "parent": cid.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(loose), Some(cid)); + // Both paths have a 1 pt stroke, so the grid puts their edges where it put the aligned path's. + let (b, at) = (d.node(loose).unwrap().geometric_bounds().unwrap(), d.node(a).unwrap().geometric_bounds().unwrap()); + assert_ne!(b.x0, 200.25); + for (v, w) in [(b.x0, at.x0), (b.y0, at.y0), (b.x1, at.x1), (b.y1, at.y1)] { + assert_eq!(v.fract(), w.fract(), "{b:?} is on the pixel grid as {at:?} is"); + } +} + /// 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] @@ -4186,18 +4536,39 @@ fn a_compound_paths_path_items_are_page_items() { 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()"] { + // The path creation methods make the new path inside the compound path. + for (made, call) in + ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] + .into_iter() + .enumerate() + { 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)); + assert_eq!(out, [json!("made"), json!(made + 3)], "{call}"); } 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 a_compound_paths_path_items_add_makes_the_path_inside_it() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var c = app.activeDocument.layers[0].compoundPathItems.add(); var p = c.pathItems.add(); p.setEntirePath([[0, 0], [10, 0], [10, 10]]);\ + var r = c.pathItems.rectangle(50, 20, 10, 10); vc.log(c.pathItems.length); vc.log(p.parent.typename); vc.log(r.parent.typename);\ + vc.log(c.pathItems[0].width);", + ); + assert_eq!(out, [json!(2), json!("CompoundPathItem"), json!("CompoundPathItem"), json!(10)]); + let d = &s.active().unwrap().doc; + let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); + assert_eq!(compound.children().unwrap().len(), 2); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); +} + #[test] fn art_collections_follow_edits_between_reads() { let (mut s, _, _) = doc(); @@ -4343,6 +4714,18 @@ fn has_selected_artwork_keeps_selected_objects_in_other_layers() { } } +#[test] +fn layer_lists_follow_edits_between_reads() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var L = app.activeDocument.layers, n = L.length; for (var i = 0; i < L.length; i++) L[i];\ + var made = L.add(); made.name = 'Top'; vc.log(L.length - n); vc.log(L[0].name); vc.log(L.getByName('Top').name);\ + made.remove(); vc.log(L.length - n);", + ); + assert_eq!(out, [json!(1), json!("Top"), json!("Top"), json!(0)]); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index df15b5c6ea..153e348cd9 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -282,6 +282,43 @@ fn path_items_remove_all_refuses_paths_on_a_locked_artboard() { assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); } +/// A clipping group's `pathItems` lists only its clipping path when its other art is a group: +/// `removeAll()` throws and deletes nothing, as `pageItems.removeAll()` does, so the group does not +/// become the clipping path. +#[test] +fn path_items_remove_all_refuses_a_clipping_path_whose_group_keeps_other_objects() { + let (mut s, a, b) = doc(); + s.execute("object.group", &json!({"ids": [b.0]})).unwrap(); + let inner = s.active().unwrap().doc.parent_of(b).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, inner.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let clip = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("object.setProps", &json!({"ids": [clip.0], "name": "clip"})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.groupItems.getByName('clip').pathItems.removeAll();"); + assert!(e.contains("cannot delete a clipping path") && e.contains(&a.0.to_string()), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +/// The document's `pathItems.removeAll()` deletes a compound path whose paths it all lists, so a +/// clipping group that holds only its clipping path and that compound path is left with nothing +/// and is not refused. +#[test] +fn path_items_remove_all_counts_compound_paths_it_empties() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.active().unwrap().doc.parent_of(b).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, compound.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.removeAll();"); + let d = &s.active().unwrap().doc; + assert!(d.node(a).is_none() && d.node(b).is_none() && d.node(compound).is_none()); +} + #[test] fn shape_creators_use_documented_defaults_and_y_up() { let mut s = Session::new(); @@ -339,6 +376,76 @@ fn shape_creators_reject_bad_sizes_without_change() { assert_eq!(undo_steps(&s), steps); } +#[test] +fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { + // `pathItems[1]` is `b`. + let (mut s, a, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[1].pathPoints[0].remove();"); + let st = s.active().unwrap(); + assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3)); + let sel = &st.selection; + // A removal renumbers the direct selection: the selected anchor after the removed one moves + // down one place. + assert_eq!(sel.anchors.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 0)]), "{sel:?}"); + assert!(sel.objects.contains(&a)); + // Moving a point keeps the anchors selected. + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];"); + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); +} + +/// Points are found by their index across subpaths, through changes that wait to be written and +/// removals that change how many points a subpath has or remove a subpath. +#[test] +fn points_are_found_across_subpaths_as_their_counts_change() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let pt = |x: f64| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false}); + let subs = json!([ + {"anchors": [pt(0.0), pt(1.0)], "closed": false}, + {"anchors": [pt(2.0)], "closed": false}, + {"anchors": [pt(3.0), pt(4.0), pt(5.0)], "closed": false}, + ]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems[0].pathPoints; vc.log(q.length);\ + for (var i = 0; i < q.length; i++) q[i].anchor = [i * 10, 7];\ + vc.log(q[2].anchor); vc.log(q[5].anchor);\ + q[1].remove(); vc.log(q.length); vc.log(q[1].anchor); vc.log(q[4].anchor);\ + q[0].remove(); vc.log(q.length); vc.log(q[0].anchor); vc.log(q[3].anchor); vc.log(q[4] === undefined);", + ); + let want = + [json!(6), json!([20, 7]), json!([50, 7]), json!(5), json!([20, 7]), json!([50, 7]), json!(4), json!([20, 7]), json!([50, 7]), json!(true)]; + assert_eq!(out, want); + let n = node(&s, a); + let counts: Vec = n.path_data().unwrap().subpaths.iter().map(|sp| sp.anchors.len()).collect(); + assert_eq!(counts, vec![1, 3]); +} + +/// Moving every point of a path, one at a time, keeps the index of where its subpaths' points +/// start: the index is built again only when a change adds or removes points. +#[test] +fn moving_each_point_keeps_the_index_of_the_subpaths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let subs: Vec = + (0..50).map(|i| json!({"anchors": [{"x": i, "y": 0, "in": [i, 0], "out": [i, 0], "smooth": false}], "closed": false})).collect(); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); + let before = crate::script::dom::index_builds(); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems[0].pathPoints; for (var i = 0; i < q.length; i++) q[i].anchor = [i, 7]; vc.log(q[49].anchor);", + ); + assert_eq!(out, vec![json!([49, 7])]); + let built = crate::script::dom::index_builds() - before; + assert!(built <= 3, "the index was built {built} times"); +} + #[test] fn set_entire_path_replaces_points_and_keeps_closed() { let (mut s, a, _) = doc(); @@ -358,6 +465,34 @@ fn set_entire_path_replaces_points_and_keeps_closed() { assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner)); } +#[test] +fn control_bounds_take_in_direction_handles() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var r = app.activeDocument.pathItems[0]; vc.log(r.controlBounds); vc.log(r.visibleBounds);\ + var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [100, 0]]);\ + n.pathPoints[0].rightDirection = [50, 80]; vc.log(n.controlBounds); vc.log(n.visibleBounds);", + ); + assert_eq!(out[0], out[1], "a rectangle has no handles outside its visible bounds"); + let edges = |v: &Value| (0..4).map(|i| v[i].as_f64().unwrap()).collect::>(); + let (control, visible) = (edges(&out[2]), edges(&out[3])); + assert!(control[1].max(control[3]) >= 80.0 - 1e-9, "{control:?}"); + assert!(visible[1].max(visible[3]) < 80.0, "{visible:?}"); + assert!(control[0] <= visible[0] && control[2] >= visible[2], "{control:?} holds {visible:?}"); +} + +/// A clipping group's control bounds are its clipping path's: art outside the clip is left out, as +/// it is from the visible bounds. +#[test] +fn a_clipping_groups_control_bounds_leave_out_the_clipped_art() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.controlBounds); vc.log(g.visibleBounds);"); + assert_eq!(out[0], out[1]); +} + #[test] fn hostile_set_entire_path_input_is_bounded() { let (mut s, _, _) = doc(); @@ -1068,6 +1203,29 @@ fn identity_transforms_of_an_empty_path_do_nothing() { } } +#[test] +fn turning_or_scaling_an_empty_path_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.rotate(90); n.resize(50, 50);"); + assert_eq!(undo_steps(&s), 1, "only the path is added"); +} + +/// Scaling stroke weights and effects by the scale itself without moving the object is refused for +/// a path with no anchors as it is for one with bounds, and the stroke weight stays. +#[test] +fn scaling_line_widths_alone_is_refused_for_an_empty_path() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;"); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(50, 50, false, false, false, false, 50);"); + assert!(e.contains("changeLineWidths other than 100 with changePositions false"), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(4)]); +} + /// The paint of the fill (`fill`) or stroke of `id`. fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint { let n = node(s, id); @@ -1792,6 +1950,39 @@ fn filled_and_stroked_true_give_the_new_art_paint() { } } +/// The pattern of a path with no anchors turns and scales about the origin, as a path without +/// points takes any transformation; each call is one undo step. +#[test] +fn transforming_the_pattern_of_an_empty_path_turns_it() { + for source in [ + "app.activeDocument.pathItems[0].rotate(90, true, true, true, true);", + "app.activeDocument.pathItems[0].resize(50, 50, true, true, true, true);", + "app.activeDocument.pathItems[0].resize(50, 50, false, true, false, true);", + ] { + let (mut s, _) = doc_with_paints(); + s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 4;"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].fillColor.typename);"), vec![json!("PatternColor")]); + let (before, steps) = (art(&s), undo_steps(&s)); + log(&mut s, source); + assert_ne!(art(&s), before, "{source}: the pattern transforms"); + assert_eq!(undo_steps(&s), steps + 1, "{source}: one undo step"); + } +} + +/// Scaling a path with no anchors with its stroke weights scales its own stroke weight. +#[test] +fn scaling_an_empty_path_with_line_widths_scales_its_stroke() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.stroked = true; n.strokeWidth = 10; n.strokeDashes = [3, 4];"); + let steps = undo_steps(&s); + log(&mut s, "app.activeDocument.pathItems[0].resize(200, 200, true, false, true, false, 200);"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeWidth);"), vec![json!(20)]); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].strokeDashes);"), vec![json!([6, 8])], "the dashes scale too"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step"); +} + #[test] fn filled_true_throws_for_a_new_art_pattern_it_cannot_give() { let placed = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::scale(2.0) }; diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 3952955779..8042d5da37 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -1493,6 +1493,93 @@ fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() { assert_eq!(state(&s), before); } +/// A script that ends past the allowance the person's last answer gave is asked again before its +/// changes are kept. +#[test] +fn a_finished_run_past_its_last_allowance_asks_again() { + let draw = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('shape.rectangle', {x:2,y:1,width:1,height:1});"; + let point = "var P = app.activeDocument.pathItems, q = P[0];\ + for (var k = 1; k < P.length; k++) if (P[k].pathPoints.length > q.pathPoints.length) q = P[k];\ + var p = q.pathPoints; for (var i = 0; i < p.length; i++) p[i].anchor = [i * 3, -4 - i];"; + // The path the script moves has 600 anchors, so its point changes weigh more than the + // rectangles do. + let two_docs = || { + let mut s = two_docs(); + let id = s.documents()[1].doc.layers[0].children().unwrap()[0].id; + let anchors: Vec = (0..600) + .map(|i| json!({"x": f64::from(i), "y": f64::from(i % 7), "in": [f64::from(i), 0.0], "out": [f64::from(i), 0.0], "smooth": false})) + .collect(); + s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); + s + }; + let added = |source: &str| { + let mut s = two_docs(); + let start = s.documents()[1].doc.clone(); + assert_eq!(run(&mut s, source).unwrap()["ok"], true); + start.retained_bytes_each(&s.documents()[1].doc).1 as u64 + }; + let whole = format!("{draw} {point}"); + let (m, p) = (added(draw), added(&whole) - added(draw)); + // The rectangles go past one object, which asks once, and stay within twice the bytes; the + // point changes, written as the script ends, then go past the second allowance and also past + // the third. + let b = (m + p - 1) / 3; + assert!(m <= 2 * b && 3 * b < m + p && m + p <= 4 * b, "m {m}, p {p}, b {b}"); + TEST_GROWTH.with(|g| g.set(Some(1))); + TEST_GROWTH_BYTES.with(|g| g.set(Some(b))); + let mut s = two_docs(); + s.script_frames = true; + run(&mut s, &whole).unwrap(); + let mut questions = 0; + let done = loop { + assert!(questions < 10); + if s.script_waiting() { + questions += 1; + s.script_continue(); + } + if let Some(r) = s.script_pump() { + break r; + } + }; + TEST_GROWTH.with(|g| g.set(None)); + TEST_GROWTH_BYTES.with(|g| g.set(None)); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(questions, 3, "asked mid-run, as the script ended, and again for the third allowance"); +} + +/// A script that ends with nothing left to write, past the allowance the person's last answer +/// gave, is asked again before its changes are kept. +#[test] +fn a_run_that_ends_past_its_last_allowance_with_nothing_to_write_asks_again() { + TEST_GROWTH.with(|g| g.set(Some(20))); + // 21 rectangles go past the first allowance, and the 45 the document opens go past the + // second and stay within twice it, which leaves them past the third. + let rects: String = (0..45).map(|i| format!(r#""#)).collect(); + let svg = format!(r#"{rects}"#); + let data = vectorcraft_format::base64_encode(svg.as_bytes()); + let source = format!( + "for (var i = 0; i < 21; i++) vc.run('shape.rectangle', {{x:i,y:1,width:1,height:1}});\ + vc.run('document.open', {{name: 'a.svg', dataBase64: '{data}'}});" + ); + let mut s = two_docs(); + s.script_frames = true; + run(&mut s, &source).unwrap(); + let mut questions = 0; + let done = loop { + assert!(questions < 10); + if s.script_waiting() { + questions += 1; + s.script_continue(); + } + if let Some(r) = s.script_pump() { + break r; + } + }; + TEST_GROWTH.with(|g| g.set(None)); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(questions, 3, "asked for the rectangles, for the document, and again as the script ended"); +} + #[test] fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { TEST_GROWTH.with(|g| g.set(Some(20))); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 28448679d2..f528df9db6 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -151,7 +151,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 \ toString typename visible visible= zOrder zOrderPosition", ), @@ -160,7 +160,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", ), ("GroupItems.", "prototype"), @@ -239,12 +239,12 @@ const INSIDE: &[(&str, &str)] = &[ strokeWidth strokeWidth= stroked stroked=", ), ("PathPoints.", "prototype"), - ("PathPoints.prototype.", "add constructor index length parent removeAll typename"), + ("PathPoints.prototype.", "add constructor index length parent removeAll toString typename"), ("PathPoint.", "prototype"), ( "PathPoint.prototype.", "anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \ - rightDirection= selected selected= typename", + rightDirection= selected selected= toString typename", ), ("Tags.", "prototype"), ("Tags.prototype.", "add constructor getByName index length parent removeAll typename"), diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 4a3aadb9cb..8be19d08f8 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -589,7 +589,8 @@ fn install_checked( let v = i.write_hosted(d)?; undo.define_global(i, &name, Prop::Data { value: v, flags: 0 })?; } - Ok(()) + // The prototypes, constructors and members are made without a reservation of their own. + i.reserve_heap(0) } /// Adds the global properties `globals`, each read with its getter and assigned with its setter as diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 44ad23caee..2752334585 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -861,6 +861,31 @@ fn with_thing(r: &mut Realm, make: Option) { r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); } +#[test] +fn host_classes_that_do_not_fit_the_heap_end_with_the_heap_limit() { + let mut r = realm(1_000_000); + let interp = r.interp(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes; + let class = HostClass { name: "Empty".into(), parent: None, members: Vec::new(), info: Vec::new(), index: None, construct: None }; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap)); +} + +/// A new object of a host class adds its handle to the heap's total as well as itself, so objects +/// made one after another count each other's handles before a collection does. +#[test] +fn an_object_of_a_host_class_counts_its_handle_toward_the_heap() { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + let interp = r.interp(); + let handle: Vec = (0..64).map(f64::from).collect(); + let before = interp.heap.bytes; + interp.write_host_ref(&host_ref("Thing", &handle)).unwrap(); + let added = interp.heap.bytes - before; + assert!(added >= crate::heap::OBJECT_BYTES + crate::host_classes::handle_bytes(handle.len()), "{added}"); +} + #[test] fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { let mut r = realm(1_000_000); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index bad3e0044c..c0ae022f6f 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1135,6 +1135,22 @@ mod tests { }) } + /// The dialog reads rows as `file.new` does: a whole number from 1 to the artboard limit, + /// `4.0` included, and a fractional, zero or larger count is refused with nothing changed. + #[test] + fn the_dialog_reads_rows_as_file_new_does() { + let mut app = app(); + open(&mut app); + set(&app, "artboards", json!(5)).unwrap(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4.0})).unwrap(); + assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); + for rows in [json!(3.5), json!(0.4), json!(MAX_ARTBOARDS + 1), json!(0)] { + let e = set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": rows})).unwrap_err(); + assert!(e.contains("can't take"), "{rows}: {e}"); + assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4), "{rows}"); + } + } + /// Press Create: the dialog files its answer and the pump runs `file.new` with it. fn create(app: &mut VectorcraftApp) { let ctx = ctx(app); diff --git a/docs/mcp.md b/docs/mcp.md index 9c5f1bc38b..cfd8a20896 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3179,7 +3179,8 @@ through `$`: (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the visible bounds with the anchors and direction handles of the shown paths in the item; a clip group or clipping - layer takes in only its clipping path's; in a document in the back, type + layer takes in only its clipping path's, and the source art a Shaper Group or a tracing keeps is left out; in a + document in the back, type not measured yet is measured first, as the switch to that document would measure it; a valid `position`, `left`, `top`, `width` or `height` equal to the value an object that holds no type, symbol instance or placed document already has is not applied, and its document stays in the back), `editable` (false for an @@ -3222,7 +3223,9 @@ through `$`: including guide paths while Lock Guides is on, throw `Cannot select`. `move` with the object itself as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds - it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). An object with nothing in it, such + it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). The compound path's + `pathItems.removeAll()` also leaves it, empty. `pathItems.removeAll()` throws and deletes nothing when it would + delete the clipping path of a group or layer that keeps other objects. An object with nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws @@ -3272,7 +3275,8 @@ through `$`: shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too (VectorCraft's own rule). A read with the text of a number that is not an array index, such as - `pageItems["-1"]`, `pageItems[1.5]` or `documents["NaN"]`, looks for an object of that name and gives `undefined` + `pageItems["-1"]`, `pageItems[1.5]` or `documents["NaN"]`, on the document's collections, a layer's, group's or + compound path's collections and `artboards`, looks for an object of that name and gives `undefined` when nothing has it; assigning to such a name is then ignored outside strict mode and throws a `TypeError` in strict mode code or with `#strict on`, instead of `Not found`. This applies only to the text JavaScript writes for that number: `pageItems["1.50"]` is a plain name and throws `Not found` when nothing has it. `"-1" in pageItems` is true when an object has that name; `index(key)` takes a number as @@ -3294,10 +3298,11 @@ 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, 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 `pathItems`, + `Stale page item`. Layer objects also become stale after their document is reverted, and so do the `layers`, + `pageItems`, `groupItems`, `compoundPathItems` and `pathItems` of a layer, group or compound path read before the + revert (`Stale page item`) and `Artboard` objects (`Stale artboard`); the document's own collections list the + reverted document. + `removeAll()` on any `pathItems`, 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 that are not ruler guides. `removeAll()` on the `pathItems` of a compound path that is such a clipping path throws the same way, since it would leave the clipping path empty. The document's `pathItems.removeAll()` still deletes the paths of a group that @@ -3350,13 +3355,13 @@ through `$`: 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`. `opacity` reads rounded to 4 decimals; assigning the number it reads, or one that stores as the same opacity, runs no command. `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`. @@ -3373,9 +3378,9 @@ through `$`: 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. + depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers. A compound + path's `pathItems` are a `PathItems` collection: `add()` and its shape methods make the new path inside 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 @@ -3416,11 +3421,12 @@ through `$`: 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, and a document the run opened in which an artboard was chosen. The chosen artboard stays active when another is inserted before it, even if it was already the active - one. 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. `GroupItems.createFromFile` on a - collection whose document, layer or group was deleted throws `Stale page item` or `Stale document` first. + one. `insert`, `remove` and `setActiveArtboardIndex` throw a `RangeError` for an index outside the list. Reading + an index past the last artboard gives `undefined` from `artboards[i]` and throws `Not found` from + `artboards.index(i)`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws + `Stale artboard`. `Layer.blendingMode`, `artworkKnockout` and `sliced` and `GroupItems.createFromFile` throw an + error that says they are not available yet. `GroupItems.createFromFile` on a collection whose document, layer or + group was deleted throws `Stale page item` or `Stale document` first. - `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; in an Image Trace object, index 0 is refused and changes nothing, @@ -3429,7 +3435,8 @@ through `$`: 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 + The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path (its layer and + groups shown and unlocked too, and not on a locked artboard unless it is new art there that is still selected), 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, and a pixel-aligned compound path snaps a path it takes to the pixel grid. `node.move` leaves the @@ -3742,8 +3749,18 @@ through `$`: new path goes on that editing layer, and the call throws and makes no path when that layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. These creation commands take `onLayer: layerId` to draw normally on that layer and - record this placement for replay. A null `onLayer` draws normally on the active layer. - A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + record this placement for replay. A null `onLayer` draws normally on the active layer. 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 Live Paint group's `pathItems`, `groupItems` and `compoundPathItems` throw + `Cannot add an object to a Live Paint group` from their `add()` and the shape methods, and nothing is made; a Live + Paint group that is hidden or locked, or that is in a hidden or locked layer or group, throws the hidden-or-locked + error above instead. 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`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to @@ -3759,6 +3776,13 @@ through `$`: the points of another path in the same Objects on Path group, and when the script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. + Setting `closed` to true on a path with no points gives it an empty closed subpath. When the points are written, + selected anchors and segments that the path no longer has are deselected, and the path is deselected when none of + its selected anchors is left or it has no points. `PathPoint.remove()` keeps the rest of the direct selection: selected anchors after the removed point are renumbered and stay + selected, except that a selected segment that starts or ends at the removed point is deselected, and so is its other + anchor unless another selected segment still uses it. When every anchor left is selected and no segment is, the + path is selected as a whole. On a path aligned to the pixel grid, or in an object that is, which is written at each + change, the removal can clear the direct selection. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, @@ -8649,7 +8673,8 @@ and `layerRows`, the rows highlighted in the panel. 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, 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 + a path into a shown, unlocked compound path whose layer and groups are also shown and unlocked and that is not on + a locked artboard unless it is new art there that is still selected (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/roadmap.md b/docs/roadmap.md index a86bbe6ebe..f6e6d14c9a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -210,7 +210,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the rest of the script document model (the `pathItems` of layers and groups, text lines, gradient stops and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the `pathItems` of layers, groups and compound paths make paths inside them; the rest of the script document model (text lines, gradient stops and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1bba3d826..c6f55e7d1c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1119,6 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - 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: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.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, guide state, selected points, 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`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`. - Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`. - Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. `crates/engine/src/tests/script_dom_images.rs`. - Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`. @@ -1130,7 +1131,7 @@ 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; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. 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. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.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; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. 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. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.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, and `unitScaleRatio` is a percentage, with 100 at full size (`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`); a batch submitted after a spool failure was reported clears it once the worker sends every job of the batch without a failure, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.