From fe0c8da91908b62ed01a1c1517a638f5b08e3d91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:51:32 -0800 Subject: [PATCH 001/106] Scripts: layers and groups give their own path items Layer.pathItems and GroupItem.pathItems now return a PathItems collection for the paths directly in the layer or group, topmost first, as the Layer and GroupItem pages describe them (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). Before, both threw an error that said they were not available yet. - The collection has the members of Document.pathItems. Its parent is the layer or group, and length, [i], index and getByName read only that container's paths, so a path inside a group, a compound path or a sublayer is not listed. - add() and the shape creators put the new path on top of the layer's or group's contents and leave the current layer as it was. The path is made with the container's layer current (layer.setCurrent) and, for a group, moved into it with node.move, in the run's one undo step. - VectorCraft's own rule: 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. - The last four path lists stay cached while their documents are unchanged, so a loop over a large layer or group builds its list once. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 6 +- crates/engine/src/script/dom/layers.rs | 24 +- crates/engine/src/script/dom/paths.rs | 206 +++++++++++++----- crates/engine/src/tests/script_dom.rs | 117 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 4 +- docs/mcp.md | 20 +- docs/target-app-parity.md | 2 +- 7 files changed, 302 insertions(+), 77 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c600cc84c4..e8d0cc404a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -102,8 +102,10 @@ pub(super) struct State { coords: Cell, items: RefCell>, locked: RefCell>, - /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. - paths: RefCell>, + /// The last [`paths::PATH_LISTS`] lists of paths a document's, a layer's or a group's + /// `pathItems` gave ([`paths`]), least recently used first, each kept while its document is + /// unchanged. + paths: RefCell>, /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3fafaf684b..23e4d58170 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,8 +12,8 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's -//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the -//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! `pageItems`, `groupItems`, `compoundPathItems` and `pathItems`, and a compound path's +//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` //! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. @@ -114,7 +114,7 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> { layer_of(h, arg(a, 0)) } -fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { +pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { let [high, low] = id_parts(id); host_ref("Layer", &[float(h.run), float(uid), high, low]) } @@ -845,6 +845,17 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +/// A layer's or group's `pathItems`: the paths directly in it ([`super::paths`]). +fn held_paths(h: &Host, a: &[Data]) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(super::paths::held_path_items(h, doc.uid, id)); + } + let item = this_item_of(h, a, "GroupItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -897,8 +908,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("pathItems", get(l, held_paths)), ]); - m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), @@ -1320,6 +1332,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("pathItems", get(l, held_paths)), ("zOrderPosition", get(l, layer_z_position)), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)), ("isIsolated", get(l, layer_is_isolated)), @@ -1328,8 +1341,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("zOrder", method(l, layer_z_order)), ]); layer.extend( - ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] - .map(|m| later(l, "Layer", m)), + ["textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), ); vec![ class("Layer", None, layer, None), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 32401db1d0..87287c5c27 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -13,7 +13,9 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside -//! groups and compound paths included. +//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in +//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden +//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, throws `Cannot edit` with nothing changed. //! - A path in a compound path or compound shape reads that owner's paint, which the paint @@ -23,8 +25,8 @@ //! fill or stroke only. //! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes //! them all. -//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever -//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's +//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. @@ -56,8 +58,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, - float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, edit_item, editable, find_doc, float, + frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -263,21 +265,48 @@ fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { r } -// ---- Document.pathItems ---- +// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ---- -/// The ids of a document's paths, in the order of its page items. -fn path_items(h: &super::Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.paths.borrow() - && *uid == st.uid - && std::sync::Arc::ptr_eq(doc, &st.doc) +/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the +/// document's), and the ids it listed then. +pub(super) type PathList = (u64, Arc, Option, Rc>); + +/// How many lists of paths [`super::State`] keeps at once. +pub(super) const PATH_LISTS: usize = 4; + +/// The ids of a document's paths, in the order of its page items, or of the paths directly in the +/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their +/// documents are unchanged, so a loop over a collection builds its list once. A new list of a +/// container is charged by the objects it looks at. +fn path_items(h: &super::Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { { - return ids.clone(); + let mut lists = h.dom.paths.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } } - let all = super::page_items(h, st); - let ids: Rc> = - Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); - *h.dom.paths.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); - ids + let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. }); + let ids: Rc> = match container { + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect()) + } + None => { + let all = super::page_items(h, st); + Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect()) + } + }; + let mut lists = h.dom.paths.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= PATH_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), container, ids.clone())); + Ok(ids) } pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { @@ -285,32 +314,57 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) } -fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "PathItems") +/// The `pathItems` of the layer or group `id` in the document `uid`. +pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { + let [high, low] = id_parts(id); + host_ref("PathItems", &[float(h.run), float(uid), high, low]) +} + +/// The document of a `PathItems` object, and the layer or group it lists the paths of, if any. +fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low] => { + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let holds = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }))); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(HostError::Type("this is not a PathItems".into())), + } } fn items_length(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) + let (doc, c) = items_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) + let (doc, c) = items_scope(h, a)?; + Ok(match c { + None => host_ref("Document", &[float(h.run), float(doc.uid)]), + Some(c) => with_doc(h, doc, |_, st| { + if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) } + }), + }) } fn items_at(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st, c)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -328,15 +382,15 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } } -/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or +/// locked path, or one in a hidden or locked layer or group, stops it before anything is deleted. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st, c)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) - }); + Ok::<_, HostError>((ids, refused)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); @@ -356,19 +410,53 @@ fn made_id(r: &Data) -> std::result::Result { id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } -/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, -/// and reverses the new path's direction when `reversed`. → the new path. -fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { - let made = on_doc(h, doc.uid, true, |h| { +/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or +/// locked layer or group. +pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group"; + +/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the +/// selection and the current layer kept. With a layer or group `container`, the container's layer +/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made +/// outside the container then moves on top of its contents in the same step; a container that is +/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`] +/// before anything is made. → the new path. +fn make_in( + h: &super::Host, + doc: Doc, + container: Option, + make: impl FnOnce(&super::Host) -> std::result::Result, +) -> Answer { + if let Some(c) = container + && !with_doc(h, doc, |_, st| editable(&st.doc, c)) + { + return Err(HostError::Error(CONTAINER_LOCKED.into())); + } + let made = match container { + None => on_doc(h, doc.uid, true, make)?, + Some(c) => super::atomically(h, |h| { + let id = on_doc(h, doc.uid, true, |h| { + command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?; + make(h) + })?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?, + }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(super::item_ref(h, st, made)) +} + +/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s +/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path. +fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { + make_in(h, doc, container, |h| { let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } Ok(id) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } /// Argument `i`, or `default` when it is left out. @@ -409,13 +497,13 @@ fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result /// `rectangle(top, left, width, height, reversed?)`. fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); let reversed = flag(a, 5, "reversed")?; let p = corner(h, doc, left, top)?; - make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the @@ -455,7 +543,7 @@ fn rounded(r: Rect, rx: f64, ry: f64) -> Vec { /// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, /// reversed = false)`: a closed path with `path.create`. fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); @@ -463,12 +551,12 @@ fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { let reversed = flag(a, 7, "reversed")?; let p = corner(h, doc, left, top)?; let anchors: Vec = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect(); - make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) + make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) } /// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`. fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?; let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?; let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?); @@ -477,7 +565,7 @@ fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Error("ellipse with inscribed true is not available yet".into())); } let p = corner(h, doc, left, top)?; - make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The center of a polygon or star, in document coordinates. @@ -489,32 +577,33 @@ fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r = size(a, 3, Some(50.0), "radius")?; let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?; let reversed = flag(a, 5, "reversed")?; - make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) + make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) } /// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed = /// false)`. fn items_star(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r1 = size(a, 3, Some(50.0), "radius")?; let r2 = size(a, 4, Some(20.0), "innerRadius")?; let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?; let reversed = flag(a, 6, "reversed")?; - make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) + make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) } -/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with -/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open -/// path is set back to none in the same step. +/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or +/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art. +/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set +/// back to none in the same step. fn items_add(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - let made = on_doc(h, doc.uid, true, |h| { + let (doc, into) = items_scope(h, a)?; + make_in(h, doc, into, |h| { let unpainted = { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() @@ -524,10 +613,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } Ok(id) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } // ---- PathItem geometry ---- diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ea3e0ac497..fb7239394a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1597,6 +1597,123 @@ fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); } +#[test] +fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost_first() { + let (mut s, _, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The layer holds `a` (30 pt wide) and a group of `b` (50 pt wide) and `c` (70 pt wide); the + // document's list holds all three, the layer's only `a`, and a sublayer's path is its own. + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers[0], g = L.groupItems[0], P = L.pathItems, G = g.pathItems;\ + vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ + vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ + var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ + vc.log(G.getByName === undefined); vc.log(P[1] === undefined);", + ); + let expected = + [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; + assert_eq!(out[..11], expected); + assert_eq!(out[11..], [json!(false), json!(true)]); +} + +#[test] +fn a_loop_over_a_groups_path_items_builds_the_list_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..1000).map(|i| rect(&mut s, f64::from(i % 40) * 10.0, 10.0, 5.0, 5.0).0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + // Reading `length` and `[i]` 1,000 times each stays within 512 KiB of data only when the list + // of 1,000 paths is not built again for each read. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 19))); + let r = run(&mut s, "var P = app.activeDocument.groupItems[0].pathItems, n = 0; for (var i = 0; i < P.length; i++) if (P[i]) n++; vc.log(n);"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(r.unwrap()["log"], json!([1000])); +} + +#[test] +fn a_layers_path_items_make_their_paths_on_top_of_that_layer() { + let (mut s, ..) = doc(); + let bottom = s.active().unwrap().doc.layers[0].id; + let selected = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + // A new layer becomes the current one; each creator of the first layer's `pathItems` still + // puts its path on top of that layer. + let out = log( + &mut s, + "var d = app.activeDocument, top = d.layers.add(), L = d.layers[1], P = L.pathItems;\ + var make = [function () { return P.rectangle(100, 100, 20, 10); }, function () { return P.roundedRectangle(100, 100, 20, 10); },\ + function () { return P.ellipse(); }, function () { return P.polygon(); }, function () { return P.star(); }, function () { return P.add(); }];\ + for (var i = 0; i < make.length; i++) { var p = make[i](); p.name = 'm' + i; vc.log(p.layer.name === L.name); vc.log(L.pageItems[0].name); }\ + vc.log(d.activeLayer.name === top.name); vc.log(top.pageItems.length); vc.log(P.length);", + ); + let mut expected = Vec::new(); + for i in 0..6 { + expected.extend([json!(true), json!(format!("m{i}"))]); + } + expected.extend([json!(true), json!(0), json!(8)]); + assert_eq!(out, expected); + assert_eq!(undo_steps(&s), steps + 1); + let st = s.active().unwrap(); + let kids = st.doc.node(bottom).unwrap().children().unwrap(); + assert_eq!(kids.last().unwrap().name.as_deref(), Some("m5")); + assert!(st.selection == selected); +} + +#[test] +fn a_groups_path_items_add_puts_the_path_in_the_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0], n = g.pathItems.add(); n.name = 'N';\ + vc.log(n.parent.typename); vc.log(g.pageItems[0].name); vc.log(n.pathPoints.length);\ + var r = g.pathItems.rectangle(50, 50, 10, 10); r.name = 'R'; vc.log(g.pathItems[0].name); vc.log(g.pathItems.length);", + ); + assert_eq!(out, [json!("GroupItem"), json!("N"), json!(0), json!("R"), json!(4)]); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + let top: Vec> = d.node(gid).unwrap().children().unwrap().iter().rev().take(2).map(|n| n.name.as_deref()).collect(); + assert_eq!(top, [Some("R"), Some("N")]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +#[test] +fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { + const REFUSED: &str = "Cannot add a path to a hidden or locked layer or group"; + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let lid = s.active().unwrap().doc.layers[0].id; + let before = format!("{:?}", s.active().unwrap().doc.layers); + s.execute("layer.setProps", &json!({"id": lid.0, "locked": true})).unwrap(); + let locked = format!("{:?}", s.active().unwrap().doc.layers); + for src in ["app.activeDocument.layers[0].pathItems.rectangle(10, 10, 5, 5);", "app.activeDocument.layers[0].pathItems.add();"] { + assert!(failure(&mut s, src).contains(REFUSED), "{src}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); + } + s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap(); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap(); + let hidden = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].pathItems.ellipse();").contains(REFUSED)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), hidden); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": true})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // A group's `pathItems` read after the group is gone throw. + let msg = failure(&mut s, "var g = app.activeDocument.groupItems[0], P = g.pathItems; g.remove(); P.length;"); + assert!(msg.contains("Stale page item"), "{msg}"); +} + #[test] fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 563f23db6f..cc604a7bc4 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -108,7 +108,7 @@ const INSIDE: &[(&str, &str)] = &[ "Layer.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \ dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ - locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ + locked= move name name= opacity opacity= pageItems parent pathItems placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ textFrames= typename visible visible= zOrder zOrderPosition", ), @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ ("GroupItem.", "prototype"), ( "GroupItem.prototype.", - "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems placedItems placedItems= \ rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", ), ("GroupItems.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 6a58f9712c..899b7f5563 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2707,12 +2707,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot layers it throws, since a document keeps at least one layer. Assigning a layer to `activeLayer` runs `layer.setCurrent`. A `Layer` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/) has `typename`, `name`, `visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`, - `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`, - `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run + `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `pathItems`, `zOrderPosition`, `hasSelectedArtwork`, + `isIsolated`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run `layer.setProps`, and `opacity` runs `object.setProps`. `move` and `zOrder` run `node.move`; a layer goes into another layer, to the top level of the document, or directly above or below another layer. Every page item has `layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has - `clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem` + `clipped`, `pageItems`, `groupItems`, `compoundPathItems` and `pathItems`, and a `CompoundPathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/) has `pathItems`. `groupItems` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. @@ -2757,8 +2757,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot run leaves it). The report also lists a document whose active artboard has another index when the run ends because artboards were inserted, removed or reordered before it. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws - `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and - `GroupItems.createFromFile` throw an error that says they are not available yet. + `Stale artboard`. `Layer.blendingMode`, `artworkKnockout` and `sliced` and `GroupItems.createFromFile` throw an + error that says they are not available yet. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and @@ -2777,7 +2777,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing - mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + mode, which stays as it was. A layer's and a group's `pathItems` + (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) + have the same members, and their `parent` is that layer or group. Their `add()` and shape creators put the new path + on top of that layer's or group's contents, with the current layer left as it was: the path is made with the + container's layer as the current one (`layer.setCurrent`) and, for a group, moved into it with `node.move`, in the + run's one undo step. VectorCraft's own rules: a layer's or group's `pathItems` list the paths directly in it, + topmost first, leaving out paths in its groups, compound paths and sublayers; a layer or group that is hidden or + locked, or that is in a hidden or locked layer or group, throws `Cannot add a path to a hidden or locked layer or + group` and no path is made. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3796a198aa..3339695f64 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 58292d605af4e21822b7f4d0bcf7aa94a2a2838e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:23:19 -0800 Subject: [PATCH 002/106] Scripts: app.showColorPicker asks for a color app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor and returns the color picked for OK. Cancel, and OK with the color unchanged, return a new object of the color the script gave. Anything else throws a TypeError. - In the app the run waits at the picker, which previews nothing on the selection. Stop and quitting end the run as at the other script dialogs and close the picker. - A run with nobody to ask takes {kind: "colorPicker", value: color | null} from answers. The report lists the picker with the color it opened on and the answer. - script.run's params text, docs/mcp.md and the Scripts line in docs/target-app-parity.md describe it. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 112 +++++++++++++++++---- crates/engine/src/script/dom.rs | 10 ++ crates/engine/src/script/dom/colors.rs | 14 ++- crates/engine/src/tests/script_dialogs.rs | 72 +++++++++++++ crates/ui-egui/src/dialogs/color_picker.rs | 99 +++++++++++++----- crates/ui-egui/src/dialogs/script_run.rs | 26 ++++- crates/ui-egui/src/script_runs.rs | 17 +++- crates/ui-egui/src/tests/script_dialogs.rs | 107 +++++++++++++++++++- docs/mcp.md | 18 +++- docs/target-app-parity.md | 1 + 11 files changed, 425 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..56bf96195f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK in a CMYK document), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..afda864f6a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -5,12 +5,14 @@ //! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the //! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and //! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel. +//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and +//! returns the color picked for OK, or a new object of the color it was given for Cancel. //! //! In the app the run waits at the call for the person's answer, and spends no fuel while it -//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with -//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no -//! answer left, or with the next answer for another kind of dialog, ends the run. The report's -//! `dialogs` lists each dialog and its answer. +//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts +//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s +//! `answers`; a call with no answer left, or with the next answer for another kind of dialog, +//! ends the run. The report's `dialogs` lists each dialog and its answer. //! //! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`], //! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and @@ -21,6 +23,7 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_color::Color; use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; use super::{Host, console}; @@ -48,21 +51,33 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// `app.showColorPicker`. + ColorPicker, } impl DialogKind { - /// The function's name, which is also the `kind` of an answer and of a report's dialog. + /// The `kind` of an answer and of a report's dialog, which is also the function's name for + /// `alert`, `confirm` and `prompt`. pub fn id(self) -> &'static str { match self { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::ColorPicker => "colorPicker", + } + } + + /// The function's name, as its errors give it. + fn function(self) -> &'static str { + match self { + Self::ColorPicker => "showColorPicker", + k => k.id(), } } } /// A dialog a script opened, which waits for its answer. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub struct ScriptDialog { pub kind: DialogKind, pub message: String, @@ -74,10 +89,12 @@ pub struct ScriptDialog { pub no_as_default: bool, /// `prompt`: the text its field starts with. pub preset: String, + /// `showColorPicker`: the color the picker starts with. `None` for the other dialogs. + pub color: Option, } /// The answer to a [`ScriptDialog`]. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub enum DialogAnswer { /// OK, for `alert`. Ok, @@ -85,6 +102,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// OK with the color picked, or Cancel (`None`), for `showColorPicker`. + ColorPicker(Option), } impl DialogAnswer { @@ -93,29 +112,51 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::ColorPicker(_) => DialogKind::ColorPicker, } } - /// What the function returns. - fn data(&self) -> Data { + /// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it + /// started with. + fn data(&self, d: &ScriptDialog) -> Data { match self { Self::Ok => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, + Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data), } } - /// The answer as a report gives it: `"ok"`, a boolean, a string or `null`. + /// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands + /// take it, or `null`. fn json(&self) -> Value { match self { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json), } } } +/// `c` as the paint commands take it. +fn color_json(c: &Color) -> Value { + serde_json::to_value(c).unwrap_or(Value::Null) +} + +/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from +/// -128 to 128, as a script's `LabColor` takes them? +fn in_range(c: &Color) -> bool { + let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x)); + match *c { + Color::Rgb { r, g, b } => unit(&[r, g, b]), + Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]), + Color::Gray { k } => unit(&[k]), + Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)), + } +} + /// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together /// is a line break; every other control character, and with `lines` false every line break too, /// shows as its Unicode Control Picture, as the Script Console shows it. @@ -148,7 +189,8 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "colorPicker", value: color | +/// null}`, the color in any form the paint commands take. An empty object, which the parameter /// took before dialogs existed, is an empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { @@ -180,7 +222,12 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + (Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)), + (Some("colorPicker"), v) => match crate::cmd::color_value(v).filter(in_range) { + Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))), + None => Err("is a color picker's answer, whose `value` must be a color or null"), + }, + _ => Err("must have `kind` alert, confirm, prompt or colorPicker"), } } @@ -245,8 +292,9 @@ impl Dialogs { let mut waiting = self.waiting.borrow_mut(); let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false }; self.record(d, answer.json()); + let data = answer.data(d); *waiting = None; - if let Err(e) = realm.answer(answer.data()) { + if let Err(e) = realm.answer(data) { *self.failed.borrow_mut() = Some(e); } true @@ -263,12 +311,15 @@ impl Dialogs { self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); - r.insert("message".into(), json!(d.message)); - r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + if d.kind != DialogKind::ColorPicker { + r.insert("message".into(), json!(d.message)); + r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + } match d.kind { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)), }; r.insert("answer".into(), answer); let r = Value::Object(r); @@ -319,7 +370,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result host.charge_call(args.iter().map(super::data_size).sum())?; let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) }; let (title, error_icon, no_as_default, preset) = match kind { - DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()), + // `showColorPicker` opens through `show_color_picker`, not here. + DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()), DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()), DialogKind::Prompt => { let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; @@ -335,7 +387,29 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset }; + wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None }) +} + +/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, +/// and a new object of `color` for Cancel. +pub(super) fn show_color_picker(host: &Host, color: Color) -> Result { + let dialog = ScriptDialog { + kind: DialogKind::ColorPicker, + message: String::new(), + title: None, + error_icon: false, + no_as_default: false, + preset: String::new(), + color: Some(color), + }; + wait_or_answer(host, dialog) +} + +/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of +/// `answers`. +fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result { + let kind = dialog.kind; + let name = kind.function(); let d = &host.dialogs; if d.framed { if !d.can_wait.get() { @@ -350,11 +424,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result match next { Some(a) if a.kind() == kind => { d.record(&dialog, a.json()); - Ok(a.data()) + Ok(a.data(&dialog)) } Some(a) => { d.record(&dialog, json!("missing")); - Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id()))) + Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id()))) } None => { d.record(&dialog, json!("missing")); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8b2267a5d8..0a7eb82ef5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -41,6 +41,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; mod paths; +pub(super) use colors::of_color as color_data; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -691,6 +693,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`, +/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]). +fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer { + let color = colors::solid(arg(a, 1), "showColorPicker's color")?; + super::dialogs::show_color_picker(h, color) +} + /// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter /// or a `\`) letters in one case. fn path_key(p: &str) -> String { @@ -1883,6 +1892,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", get(l, app_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("showColorPicker", method(l, app_show_color_picker)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 34c1496054..da34e8cf31 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -66,7 +66,7 @@ fn shown(v: f32, scale: f64) -> f64 { } /// The color object for a solid color. -fn of_color(c: &Color) -> Data { +pub(in crate::script) fn of_color(c: &Color) -> Data { match *c { Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]), Color::Cmyk { c, m, y, k } => color_object( @@ -131,6 +131,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result std::result::Result { + let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor")); + match assigned(d, what) { + Ok(Some(c)) => Ok(c), + // A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error. + Ok(None) | Err(HostError::Error(_)) => Err(not_solid()), + Err(e) => Err(e), + } +} + /// `color` as `paint.setFill` and `paint.setStroke` take it. pub(super) fn param(color: &Color) -> Value { serde_json::to_value(color).unwrap_or(Value::Null) diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index baa8989208..aa373d09bb 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -177,6 +177,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { error_icon: false, no_as_default: true, preset: String::new(), + color: None, }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); @@ -319,3 +320,74 @@ fn a_dialog_in_a_callback_throws_in_the_app() { assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}"); assert_eq!(r["dialogCount"], 0); } + +/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns. +const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() { + let mut s = one_doc(); + let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());"); + let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})])) + .unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}"); + let dialogs = r["dialogs"].as_array().unwrap(); + assert_eq!(dialogs.len(), 2); + assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}"); + assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null"); + let cmyk = headless( + &mut s, + "var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);", + answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]), + ) + .unwrap(); + assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}"); +} + +#[test] +fn the_color_picker_ends_the_run_when_no_answer_is_left() { + let mut s = one_doc(); + let before = art(&s); + let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] { + let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}"); + let e = headless(&mut s, &source, given).unwrap_err().to_string(); + assert!(e.contains("showColorPicker") && e.contains(says), "{e}"); + assert_eq!(art(&s), before, "the run's edit goes back"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } + let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string(); + assert!(a.contains("is for colorPicker, not alert"), "{a}"); +} + +#[test] +fn the_color_picker_refuses_what_is_not_a_solid_color() { + let mut s = one_doc(); + let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\ + try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\ + try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());"; + let r = headless(&mut s, source, json!([])).unwrap(); + assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}"); + assert_eq!(r["dialogCount"], 0, "no picker opened"); + for bad in [json!("not a color"), json!([255, 0, 0]), json!({"model": "lab", "l": 120, "a": 0, "b": 0}), json!(true)] { + let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); + assert!(e.contains("color picker's answer"), "{bad}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_the_color_picker() { + let mut s = one_doc(); + framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);")); + let d = s.script_dialog().unwrap(); + assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); + assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))))); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given"); + assert!(s.script_answer(DialogAnswer::ColorPicker(None))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}"); +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index af1b318728..4060b26d40 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -27,6 +27,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::swatchlib; +use vectorcraft_engine::script::DialogAnswer; use super::preview::LivePreview; use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values}; @@ -45,6 +46,8 @@ pub(crate) enum Target { Artboard(usize), /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, + /// The answer to a running script's `app.showColorPicker`, which opened it on this colour. + Script(Color), } /// One open Color Picker: what the dialog itself does not know. @@ -152,28 +155,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; let dialogs = app.dialogs().ok_or("no window")?; let start = srgba(&color); - let mut dialog = ColorPickerDialog::new( - match (artboard, stroke) { - (Some(_), _) => "artboard", - (None, true) => "stroke", - (None, false) => "fill", - }, - tl!("Color Picker"), - start, - ) - .eyedropper(true) - .add_to_swatches(false) - .gamut(gamut(app)) - .working_rgb(WorkingRgb) - .swatch_view(swatch_view(app)); - if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) - && let Some(converter) = working_cmyk() - { - dialog = dialog.cmyk(&converter); - } - if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { - dialog = dialog.kept(model_values(&color)); - } + let key = match (artboard, stroke) { + (Some(_), _) => "artboard", + (None, true) => "stroke", + (None, false) => "fill", + }; + let mut dialog = picker(app, key, &color); // PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target. if let Some((i, _)) = artboard { dialog = dialog.instance(i); @@ -196,6 +183,58 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's +/// swatches and libraries, and in a CMYK document the working CMYK inks. +fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { + let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color)) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); + if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) + && let Some(converter) = working_cmyk() + { + dialog = dialog.cmyk(&converter); + } + if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { + dialog = dialog.kept(model_values(color)); + } + dialog +} + +/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`. It +/// previews nothing; its OK and Cancel answer the run ([`finish`]). +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color) { + let Some(dialogs) = app.dialogs() else { return }; + // The given colour's own values, so that OK can tell an untouched pick from another model's. + let dialog = picker(app, SCRIPT_KEY, &color).kept(model_values(&color)); + let id = dialogs.with(|h| h.open(dialog)); + app.color_dialogs.pickers.retain(|o| o.id != id); + app.color_dialogs.pickers.push(Open { id, target: Target::Script(color), start: srgba(&color), keep: false, preview: LivePreview::default() }); +} + +/// The key of the Color Picker a script opens. +pub(crate) const SCRIPT_KEY: &str = "script"; + +/// The id of the Color Picker a running script waits at, while it is open or its answer is not +/// yet given. +pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { + app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script(_))).map(|o| o.id) +} + +/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. +pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(id) = script_picker(app) else { return }; + app.color_dialogs.pickers.retain(|o| o.id != id); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| { + h.cancel_by_id(ctx, id); + let _ = h.take_by_id::(id); + }); + } +} + /// Once per frame (after the shell pass): opens a picker for each dialog's colour request, previews /// each open picker's colour on the art, hands it the screen picks, and settles the ones that /// closed. @@ -259,6 +298,15 @@ fn finish( dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } } + // OK on the colour it opened with, in the model it opened with, gives that colour back. + (Some(DialogResult::Ok(r)), Target::Script(given)) => { + let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); + let picked = if untouched { *given } else { in_document_model(app, color_of(&r.picked)) }; + app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); + } + (_, Target::Script(_)) => { + app.session.script_answer(DialogAnswer::ColorPicker(None)); + } (Some(DialogResult::Ok(r)), _) => { if let Err(e) = commit(app, open, preview, &r.picked) { app.status(e); @@ -273,7 +321,7 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })), Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Fill | Target::Answer { .. } | Target::Script(_) => ("paint.setFill", json!({ "color": color_json(&c) })), } } @@ -291,8 +339,9 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// preview. Nothing previews until the colour first changes, nor without a selection (the colour /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { - // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) { + // A picker over a command dialog only fills a row; the dialog previews it. A script's picker + // only answers the script. + if matches!(open.target, Target::Answer { .. } | Target::Script(_)) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..65b7c92e1a 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -29,6 +29,7 @@ use std::path::Path; +use craft::color_ui::ui::ColorPickerDialog; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; @@ -46,6 +47,7 @@ use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; +use super::color_picker; use crate::VectorcraftApp; use crate::file_asks::{self, Owner}; @@ -430,6 +432,22 @@ pub(crate) fn forget(app: &VectorcraftApp) { }); } +/// [`forget`] for the Color Picker a script's `app.showColorPicker` opened. +pub(crate) fn forget_color_picker(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if color_picker::script_picker(app).is_none() { + return; + } + let asking = with_host(app, |host, _| host.is_open::()).unwrap_or(false); + color_picker::forget_script(app, &ctx); + if asking { + with_host(app, |host, _| { + let _ = host.take::(); + host.open(close_question()); + }); + } +} + /// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file. pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { if p.get("path").is_some() || p.get("source").is_some() { @@ -514,8 +532,13 @@ pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) { /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { + let picker = color_picker::script_picker(app); with_host(app, |host, _| { - let own = host.get::().map(StackDialog::id).or_else(|| host.get::().map(StackDialog::id)); + let own = host + .get::() + .map(StackDialog::id) + .or_else(|| host.get::().map(StackDialog::id)) + .or_else(|| picker.filter(|&id| host.get_by_id::(id).is_some())); match own { Some(parent) if host.stack().is_top(parent) => { host.open_child(close_question(), parent); @@ -585,6 +608,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { crate::script_runs::failed(app, error); forget::(app); forget::(app); + forget_color_picker(app); app.sync_views(); } if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index b08a8f2e93..e4f6303fab 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,9 +1,13 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, `app.showColorPicker` or a `File` or `Folder` file dialog, waits +//! for the person's answer. + +use vectorcraft_engine::script::DialogKind; use crate::VectorcraftApp; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; /// Advances the running script by one slice, or asks what its growth needs asked. @@ -47,13 +51,22 @@ fn ask(app: &mut VectorcraftApp) -> bool { } script_run::forget::(app); if let Some(dialog) = app.session.script_dialog() { - if !script_run::busy(app) { + if dialog.kind == DialogKind::ColorPicker { + // A picker that closed this frame answers the run in its own pump. + if color_picker::script_picker(app).is_none() + && !script_run::busy(app) + && let Some(color) = dialog.color + { + color_picker::open_for_script(app, color); + } + } else if !script_run::busy(app) { script_run::open_notice(app, &dialog); } return true; } // A run asked to stop no longer waits at its dialog. script_run::forget::(app); + script_run::forget_color_picker(app); if app.session.script_waiting() { if !script_run::busy(app) { script_run::open_growth(app); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 94e1bb9311..3417c5580b 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -1,12 +1,14 @@ //! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons, //! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers -//! given by a run with nobody to ask. The helpers over the dialog host are shared with the other -//! script tests. +//! given by a run with nobody to ask; and the Color Picker of `app.showColorPicker`. The helpers +//! over the dialog host are shared with the other script tests. +use craft::color_ui::ui::{ColorPickerDialog, PickedColor}; use craft::ui::dialog::{DialogId, StackDialog, StandardPrompt}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, CLOSE_KIND, CloseQuestion, NOTICE_KIND, ScriptNotice}; use crate::{VectorcraftApp, menus, script_runs}; @@ -315,3 +317,104 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { assert_eq!(framed["dialogs"], headless["dialogs"]); assert_eq!(framed["log"], json!([true, "p", "done"])); } + +/// Is the Color Picker of the script's `app.showColorPicker` open? +fn picker_open(app: &VectorcraftApp) -> bool { + let id = color_picker::script_picker(app); + id.is_some_and(|id| script_run::with_host(app, |host, _| host.get_by_id::(id).is_some()).unwrap()) +} + +/// Polls the run until it ends, or until its Color Picker is open (true). +fn until_picker(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if picker_open(app) { + return true; + } + } + panic!("the script neither ended nor opened the Color Picker"); +} + +/// Answers the script's Color Picker with OK (or Cancel), then runs the frame's picker pump. +fn answer_picker(app: &mut VectorcraftApp, ok: bool) { + let id = color_picker::script_picker(app).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let done = script_run::with_host(app, |host, ctx| if ok { host.confirm_by_id(ctx, id) } else { host.cancel_by_id(ctx, id) }).unwrap(); + assert!(done); + color_picker::pump(app, &ctx); +} + +#[test] +fn the_color_picker_waits_and_answers_the_run() { + let mut app = app(); + let gray = "var g = new GrayColor(); g.gray = 40;"; + start( + &mut app, + &format!( + "{DRAW} var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join()); \ + {gray} var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join()); var r = app.showColorPicker(g); vc.log([r.typename, r.gray].join());" + ), + ); + assert!(until_picker(&mut app)); + assert!(!is_open::(&app), "the picker opens in place of a notice"); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + color_picker::pump(&mut app, &ctx); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app), "the next call opens the picker again"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app)); + answer_picker(&mut app, false); + assert!(!until_picker(&mut app)); + assert_eq!( + log(&app), + json!(["RGBColor,0,255,0", "GrayColor,40", "GrayColor,40"]), + "OK gives the color picked, untouched its own color, Cancel the color given" + ); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "OK paints nothing"); + let dialogs = app.session.script_report().unwrap()["dialogs"].clone(); + assert_eq!(dialogs[2]["answer"], Value::Null, "Cancel is listed as null"); +} + +#[test] +fn the_same_color_set_in_another_model_is_a_new_pick() { + let mut app = app(); + start(&mut app, "var g = new GrayColor(); g.gray = 40; var p = app.showColorPicker(g); vc.log(p.typename);"); + assert!(until_picker(&mut app)); + // The gray's own sRGB, set as a plain color, as a screen sample sets one. + let open = app.color_dialogs.pickers.iter().find(|o| Some(o.id) == color_picker::script_picker(&app)).map(|o| (o.id, o.start)).unwrap(); + script_run::with_host(&app, |host, _| host.get_mut_by_id::(open.0).map(|d| d.set_color(PickedColor::rgb(open.1)))).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor"]), "the same sRGB as a plain color is an RGB pick, not the gray the script gave"); +} + +#[test] +fn stopping_or_quitting_the_run_closes_its_color_picker() { + let source = format!("{DRAW} var c = new RGBColor(); app.showColorPicker(c); vc.log('after');"); + let mut app = app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert!(!picker_open(&app), "no picker is left for the stopped run"); + assert!(color_picker::script_picker(&app).is_none()); + assert_eq!(objects(&app), 0, "the run's edit goes back"); + assert_eq!(log(&app), json!([])); + let mut app = self::app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + script_run::ask_to_close(&mut app); + assert!(is_open::(&app), "quitting asks over the picker"); + cancel(&mut app, CLOSE_KIND); + assert!(picker_open(&app), "Cancel shows the picker again"); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + assert!(!app.session.script_running()); + assert!(!picker_open(&app), "no picker is left for the abandoned run"); + assert_eq!(objects(&app), 0); +} diff --git a/docs/mcp.md b/docs/mcp.md index da2ab72029..5321b74f87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2667,7 +2667,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + `app.selection`, `app.coordinateSystem`, `app.getIsFileOpen(path)` and `app.showColorPicker(color)`, described + with the dialogs below. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -3048,7 +3049,9 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and + run ended at, or `"missing"` for a dialog `answers` had no answer for. `app.showColorPicker` is listed as `{kind: + "colorPicker", color, answer}`, with the color it opened on and the color picked, `null` for Cancel or + `"missing"`, each color as `paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at its limit. ```json @@ -3096,6 +3099,17 @@ left, when the next answer is for another kind of dialog, or when the script end and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an empty object are the same. +`app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at +https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, +`CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in a CMYK +document an RGB pick is returned as CMYK. OK with the color unchanged and Cancel return a new object of the color the +script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting +end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: +"colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its +range, or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and +`ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. + ```sh vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff2ebf0bf4..864cff266f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1036,6 +1036,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, 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`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, and Cancel a new object of the color given. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 80c33ec810298b6c1e65204ac378ac36b34b39ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 00:02:09 -0800 Subject: [PATCH 003/106] Scripts: fix review findings in the layer and path items - controlBounds takes in the paths' direction handles. A clipping group's are its clipping path's. - A compound path's pathItems is a PathItems collection: add() and the shape methods make the path inside it. - resize() scales and sets the stroke weight as one step, so a failed stroke change undoes the scale too. - A point change that adds or removes anchors deselects the path's direct-selected anchors, from a script and from path.setAnchors, so other anchors are not left selected in their place. - A script that ends past the allowance of the last answer is asked again before its changes are kept. - documents.addDocument starts from the built-in preset when a saved preset has its name, and Recent keeps the built-in preset's name. - Saved preset rows past the artboard limit read as the limit. - Host classes that do not fit the heap end with the heap limit. - Layers keep their list while the document is unchanged, and getByName charges its scan on a kept list too. - Selection ids are deduplicated with a set. - A path made on the current layer is made in one step, so a failed stroke or reversal after it undoes the path too. - Path points are found through a kept index of where each subpath's points start, rebuilt when the path's points change, so reading every point of a path with many subpaths is no longer quadratic. - A pixel-aligned compound path snaps a path moved into it. --- crates/engine/src/cmd/layer.rs | 12 +- crates/engine/src/cmd/newdoc.rs | 10 +- crates/engine/src/cmd/path.rs | 13 +- crates/engine/src/script/dom.rs | 88 +++++++++++- crates/engine/src/script/dom/layers.rs | 56 ++++++-- crates/engine/src/script/dom/paths.rs | 152 +++++++++++++++----- crates/engine/src/script/mod.rs | 10 ++ crates/engine/src/tests/newdoc.rs | 16 +++ crates/engine/src/tests/script_dom.rs | 74 +++++++++- crates/engine/src/tests/script_dom_paths.rs | 94 ++++++++++++ crates/engine/src/tests/script_run.rs | 54 +++++++ crates/js/src/host_classes.rs | 3 +- crates/js/src/host_tests.rs | 11 ++ crates/ui-egui/src/dialogs/new_document.rs | 16 +++ docs/mcp.md | 7 +- 15 files changed, 549 insertions(+), 67 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 9fe8d9e678..67f6cee727 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -956,7 +956,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) { @@ -966,9 +967,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/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 3bec14515a..55ea019e82 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -171,8 +171,9 @@ pub struct DocSettings { pub layout: ArtboardLayout, /// Columns of a grid layout. pub columns: u32, - /// Rows of a grid by column, in place of `columns` when more than 0. - #[serde(skip_serializing_if = "is_zero")] + /// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a + /// saved or Recent preset's value past it is read as `MAX_ARTBOARDS`). + #[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")] pub rows: u32, /// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value /// outside that range is read as the nearer end). @@ -594,6 +595,11 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result { + Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32) +} + /// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points. fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING)) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d747f34989..dba64bf53c 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -702,9 +702,18 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result { }) .collect::>>()?, ); - s.edit("Reshape", |d, _| { - *path_mut(d, id)? = data; + s.edit("Reshape", |d, sel| { + let counts = |pd: &PathData| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::>(); + let path = path_mut(d, id)?; + let reshaped = counts(path) != counts(&data); + *path = data; super::object::resnap(d, id); + // Direct-selected anchors and segments are kept by index: when anchors were added or + // removed, the path is deselected rather than left with other anchors selected. + if reshaped && (sel.anchors.remove(&id).is_some() | sel.segments.remove(&id).is_some()) { + sel.objects.retain(|o| *o != id); + sel.prune(d); + } Ok(()) })?; ok() diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e8d0cc404a..b6a1160e28 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -109,6 +109,11 @@ pub(super) struct State { /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, + /// How many times [`paths`] changed the waiting point changes, which makes a + /// [`paths::PointIndex`] of them stale. + pending_changes: Cell, + /// Where the points of the path the run last read points of start, by subpath ([`paths`]). + point_index: RefCell>, /// How many times the points the run read of each path went stale, by document uid and path id /// ([`paths`]). point_cuts: RefCell>, @@ -125,6 +130,9 @@ pub(super) struct State { /// 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::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 open document's uid and the index of its active artboard when the run started. @@ -716,11 +724,11 @@ fn on_doc_layer( keep_layer: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before, layer) = { + let (index, active, mut before, layer, old) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; let st = &s.documents()[index]; - (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()), st.doc.clone()) }; let switch = active != Some(index); if switch { @@ -737,7 +745,28 @@ fn on_doc_layer( if keep_selection { let doc = { let s = h.session.borrow(); - s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone()) + s.active().filter(|st| st.uid == uid).map(|st| st.doc.clone()) + }; + // Anchors and segments are selected by index: a path that gained or lost anchors is not + // selected again, so that other anchors of it are not selected in their place. + if let Some(doc) = &doc { + let counts = |d: &Document, id: NodeId| { + d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| sp.anchors.len()).collect::>()) + }; + let partial: Vec = before.anchors.keys().chain(before.segments.keys()).copied().collect(); + for id in partial { + if counts(&old, id) != counts(doc, id) { + before.anchors.remove(&id); + before.segments.remove(&id); + before.objects.retain(|o| *o != id); + before.key_anchor = before.key_anchor.filter(|(k, _)| *k != id); + before.key = before.key.filter(|k| *k != id); + } + } + } + let doc = { + let s = h.session.borrow(); + doc.filter(|_| s.active().is_some_and(|st| st.selection != before)) }; if let Some(doc) = doc { restored = restore_selection(h, &doc, &before); @@ -1104,8 +1133,21 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { } // The document starts from the first preset of the profile's category (Print: Letter). 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 shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim())); + if shadowed { + shadowed_by = Some(first.clone()); + // `file.new` would find the saved preset of that name first: the built-in preset's + // settings go as params instead, under the ones `presetSettings` gives. + if let Value::Object(base) = first.to_json() { + for (k, v) in base.into_iter().filter(|(k, _)| !matches!(k.as_str(), "name" | "size" | "orientation" | "profile")) { + p.entry(k).or_insert(v); + } + } + } else { + p.insert("preset".into(), json!(first.name)); + } } p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); if let Some(m) = mode { @@ -1120,6 +1162,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)); @@ -1346,6 +1397,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); let locks = d.locked_artboards(); @@ -1360,7 +1412,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { bounds(h, a, true) } +/// The box of the anchors and direction handles of the paths in `n` that its visible bounds take +/// in: a clipping group or layer gives only its clipping path's, and the source art a Shaper Group +/// or a tracing keeps is left out, as are hidden objects. +fn handles_box(n: &vectorcraft_doc::Node) -> Option { + let children = n.editing_children(); + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + _ if n.clips() => children.first().and_then(|c| handles_box(c)), + _ => children.iter().filter(|c| c.visible).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, handles_box(c))), + } +} + +/// The item's visible bounds grown to take in the direction handles of its paths. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = with_doc(h, item.doc, |_, st| { + let visible = st.doc.bounds_of(&[item.id], true); + let handles = st.doc.node(item.id).and_then(handles_box); + let r = vectorcraft_geom::union_opt(visible, handles).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; + Ok::<_, HostError>((r, frame(st)?)) + })?; + Ok(f.bounds(h.dom.coords.get(), r)) +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -2140,7 +2216,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 23e4d58170..7a24b8fa3e 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -474,6 +474,39 @@ 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, a parent layer (`None`: the top level) and its layers. +pub(super) type LayerList = (u64, Arc, Option, Rc>); + +/// 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.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 = match parent { + None => st.doc.layers.len(), + Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len), + }; + h.charge_call(looked as u64)?; + let ids = Rc::new(layer_list(&st.doc, parent)); + 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() >= LAYER_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), parent, ids.clone())); + Ok(ids) +} + fn layers_of(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let [high, low] = id_parts(id); @@ -482,7 +515,7 @@ fn layers_of(h: &Host, a: &[Data]) -> Answer { 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| layer_list(&st.doc, parent).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 { @@ -499,14 +532,14 @@ fn layers_at(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) + 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 = layer_list(&st.doc, 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())) @@ -659,6 +692,8 @@ 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())) }) @@ -767,10 +802,8 @@ fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { } fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { - let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - // A compound path's `pathItems` are its `PageItems`: it holds only paths. - let compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); - Ok(text(if compound && kind == Kind::Any { "PathItems" } else { kind.class() })) + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { @@ -856,6 +889,13 @@ fn held_paths(h: &Host, a: &[Data]) -> Answer { 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)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -913,7 +953,7 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { m.extend(["textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } - "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, compound_paths))]), _ => Vec::new(), } } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 87287c5c27..19ad6ac4fb 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -131,20 +131,79 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) } -/// How many points a path with the subpaths `subs` has. -fn point_count(subs: &[SubPath]) -> usize { - subs.iter().map(|sp| sp.anchors.len()).sum() +/// The subpaths a [`PointIndex`] was made from. +enum PointSource { + /// The path's node as its document held it, kept so that the node compared with is the same + /// one: any change to the path's points makes a new node. + Node(Arc), + /// The path's waiting point changes, after this many changes to them + /// ([`super::State`]'s `pending_changes`). + Pending(u64), } -/// 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() { - if i < sp.anchors.len() { - return Some((s, i)); +/// Where the points of a path start, by subpath, so that a point is found by its index without a +/// pass over the subpaths before it. +pub(super) struct PointIndex { + /// The document uid and the id of the path. + key: (u64, u64), + source: PointSource, + /// The number of points before each subpath. + starts: Vec, + /// The number of points in all. + count: usize, +} + +impl PointIndex { + fn new(key: (u64, u64), source: PointSource, subs: &[SubPath]) -> Self { + let mut starts = Vec::with_capacity(subs.len()); + let mut count = 0; + for sp in subs { + starts.push(count); + count += sp.anchors.len(); } - i -= sp.anchors.len(); + PointIndex { key, source, starts, count } } - None + + /// The subpath and the place in it of point `i`. + fn locate(&self, i: usize) -> Option<(usize, usize)> { + if i >= self.count { + return None; + } + // The last subpath that starts at or before `i`: a subpath with no points starts where the + // next one does, so it is never the one found. + let s = self.starts.partition_point(|&start| start <= i).checked_sub(1)?; + Some((s, i - self.starts[s])) + } +} + +/// The number of points of the path of `item`, its waiting point changes included, and the subpath +/// and the place in it of point `i` when `i` is given and in the path. The index of the path's +/// subpaths is kept in [`super::State`] until the path's points change. +fn point_place(h: &super::Host, item: Item, i: Option) -> std::result::Result<(usize, Option<(usize, usize)>), HostError> { + let key = (item.doc.uid, item.id.0); + let source = match &*h.dom.pending.borrow() { + Some((waiting, _)) if same_path(*waiting, item) => PointSource::Pending(h.dom.pending_changes.get()), + _ => { + let s = h.session.borrow(); + let node = s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, item.id).cloned()); + PointSource::Node(node.ok_or_else(|| HostError::Error(STALE_ITEM.into()))?) + } + }; + let fresh = h.dom.point_index.borrow().as_ref().is_some_and(|x| { + x.key == key + && match (&x.source, &source) { + (PointSource::Node(a), PointSource::Node(b)) => Arc::ptr_eq(a, b), + (PointSource::Pending(a), PointSource::Pending(b)) => a == b, + _ => false, + } + }); + if !fresh { + let index = read_points(h, item, |subs| PointIndex::new(key, source, subs))?; + *h.dom.point_index.borrow_mut() = Some(index); + } + let kept = h.dom.point_index.borrow(); + let Some(index) = kept.as_ref() else { return Err(HostError::Error(STALE_ITEM.into())) }; + Ok((index.count, i.and_then(|i| index.locate(i)))) } fn anchor_json(a: &Anchor) -> Value { @@ -171,6 +230,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// locked, unless it changes nothing. A path 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 { + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { @@ -320,7 +380,8 @@ pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { host_ref("PathItems", &[float(h.run), float(uid), high, low]) } -/// The document of a `PathItems` object, and the layer or group it lists the paths of, if any. +/// 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() { @@ -328,7 +389,9 @@ fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option< [run, uid, high, low] => { let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let holds = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }))); + 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())); } @@ -432,7 +495,9 @@ fn make_in( return Err(HostError::Error(CONTAINER_LOCKED.into())); } let made = match container { - None => on_doc(h, doc.uid, true, make)?, + // 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}))?; @@ -1124,17 +1189,21 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } - if sx != 100.0 || sy != 100.0 { - let (r, _) = item_rect(h, item, false)?; - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.scale", params)?; - } - if let Some(w) = new_width - && (w - width).abs() > 1e-9 - { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; - } + // The scale and the new stroke weight are one edit: a failure of either undoes both. + super::atomically(h, |h| { + if sx != 100.0 || sy != 100.0 { + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); + edit_path(h, item, "object.scale", params)?; + } + if let Some(w) = new_width + && (w - width).abs() > 1e-9 + { + edit_path(h, item, "stroke.set", json!({"weight": w}))?; + } + Ok(()) + })?; Ok(Data::Undefined) } @@ -1148,7 +1217,8 @@ fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result Answer { let item = points_path(h, a)?; - read_points(h, item, |subs| num(float(point_count(subs) as u64))) + let (n, _) = point_place(h, item, None)?; + Ok(num(float(n as u64))) } fn points_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -1272,7 +1342,7 @@ fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - let n = read_points(h, item, point_count)?; + let (n, _) = point_place(h, item, None)?; Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) } @@ -1290,7 +1360,8 @@ fn points_index(h: &super::Host, a: &[Data]) -> Answer { fn points_add(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0]))); - let (n, last) = read_points(h, item, |subs| (point_count(subs), subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p)))?; + let (n, _) = point_place(h, item, None)?; + let last = read_points(h, item, |subs| subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p))?; if n >= MAX_POINTS { return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); } @@ -1324,20 +1395,29 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It return Err(HostError::Error(STALE_POINT.into())); } let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - let n = read_points(h, item, point_count)?; + let (n, _) = point_place(h, item, None)?; if i >= n { return Err(HostError::Error(STALE_POINT.into())); } Ok((item, i)) } +/// [`this_point`] with the subpath and the place in it of the point. +fn this_point_place(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize, usize), HostError> { + let (item, i) = this_point(h, a)?; + match point_place(h, item, Some(i))? { + (_, Some((s, j))) => Ok((item, s, j)), + (_, None) => Err(HostError::Error(STALE_POINT.into())), + } +} + /// Reads the anchor `this` names with `f`, given the frame and the coordinate system. fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, &Anchor) -> Data) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; let c = h.dom.coords.get(); let fr = with_doc(h, item.doc, |_, st| frame(st))?; read_points(h, item, |subs| { - let anchor = locate(subs, i).and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); + let anchor = subs.get(s).and_then(|sp| sp.anchors.get(j)); anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) })? } @@ -1345,11 +1425,9 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// Changes the anchor `this` names with `f`, given the point the script assigned in document /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) - && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) - { + if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { f(an); } })?; @@ -1411,10 +1489,10 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) - && let Some(sp) = subs.get_mut(s) + if let Some(sp) = subs.get_mut(s) + && j < sp.anchors.len() { sp.anchors.remove(j); if sp.anchors.is_empty() { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index ccb5b7f8d8..3a04359e7f 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2227,6 +2227,16 @@ 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)); } + // 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)); + self.script_key = Some(key); + return None; + } return Some(self.script_ended(job)); } // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 4e99adf688..e2ac91d592 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -422,6 +422,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/script_dom.rs b/crates/engine/src/tests/script_dom.rs index fb7239394a..5368a64c2f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -930,6 +930,19 @@ 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 document_preset_applies_only_its_given_fields() { let mut s = Session::new(); @@ -1317,8 +1330,9 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy(); + let (p, other) = (json!(p), json!(format!("{p}.other"))); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. @@ -1612,12 +1626,12 @@ fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ - vc.log(G.getByName === undefined); vc.log(P[1] === undefined);", + G[1].name = 'B'; vc.log(G.getByName('B') === G[1]); vc.log(G.index('B') === G[1]); vc.log(P[1] === undefined);", ); let expected = [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; assert_eq!(out[..11], expected); - assert_eq!(out[11..], [json!(false), json!(true)]); + assert_eq!(out[11..], [json!(true), json!(true), json!(true)]); } #[test] @@ -1917,6 +1931,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"); + } +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); @@ -1930,6 +1967,23 @@ fn a_compound_paths_path_items_are_path_items() { assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); } +#[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!(undo_steps(&s) > steps); +} + #[test] fn art_collections_follow_edits_between_reads() { let (mut s, _, _) = doc(); @@ -1966,6 +2020,18 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); } +#[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 2dbf3263b9..99e83b4ddc 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -154,6 +154,72 @@ 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; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{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); +} + +#[test] +fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() { + 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(); + let pt = |x: f64, y: f64| json!({"x": x, "y": y, "in": [x, y], "out": [x, y], "smooth": false}); + let three = json!([{"anchors": [pt(0.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": three})).unwrap(); + let sel = &s.active().unwrap().selection; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}"); + assert!(sel.objects.contains(&a)); + // The same number of anchors keeps them selected. + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let moved = json!([{"anchors": [pt(1.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved})).unwrap(); + 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]); +} + #[test] fn set_entire_path_replaces_points_and_keeps_closed() { let (mut s, a, _) = doc(); @@ -173,6 +239,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(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 2be8a841a8..f89d15d16c 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -1297,6 +1297,60 @@ 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"); +} + #[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/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..de41e7ef6f 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -215,7 +215,8 @@ pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(S let global = i.global; i.define(global, key(&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) } fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..a17c420c5e 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -648,6 +648,17 @@ 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(), index: None, construct: None }; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap)); +} + #[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 53300e92ec..77183407da 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -820,6 +820,22 @@ mod tests { assert_eq!(shown_columns(&s), 2.0); } + /// 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!(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 9210de701c..9f0f89f49e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2682,7 +2682,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, + visible bounds grown to take in the paths' direction handles), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs @@ -2757,8 +2757,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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` have the typename `PathItems`. A layer's or artboard's `name` takes a number or a boolean as + 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. A layer's or artboard's `name` takes a number or a boolean as `String()` writes it. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past From 88fe4e979629e7aa275f3334feeaa72744976113 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:52:31 -0800 Subject: [PATCH 004/106] Tests: list app.showColorPicker in the script host inventory --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 22f0b8b0b0..af193b5d56 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -84,7 +84,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + selection showColorPicker typename", ), ("DocumentPreset.", "prototype"), ( From a8cd6180cefc3a238760796dd6f4957756d4c604 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:47:22 -0800 Subject: [PATCH 005/106] Scripts: fix further review findings in the layer and path items - Point changes that add, remove or replace points deselect the path's direct-selected anchors even when the counts come out the same; path.setAnchors takes `reshaped` for this and refuses a non-boolean. - Moving points or handles, changing a point's type or setting `closed` keeps the index of where each subpath's points start. - A failed write keeps the waiting point changes. - Restoring the selection keeps a segment-only path to its segments. - getIsFileOpen folds `\` and letter case only on Windows. - Assigning `undefined` to Document.selection throws with nothing changed. - A document's path list is charged for the objects it looks at. - A made path keeps an id above 2^53. - A host object's handle is charged to the heap limit. - docs/mcp.md states that node.move into a compound path also needs its layer and groups shown and unlocked and no locked artboard. --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/cmd/path.rs | 13 +++- crates/engine/src/script/dom.rs | 37 +++++++--- crates/engine/src/script/dom/paths.rs | 81 ++++++++++++++++----- crates/engine/src/tests/script_dom.rs | 63 +++++++++++++++- crates/engine/src/tests/script_dom_paths.rs | 34 +++++++++ crates/js/src/heap.rs | 7 ++ crates/js/src/host_classes.rs | 2 +- docs/mcp.md | 18 +++-- 9 files changed, 212 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 67f6cee727..02ed82d101 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,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; a 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; a 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, 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 ), diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index cc11f6f824..06d089ab08 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Set Anchors", [], None, - "{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry", + "{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}], reshaped?: bool (true: the anchors were added, removed or replaced, so the path's direct-selected anchors are deselected even when each subpath keeps its count)} replace a path's geometry", has_doc, set_anchors ), @@ -757,14 +757,19 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result { }) .collect::>>()?, ); + let replaced = match p.get("reshaped") { + None => false, + Some(Value::Bool(v)) => *v, + Some(_) => return Err(bad("path.setAnchors", "reshaped must be a boolean")), + }; s.edit("Reshape", |d, sel| { let counts = |pd: &PathData| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::>(); let path = path_mut(d, id)?; - let reshaped = counts(path) != counts(&data); + let reshaped = replaced || counts(path) != counts(&data); *path = data; super::object::resnap(d, id); - // Direct-selected anchors and segments are kept by index: when anchors were added or - // removed, the path is deselected rather than left with other anchors selected. + // Direct-selected anchors and segments are kept by index: when anchors were added, + // removed or replaced, the path is deselected rather than left with other anchors selected. if reshaped && (sel.anchors.remove(&id).is_some() | sel.segments.remove(&id).is_some()) { sel.objects.retain(|o| *o != id); sel.prune(d); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b6a1160e28..2a716a1bb0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -44,6 +44,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; pub(super) mod layers; mod paths; +#[cfg(test)] +pub(crate) use paths::index_builds; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -112,6 +114,12 @@ pub(super) struct State { /// How many times [`paths`] changed the waiting point changes, which makes a /// [`paths::PointIndex`] of them stale. pending_changes: Cell, + /// Whether the waiting point changes added, removed or replaced points, so that writing them + /// deselects the path's direct-selected anchors even when the counts come out the same. + pending_reshaped: Cell, + /// The path [`flush`] is writing reshaped changes to, whose direct-selected anchors and + /// segments [`on_doc`] does not select again. + reshaping: Cell>, /// Where the points of the path the run last read points of start, by subpath ([`paths`]). point_index: RefCell>, /// How many times the points the run read of each path went stale, by document uid and path id @@ -626,12 +634,15 @@ 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| { let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + None if before.segments.contains_key(i) => Vec::new(), None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), }; json!({"id": i.0, "anchors": anchors}) @@ -747,15 +758,16 @@ fn on_doc_layer( let s = h.session.borrow(); s.active().filter(|st| st.uid == uid).map(|st| st.doc.clone()) }; - // Anchors and segments are selected by index: a path that gained or lost anchors is not - // selected again, so that other anchors of it are not selected in their place. + // Anchors and segments are selected by index: a path that gained, lost or replaced anchors + // is not selected again, so that other anchors of it are not selected in their place. if let Some(doc) = &doc { let counts = |d: &Document, id: NodeId| { d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| sp.anchors.len()).collect::>()) }; + let reshaped = h.dom.reshaping.get().filter(|it| it.doc.uid == uid).map(|it| it.id); let partial: Vec = before.anchors.keys().chain(before.segments.keys()).copied().collect(); for id in partial { - if counts(&old, id) != counts(doc, id) { + if reshaped == Some(id) || counts(&old, id) != counts(doc, id) { before.anchors.remove(&id); before.segments.remove(&id); before.objects.retain(|o| *o != id); @@ -840,13 +852,15 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter -/// or a `\`) letters in one case. +/// A path as `getIsFileOpen` compares it, without a trailing `/`: on Windows, `\` and `/` alike and +/// letters in one case; elsewhere `\` is part of a name and case counts. fn path_key(p: &str) -> String { - let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); - let p = p.replace('\\', "/"); - let p = p.trim_end_matches('/').to_string(); - if windows { p.to_lowercase() } else { p } + path_key_on(p, cfg!(windows)) +} + +/// [`path_key`] for Windows when `windows`, else for macOS and Linux. +pub(crate) fn path_key_on(p: &str, windows: bool) -> String { + if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() } } /// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is @@ -1391,7 +1405,8 @@ fn selection_of(h: &Host, uid: u64) -> Answer { /// `[]`. Every one must be an object of that document that can be selected. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), + Data::Undefined => return Err(HostError::Type("the selection takes a page item, a list of them, null or [], not undefined".into())), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 19ad6ac4fb..e6867d8b55 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -58,9 +58,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, edit_item, editable, find_doc, float, - frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, - point_method, point_property, property, this_doc, typename_of, whole, with_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, command_value, coordinate, edit_item, editable, + find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, + point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -176,6 +176,18 @@ impl PointIndex { } } +#[cfg(test)] +thread_local! { + /// How many times [`point_place`] built a [`PointIndex`] on this thread. + static INDEX_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times a [`PointIndex`] was built on this thread. +#[cfg(test)] +pub(crate) fn index_builds() -> u64 { + INDEX_BUILDS.with(std::cell::Cell::get) +} + /// The number of points of the path of `item`, its waiting point changes included, and the subpath /// and the place in it of point `i` when `i` is given and in the path. The index of the path's /// subpaths is kept in [`super::State`] until the path's points change. @@ -198,6 +210,8 @@ fn point_place(h: &super::Host, item: Item, i: Option) -> std::result::Re } }); if !fresh { + #[cfg(test)] + INDEX_BUILDS.with(|n| n.set(n.get() + 1)); let index = read_points(h, item, |subs| PointIndex::new(key, source, subs))?; *h.dom.point_index.borrow_mut() = Some(index); } @@ -230,12 +244,27 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// locked, unless it changes nothing. A path 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 { - h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); + 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 a [`PointIndex`] of the waiting changes stays good. +fn edit_points_keeping( + h: &super::Host, + item: Item, + counts_kept: bool, + f: impl FnOnce(&mut Vec) -> T, +) -> std::result::Result { if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { + if !counts_kept { + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); + h.dom.pending_reshaped.set(true); + } return Ok(f(subs)); } + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; let r = f(&mut subs); @@ -249,6 +278,7 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) return Err(cannot_edit(item.id)); } *h.dom.pending.borrow_mut() = Some((item, subs)); + h.dom.pending_reshaped.set(!counts_kept); if aligned { flush(h)?; } @@ -262,9 +292,13 @@ fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::R } /// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless -/// the path has those points already. +/// the path has those points already. Changes that added, removed or replaced points are written +/// with `reshaped`, so the path's direct-selected anchors are deselected even when the counts come +/// out the same, and the selection the run puts back leaves them out. When the write fails, the +/// changes stay waiting. pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) }; + let reshaped = h.dom.pending_reshaped.replace(false); let same = { let s = h.session.borrow(); let node = s.documents().iter().find(|d| d.uid == item.doc.uid).and_then(|st| st.doc.node(item.id)); @@ -277,7 +311,18 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); - edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + let mut params = json!({"id": item.id.0, "subpaths": subpaths}); + if reshaped { + params["reshaped"] = json!(true); + } + let kept = h.dom.reshaping.replace(reshaped.then_some(item)); + let r = edit_item(h, item, "path.setAnchors", ¶ms); + h.dom.reshaping.set(kept); + if let Err(e) = r { + *h.dom.pending.borrow_mut() = Some((item, subs)); + h.dom.pending_reshaped.set(reshaped); + return Err(e); + } Ok(()) } @@ -336,8 +381,8 @@ pub(super) const PATH_LISTS: usize = 4; /// The ids of a document's paths, in the order of its page items, or of the paths directly in the /// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their -/// documents are unchanged, so a loop over a collection builds its list once. A new list of a -/// container is charged by the objects it looks at. +/// 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(); @@ -357,6 +402,7 @@ fn path_items(h: &super::Host, st: &DocState, container: Option) -> std: } 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()) } }; @@ -464,13 +510,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object. -fn made_id(r: &Data) -> std::result::Result { - let id = match r { - Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), - _ => None, - }; - id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// The id in the result of a command that made an object, read from the command's own result (not +/// the script's copy, whose numbers are exact only up to 2^53). +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())) } /// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or @@ -516,7 +559,7 @@ fn make_in( /// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { make_in(h, doc, container, |h| { - let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; + let id = made_id(&drawing_normally(h, || command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -673,7 +716,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -697,7 +740,7 @@ 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| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; Ok(Data::Undefined) } @@ -1426,7 +1469,7 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { let (item, s, j) = this_point_place(h, a)?; - edit_points(h, item, |subs| { + edit_points_keeping(h, item, true, |subs| { if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { f(an); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 5368a64c2f..06bf3e83b0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -855,6 +855,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(); @@ -1349,6 +1375,18 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let _ = std::fs::remove_file(path); } +/// `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(); @@ -1626,12 +1664,15 @@ fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost 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);\ - G[1].name = 'B'; vc.log(G.getByName('B') === G[1]); vc.log(G.index('B') === G[1]); vc.log(P[1] === undefined);", + 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); - assert_eq!(out[11..], [json!(true), json!(true), json!(true)]); + // 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] @@ -1716,6 +1757,22 @@ fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { 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); @@ -1981,7 +2038,7 @@ fn a_compound_paths_path_items_add_makes_the_path_inside_it() { 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!(undo_steps(&s) > steps); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); } #[test] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 99e83b4ddc..0ac6a14eff 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -170,6 +170,12 @@ fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { 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); + // Removing a point and adding one in a single write ends with as many points, but the + // selected anchor's index now names another point, so the path is deselected. + log(&mut s, "var pp = app.activeDocument.pathItems[1].pathPoints; pp[0].remove(); pp.add();"); + let st = s.active().unwrap(); + assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3)); + assert!(!st.selection.anchors.contains_key(&b), "{:?}", st.selection); } #[test] @@ -188,6 +194,14 @@ fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() { let moved = json!([{"anchors": [pt(1.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved})).unwrap(); assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); + // `reshaped` deselects them at the same count; a value that is not a boolean is refused. + for bad in [json!(null), json!(1), json!("yes")] { + assert!(s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved, "reshaped": bad})).is_err(), "{bad}"); + } + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved, "reshaped": true})).unwrap(); + let sel = &s.active().unwrap().selection; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}"); } /// Points are found by their index across subpaths, through changes that wait to be written and @@ -220,6 +234,26 @@ fn points_are_found_across_subpaths_as_their_counts_change() { 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(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index bddab84fd6..f541c221e6 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -779,11 +779,18 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, + Class::Host(h) => extra = host_handle_bytes(h.handle.len()), _ => {} } OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra } +/// The bytes an object of a host class keeps for a handle of `numbers` numbers: the handle itself +/// and its copy in the realm's map of host objects. +pub(crate) fn host_handle_bytes(numbers: usize) -> usize { + numbers.saturating_mul(16) +} + fn add_name(name: &XmlName, strings: &mut StringSizes) { strings.add_key(&name.local); name.uri.iter().chain(&name.prefix).for_each(|k| strings.add_key(k)); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index de41e7ef6f..0d0b7ec69c 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -155,7 +155,7 @@ impl Interp { } return Ok(Value::Object(id)); } - self.reserve_heap(crate::heap::OBJECT_BYTES)?; + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(crate::heap::host_handle_bytes(handle.len())))?; let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); diff --git a/docs/mcp.md b/docs/mcp.md index 72d0c0f0f1..7ba136cb52 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,11 +2749,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, - a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or + a list of at most 10,000, `null` or `[]`; `undefined` (such as a page item looked up past the end of a list) + throws a `TypeError`, and an object that cannot be selected throws `Cannot select`, each with nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or with `selected`. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other - selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, - letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when + selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (on Windows, + letter case is ignored and `\` matches `/`; on macOS and Linux, `\` is part of a file name) and does not resolve the + path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, Document and PageItem pages list, such as `Document.views`, `PageItem.blendingMode`, `PageItem.rotate` and @@ -2825,7 +2826,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. - 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), where the path gives up its own paint, 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. @@ -2859,6 +2861,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the script uses any other member or command, or the points of another path, 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. + Writing changes that added, removed or replaced points deselects the path's direct-selected anchors, even when the + path ends with as many points as before; changes that only move points or handles, change a point's type or set + `closed` keep them selected. `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`, @@ -6744,7 +6749,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 (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, From 637facb057236984dfb89bfe8707fdbf200bb639 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:27:19 -0800 Subject: [PATCH 006/106] Scripts: empty objects read zero control bounds and turn or scale as no-ops - controlBounds of an object with nothing in it reads zeros, like its geometric and visible bounds. - path.rotate and path.resize of a path with no anchors change nothing. - The path tests make the first rectangle last, so pathItems[0] is the topmost path as pageItems lists it. --- crates/engine/src/script/dom.rs | 9 ++++++--- crates/engine/src/script/dom/paths.rs | 17 ++++++++++------- crates/engine/src/tests/script_dom.rs | 8 ++++---- crates/engine/src/tests/script_dom_paths.rs | 13 +++++++++++-- .../tests/it/script_host_vs_scriptcheck.rs | 5 ++++- 5 files changed, 35 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4a40865c1f..2ef5503fb0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1851,10 +1851,13 @@ fn item_control(h: &Host, a: &[Data]) -> Answer { let (r, f) = with_doc(h, item.doc, |_, st| { let visible = st.doc.bounds_of(&[item.id], true); let handles = st.doc.node(item.id).and_then(handles_box); - let r = vectorcraft_geom::union_opt(visible, handles).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; - Ok::<_, HostError>((r, frame(st)?)) + Ok::<_, HostError>((vectorcraft_geom::union_opt(visible, handles), frame(st)?)) })?; - Ok(f.bounds(h.dom.coords.get(), r)) + // An object with nothing in it has no bounds, and they read as zeros like its other bounds. + match r { + Some(r) => Ok(f.bounds(h.dom.coords.get(), r)), + None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } } fn item_position(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e735b8f153..ffe1a23264 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -58,9 +58,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, class_text, colors, command, command_value, coordinate, edit_item, editable, - find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, - point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, class_text, colors, command, command_value, coordinate, edit_item, + editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -1202,8 +1202,10 @@ fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { let place = about_name(arg(a, 6))?; let mut params = json!({"angle": angle}); transform_options(a, 2, &mut params)?; - if angle.rem_euclid(360.0) != 0.0 { - let (r, _) = item_rect(h, item, false)?; + // A path with no anchors has no bounds to turn about, and turning it changes nothing. + if angle.rem_euclid(360.0) != 0.0 + && let (Some(r), _) = item_rect(h, item, false)? + { let origin = about(h, item, place, r)?; params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.rotate", params)?; @@ -1234,8 +1236,9 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { } // The scale and the new stroke weight are one edit: a failure of either undoes both. super::atomically(h, |h| { - if sx != 100.0 || sy != 100.0 { - let (r, _) = item_rect(h, item, false)?; + if (sx != 100.0 || sy != 100.0) + && let (Some(r), _) = item_rect(h, item, false)? + { let origin = about(h, item, place, r)?; params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.scale", params)?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0be17f5d71..09c856dbcf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -717,10 +717,10 @@ fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() { s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); let anchors = s.active().unwrap().selection.anchors.clone(); assert!(anchors.contains_key(&a)); - log(&mut s, "app.activeDocument.pageItems[1].selected = false;"); + log(&mut s, "app.activeDocument.pageItems[0].selected = false;"); let sel = &s.active().unwrap().selection; assert_eq!((sel.objects.clone(), sel.anchors.clone()), (vec![a], anchors.clone())); - log(&mut s, "app.activeDocument.pageItems[1].selected = true;"); + log(&mut s, "app.activeDocument.pageItems[0].selected = true;"); let sel = &s.active().unwrap().selection; assert_eq!((sel.objects.clone(), sel.anchors.get(&a)), (vec![a, b], anchors.get(&a))); } @@ -2428,7 +2428,7 @@ fn every_page_item_has_its_layer_and_members_check_this() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\ - vc.log(p.layer.name); vc.log(d.pageItems[0].layer.name); vc.log(p.layer.layers.typename);\ + vc.log(p.layer.name); vc.log(d.pageItems[1].layer.name); vc.log(p.layer.layers.typename);\ vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);", ); assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]); @@ -2542,7 +2542,7 @@ fn page_items_report_their_available_members_as_their_own() { ); assert_eq!(out[0], json!([true, true, true, true, true, true, true])); // Members that are not available yet, unknown names and inherited ones are not the object's own. - assert_eq!(out[1], json!([false, false, false, false, false, false])); + assert_eq!(out[1], json!([false, true, true, false, false, false])); // `for`-`in` lists the properties, not the methods or the members that are not available yet. assert_eq!(out[2], json!([true, true, -1, -1])); } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 0ac6a14eff..94b638ccc7 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -30,8 +30,9 @@ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { fn doc() -> (Session, NodeId, NodeId) { 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); + // `pathItems[0]` is the topmost path, so `a` is made last. let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); s.execute("select.none", &json!({})).unwrap(); (s, a, b) } @@ -564,6 +565,14 @@ 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"); +} + /// 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); @@ -935,7 +944,7 @@ fn locked_paths_and_wrong_objects_are_refused() { } assert_eq!(art(&s), before); s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); - let e = failure(&mut s, "var t = app.activeDocument.pageItems[2]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); assert!(e.contains("not a PathItem"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(PathPoint.prototype, 'anchor').get.call({});"); assert!(e.contains("not a PathPoint"), "{e}"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f5a2e83aed..24722a3adc 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -153,7 +153,10 @@ const INSIDE: &[(&str, &str)] = &[ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("PathItems.", "prototype"), - ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename"), + ( + "PathItems.prototype.", + "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename", + ), ("PathItem.", "prototype"), ( "PathItem.prototype.", From c98c18c56387e3b11c2e402fc4445db40d9ae703 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:37:26 -0800 Subject: [PATCH 007/106] Scripts: name lookups in every collection, and growth checked at the end - `pageItems`, `pathItems`, `groupItems` and `compoundPathItems` of a layer or group, the document's `pathItems`, `layers` and `artboards` read with a name give what `getByName` gives, and a name nothing has is not `in` them. Before, only the document's `pageItems` did. - A compound path's `pathItems.removeAll()` keeps the compound path, empty, as `remove()` of its last path does. Before, the compound path was deleted too and the collection went stale. - A Live Paint group's `pathItems`, `groupItems` and `compoundPathItems` throw `Cannot add an object to a Live Paint group` and make nothing. Before, a new path joined the group's source paths and the script got back an object that was not in the collection. - After each command, the points the run read are checked only for the paths in the parts of the document that changed, so a script that reads points of many paths and then edits each one no longer looks at every path after every edit. - A script that ends with nothing left to write, past the growth allowance the last answer gave, is asked again before its changes are kept, as one that writes point changes at the end is. - A new object of a host class adds its handle to the heap's total, as a collection counts it, so objects made between collections cannot go past the heap limit. Docs: docs/mcp.md (collection errors, artboard index errors). --- crates/engine/src/script/dom.rs | 14 +- crates/engine/src/script/dom/layers.rs | 23 +++- crates/engine/src/script/dom/paths.rs | 174 ++++++++++++++++++------- crates/engine/src/script/mod.rs | 24 +++- crates/engine/src/tests/script_dom.rs | 60 +++++++++ crates/engine/src/tests/script_run.rs | 33 +++++ crates/js/src/host_classes.rs | 5 +- crates/js/src/host_tests.rs | 14 ++ docs/mcp.md | 11 +- 9 files changed, 293 insertions(+), 65 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2ef5503fb0..4bfaa33968 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1570,6 +1570,15 @@ 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, + } +} + /// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. fn items_at(h: &Host, a: &[Data]) -> Answer { if layers::is_scoped(a) { @@ -1577,10 +1586,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { } let doc = items_doc(h, a)?; if let Data::String(_) = arg(a, 1) { - return match items_by_name(h, a) { - Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), - r => r, - }; + return by_name_or_probe(a, items_by_name(h, a)); } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index ed88917fd9..121c9a339f 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -537,8 +537,12 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer { Ok(text("Layers")) } +/// `layers[i]`, and `layers["name"]` as `getByName` reads it. 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 super::by_name_or_probe(a, layers_by_name(h, a)); + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) @@ -689,8 +693,12 @@ 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. 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 super::by_name_or_probe(a, art_by_name(h, a, kind)); + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) @@ -826,15 +834,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 @@ -1232,8 +1245,12 @@ 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. fn boards_at(h: &Host, a: &[Data]) -> Answer { let doc = boards_doc(h, a)?; + if let Data::String(_) = arg(a, 1) { + return super::by_name_or_probe(a, boards_by_name(h, a)); + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id)))) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ffe1a23264..c4fb82be2f 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -462,8 +462,12 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { }) } +/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { let (doc, c) = items_scope(h, a)?; + if let Data::String(_) = arg(a, 1) { + return super::by_name_or_probe(a, items_by_name(h, a)); + } let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) @@ -493,6 +497,8 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or /// locked path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// A compound path's `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its +/// last path does. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let (doc, c) = items_scope(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { @@ -505,7 +511,8 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); } if !ids.is_empty() { - on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + 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) } @@ -520,22 +527,35 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { /// 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. → the new path. +/// 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 - && !with_doc(h, doc, |_, st| editable(&st.doc, c)) - { - return Err(HostError::Error(CONTAINER_LOCKED.into())); + 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 @@ -1314,11 +1334,13 @@ fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc> { /// points read before go stale, unless `own`: the object model made the change /// ([`see_all_points`]), which `own` is asked only after a change. The kept node is shared with /// the document, so a node whose pointer is unchanged has unchanged points, and any change to it -/// makes a new node. +/// makes a new node. The first look at a path of a document also keeps the document as it is then, +/// when no look kept it before ([`see_all_points`]). fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { - let node = { + let (node, doc) = { let s = h.session.borrow(); - s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()) + let st = s.documents().iter().find(|d| d.uid == key.0); + (st.and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()), st.map(|st| st.doc.clone())) }; // A path that is gone makes its points stale, so that an undo that brings it back leaves them // stale. @@ -1328,9 +1350,15 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { } return; }; - let changed = match h.dom.point_nodes.borrow_mut().insert(key, node.clone()) { + let old = h.dom.point_nodes.borrow_mut().insert(key, node.clone()); + let changed = match old { Some(old) => !Arc::ptr_eq(&old, &node) && old.path_data().map(|pd| &pd.subpaths) != node.path_data().map(|pd| &pd.subpaths), - None => false, + None => { + if let Some(doc) = doc { + h.dom.point_docs.borrow_mut().entry(key.0).or_insert(doc); + } + false + } }; if changed && !own() { cut_key(h, key); @@ -1338,52 +1366,106 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { } /// [`see_points`] for each path whose points the run has read, after each command, so that a -/// change that a later command reverses still makes the points stale. Paths under the object that -/// the object model is changing ([`super::State`]), or that object itself, take the change as the -/// object model's own, and their points stay valid. A document that is the one the run last looked -/// at is skipped, as are its paths. +/// change that a later command reverses still makes the points stale. Only the paths of documents +/// that changed since the last look are looked at, and of those only the paths in the parts of the +/// document that changed ([`changed_ids`]), so an edit of one path does not look at every other +/// path the run read. Paths under the object that the object model is changing +/// ([`super::State`]), or that object itself, take the change as the object model's own, and their +/// points stay valid. pub(super) fn see_all_points(h: &super::Host) { - let keys: Vec<(u64, u64)> = { - let seen = h.dom.point_nodes.borrow(); - if seen.is_empty() { - return; - } + if h.dom.point_nodes.borrow().is_empty() { + return; + } + // The documents that changed since the last look, as they were then (`None`: gone, or not + // kept), kept as they are now. + type Kept = Option>; + let changed: Vec<(u64, Kept, Kept)> = { let s = h.session.borrow(); - let mut docs = h.dom.point_docs.borrow_mut(); - // The documents that changed since the last look, kept as they are now. - let mut changed = std::collections::HashSet::new(); - for (uid, _) in seen.keys() { - if changed.contains(uid) { - continue; + let mut changed = Vec::new(); + h.dom.point_docs.borrow_mut().retain(|uid, kept| match s.documents().iter().find(|d| d.uid == *uid) { + Some(st) if Arc::ptr_eq(kept, &st.doc) => true, + Some(st) => { + changed.push((*uid, Some(std::mem::replace(kept, st.doc.clone())), Some(st.doc.clone()))); + true } - match s.documents().iter().find(|d| d.uid == *uid) { - Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => {} - Some(st) => { - docs.insert(*uid, st.doc.clone()); - changed.insert(*uid); - } - None => { - docs.remove(uid); - changed.insert(*uid); - } + None => { + changed.push((*uid, None, None)); + false } - } - seen.keys().copied().filter(|(uid, _)| changed.contains(uid)).collect() + }); + changed }; let editing = h.dom.editing.get(); - for (uid, id) in keys { - let own = || match editing { - Some(e) if e.doc.uid == uid => { - let s = h.session.borrow(); - let id = NodeId(id); - id == e.id || s.documents().iter().find(|d| d.uid == uid).and_then(|st| st.doc.ancestry(id)).is_some_and(|a| a.contains(&e.id)) + for (uid, was, now) in changed { + let keys: Vec<(u64, u64)> = { + let seen = h.dom.point_nodes.borrow(); + match (&was, &now) { + (Some(was), Some(now)) => changed_ids(was, now).into_iter().map(|id| (uid, id.0)).filter(|k| seen.contains_key(k)).collect(), + _ => seen.keys().copied().filter(|(u, _)| *u == uid).collect(), } - _ => false, }; - see_points(h, (uid, id), own); + if keys.is_empty() { + continue; + } + // The objects under the one the object model is changing, as it is now. + let mut inside = std::collections::HashSet::new(); + if let (Some(e), Some(now)) = (editing, &now) + && e.doc.uid == uid + && let Some(n) = node_arc(now, e.id) + { + let mut stack = vec![n]; + while let Some(n) = stack.pop() { + inside.insert(n.id); + stack.extend(n.children().map_or(&[][..], Vec::as_slice)); + } + } + for key in keys { + see_points(h, key, || inside.contains(&NodeId(key.1))); + } } } +/// The ids of the objects that differ between `was` and `now`, two versions of a document that +/// share the objects they have in common: each object that is not the same object in both, and +/// everything in it. Lists that keep their objects in place are compared object by object, and +/// the rest by the part between the objects they start and end with in common. +fn changed_ids(was: &crate::Document, now: &crate::Document) -> Vec { + type Nodes<'a> = &'a [Arc]; + fn all(nodes: Nodes<'_>, out: &mut Vec) { + let mut stack: Vec<&Arc> = nodes.iter().collect(); + while let Some(n) = stack.pop() { + out.push(n.id); + stack.extend(n.children().map_or(&[][..], Vec::as_slice)); + } + } + let mut out = Vec::new(); + let mut work: Vec<(Nodes<'_>, Nodes<'_>)> = vec![(&was.layers, &now.layers)]; + while let Some((a, b)) = work.pop() { + let start = a.iter().zip(b).take_while(|(x, y)| Arc::ptr_eq(x, y)).count(); + let end = a[start..].iter().rev().zip(b[start..].iter().rev()).take_while(|(x, y)| Arc::ptr_eq(x, y)).count(); + let (a, b) = (&a[start..a.len() - end], &b[start..b.len() - end]); + if a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.id == y.id) { + for (x, y) in a.iter().zip(b) { + if Arc::ptr_eq(x, y) { + continue; + } + out.push(y.id); + match (x.children(), y.children()) { + (Some(xc), Some(yc)) => work.push((xc, yc)), + (xc, yc) => { + all(xc.map_or(&[][..], Vec::as_slice), &mut out); + all(yc.map_or(&[][..], Vec::as_slice), &mut out); + } + } + } + } else { + all(a, &mut out); + all(b, &mut out); + } + } + out +} + fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 9c372156a1..7b8ee73568 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2252,14 +2252,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/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 09c856dbcf..de4dacfb62 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1870,6 +1870,66 @@ fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { 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(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 2a4e67e7fc..6845a10123 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -1423,6 +1423,39 @@ fn a_finished_run_past_its_last_allowance_asks_again() { 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/js/src/host_classes.rs b/crates/js/src/host_classes.rs index dcd9e4a695..3313299073 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -189,10 +189,13 @@ impl Interp { } return Ok(Value::Object(id)); } - self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(crate::heap::host_handle_bytes(handle.len())))?; + let handle_bytes = crate::heap::host_handle_bytes(handle.len()); + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(handle_bytes))?; let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); + // The heap counts the object; its handle is counted here, as a collection counts it. + self.heap.bytes = self.heap.bytes.saturating_add(handle_bytes); self.host_objects.insert(made, id); Ok(Value::Object(id)) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 2e72ea124f..17ee28d49e 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -698,6 +698,20 @@ fn host_classes_that_do_not_fit_the_heap_end_with_the_heap_limit() { 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::heap::host_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/docs/mcp.md b/docs/mcp.md index b64bddc9cd..bab3a91147 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2779,7 +2779,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot object that is hidden or locked itself takes all of them (VectorCraft's own rule). `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. 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 @@ -2896,8 +2897,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the run leaves it). The report also lists a document whose active artboard has another index when the run ends because - artboards were inserted, removed or reordered before it. An index outside the list throws a - `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws + artboards were inserted, removed or reordered before it. `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. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; @@ -2927,7 +2929,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot run's one undo step. VectorCraft's own rules: a layer's or group's `pathItems` list the paths directly in it, topmost first, leaving out paths in its groups, compound paths and sublayers; a layer or group that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot add a path to a hidden or locked layer or - group` and no path is made. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + 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 `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, From e4d1dabf9e3c670a9b530ab0f7be706c287ab901 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:31:48 -0800 Subject: [PATCH 008/106] Scripts: path point reads scale with subpaths; the script color picker keeps its color - app.showColorPicker opens on the script's color even when an earlier picker left Only Web Colors on, and a changed RGB pick takes the model of the run's own active document, which may be one the script made. - Point reads and edits look a point up in a cached layout of where each subpath's points start, so a loop over a path with many subpaths no longer counts every subpath for each point. selectedPathPoints walks the selected anchors of a partial selection instead of every point. - PathPoint.selected writes the waiting point changes whenever any of them added or removed points of the path. - The path creators read the new path's id from the command's own result, so an id above 2^53 stays exact. - typename of a stale PathPoint or PathPoints throws as the other members do. - pageItems, pathItems and documents look up a key that reads as a number but is not an index, such as "-1", by name first. - artboardLayout keeps the columns the rows gave the current artboards when a new layout replaces the rows without its own columns. - Docs: pathItems.add() and the shape creators follow isolation; reading another path's points does not write the waiting changes; a gray within about 1e-14 % of white reads as 100; assigning documents throws in strict mode; when showColorPicker keeps the given color's model. --- crates/engine/src/cmd/newdoc.rs | 5 + crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 9 +- crates/engine/src/script/dom.rs | 37 ++++ crates/engine/src/script/dom/colors.rs | 4 +- crates/engine/src/script/dom/paths.rs | 230 +++++++++++++------- crates/engine/src/script/mod.rs | 3 + crates/engine/src/tests/script_dialogs.rs | 1 + crates/engine/src/tests/script_dom.rs | 16 ++ crates/engine/src/tests/script_dom_paths.rs | 91 ++++++++ crates/ui-egui/src/dialogs/color_picker.rs | 52 +++-- crates/ui-egui/src/script_runs.rs | 2 +- crates/ui-egui/src/tests/script_dialogs.rs | 61 ++++++ docs/mcp.md | 18 +- docs/target-app-parity.md | 2 +- 15 files changed, 423 insertions(+), 110 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index f672799325..743eaab2a7 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -372,6 +372,11 @@ impl DocSettings { /// `artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?}` or just a layout id. fn layout_params(&mut self, l: &Value, cmd: &str) -> Result<()> { let bad_layout = || bad(cmd, "artboardLayout.layout must be gridByRow, gridByColumn, row or column"); + // The columns that rows give the artboards as they are now, which a layout that replaces the + // rows without its own `columns` keeps. + if self.grid_rows().is_some() { + self.columns = u32::try_from(self.grid_columns()).unwrap_or(u32::MAX); + } if let Some(id) = l.as_str() { self.layout = ArtboardLayout::parse(id).ok_or_else(bad_layout)?; if self.layout != ArtboardLayout::GridByColumn { diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2ee3718b3a..7a7e81cf82 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK in a CMYK document), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index afda864f6a..27d22598d9 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -91,6 +91,9 @@ pub struct ScriptDialog { pub preset: String, /// `showColorPicker`: the color the picker starts with. `None` for the other dialogs. pub color: Option, + /// `showColorPicker`: the run's active document is in CMYK when the picker opens, so the app + /// gives an RGB pick back as CMYK. False for the other dialogs. + pub cmyk_document: bool, } /// The answer to a [`ScriptDialog`]. @@ -387,12 +390,15 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None }) + wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None, cmyk_document: false }) } /// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, /// and a new object of `color` for Cancel. pub(super) fn show_color_picker(host: &Host, color: Color) -> Result { + // During a slice the session holds the run's working copy, whose active document may be one + // the script made; between slices the app sees the documents as they were before the run. + let cmyk_document = host.session.borrow().active().is_some_and(|s| s.doc.color_mode == crate::doc::ColorMode::Cmyk); let dialog = ScriptDialog { kind: DialogKind::ColorPicker, message: String::new(), @@ -401,6 +407,7 @@ pub(super) fn show_color_picker(host: &Host, color: Color) -> Result)>>, + /// How many times the run has started point changes of a path, or added or removed points of + /// the path whose changes wait ([`paths::layout`]). + relayouts: Cell, + /// The waiting point changes add or remove points of their path. + relaid: Cell, + /// The last two point layouts the run worked out, the newest first ([`paths::layout`]). + layouts: RefCell)>>, /// How many times the points the run read of each path went stale, by document uid and path id /// ([`paths`]). point_cuts: RefCell>, @@ -946,6 +953,9 @@ fn front_docs(s: &Session) -> impl Iterator { /// `documents[i]`, and `documents["name"]` as `getByName` reads it. fn docs_at(h: &Host, a: &[Data]) -> Answer { + if let Some(r) = by_number_name(a, |a| docs_by_name(h, a)) { + return r; + } let s = h.session.borrow(); let at = match arg(a, 1) { Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)), @@ -1608,8 +1618,35 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } +/// The name a collection's indexer key reads as, when the key is a number that is not an array +/// index. The indexer passes a name that reads as a number, such as `"-1"` or `"1.5"`, as that +/// number, so a collection looks the name up first and gives `undefined` when nothing has it. +fn number_name(d: &Data) -> Option { + match d { + Data::Number(n) if !(n.fract() == 0.0 && (0.0..4_294_967_295.0).contains(n)) => Some(vectorcraft_js::number_to_string(*n)), + _ => None, + } +} + +/// Looks the indexer key of `a` up with `by_name` when it is a name that reads as a number +/// ([`number_name`]). → `None` for any other key. +fn by_number_name(a: &[Data], by_name: impl FnOnce(&[Data]) -> Answer) -> Option { + let name = number_name(arg(a, 1))?; + let mut named = a.to_vec(); + if let Some(key) = named.get_mut(1) { + *key = Data::String(name); + } + Some(match by_name(&named) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }) +} + /// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. fn items_at(h: &Host, a: &[Data]) -> Answer { + if let Some(r) = by_number_name(a, |a| items_by_name(h, a)) { + return r; + } let doc = items_doc(h, a)?; if let Data::String(_) = arg(a, 1) { return match items_by_name(h, a) { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index da34e8cf31..68a4052441 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -13,7 +13,9 @@ //! VectorCraft's own rules, which the help pages do not state: components left out count as 0; //! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` //! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page -//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not +//! says. A color read from an object gives that object the same color when it is assigned back, +//! except a gray within about 1e-14 % of white: one number cannot hold it, so it reads as 100 and +//! assigning it back makes the gray white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not //! assigned yet. use std::rc::Rc; diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 823ed46d41..e9e3285d3c 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -8,8 +8,9 @@ //! point's index, counted across the path's subpaths in order. Each read looks the path up again. //! Every change runs one command inside the run's one undo step, and a change that changes nothing //! runs no command. Changes to the points of one path wait in the run's [`super::State`] and are -//! written together with one `path.setAnchors` ([`flush`]) before any other member, command or -//! path's points are read or changed, and when the script ends. +//! written together with one `path.setAnchors` ([`flush`]) before any other member or command is +//! used or another path's points are changed, and when the script ends. Reading the points of +//! another path does not write them. //! //! 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 @@ -24,7 +25,8 @@ //! - `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 +//! the drawing mode, or where drawing puts a new path while an object is isolated (in an +//! isolated group, for example), 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. @@ -69,7 +71,7 @@ use vectorcraft_tools::params::gradient_params; use super::{ Answer, Coords, 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, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, - point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, + point, point_get, point_method, point_property, property, text, this_doc, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -140,20 +142,72 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) } -/// How many points a path with the subpaths `subs` has. -fn point_count(subs: &[SubPath]) -> usize { - subs.iter().map(|sp| sp.anchors.len()).sum() +/// Where the points of each subpath of a path start among the path's points, and how many points +/// the path has. +pub(super) struct Layout { + starts: Vec, + total: usize, } -/// 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() { - if i < sp.anchors.len() { - return Some((s, i)); +impl Layout { + fn of(subs: &[SubPath]) -> Self { + #[cfg(test)] + crate::script::LAYOUTS_BUILT.with(|n| n.set(n.get() + 1)); + let mut starts = Vec::with_capacity(subs.len()); + let mut total = 0usize; + for sp in subs { + starts.push(total); + total = total.saturating_add(sp.anchors.len()); } - i -= sp.anchors.len(); + Self { starts, total } } - None + + /// The subpath and the place in it of point `i`. + fn locate(&self, i: usize) -> Option<(usize, usize)> { + if i >= self.total { + return None; + } + // The last subpath that starts at or before `i`; a subpath with no points starts where the + // next one does, so the one found holds `i`. + let s = self.starts.partition_point(|start| *start <= i).checked_sub(1)?; + Some((s, i - self.starts.get(s)?)) + } +} + +/// What a [`Layout`] the run keeps was worked out from: the waiting point changes of a path, as +/// they were after [`super::State`]'s count of relayouts reached the number given, or the path as +/// a document held it. +pub(super) enum LayoutOf { + Waiting(Item, u64), + Stored(Item, Arc), +} + +impl LayoutOf { + fn same(&self, other: &Self) -> bool { + match (self, other) { + (Self::Waiting(a, n), Self::Waiting(b, m)) => same_path(*a, *b) && n == m, + (Self::Stored(a, d), Self::Stored(b, e)) => same_path(*a, *b) && Arc::ptr_eq(d, e), + _ => false, + } + } +} + +/// The layout of the points of the path of `item`, its waiting point changes included. The last +/// two layouts are kept, so that reading or changing point after point does not count the points +/// of every subpath each time. +fn layout(h: &super::Host, item: Item) -> std::result::Result, HostError> { + let of = match &*h.dom.pending.borrow() { + Some((waiting, _)) if same_path(*waiting, item) => LayoutOf::Waiting(item, h.dom.relayouts.get()), + _ => LayoutOf::Stored(item, with_doc(h, item.doc, |_, st| st.doc.clone())), + }; + if let Some((_, l)) = h.dom.layouts.borrow().iter().find(|(kept, _)| kept.same(&of)) { + return Ok(l.clone()); + } + let l = Rc::new(read_points(h, item, Layout::of)?); + let mut kept = h.dom.layouts.borrow_mut(); + kept.insert(0, (of, l.clone())); + kept.truncate(2); + Ok(l) } fn anchor_json(a: &Anchor) -> Value { @@ -174,15 +228,20 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) read_path(h, item, |_, _, pd| f(&pd.subpaths)) } -/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with -/// the path's other point changes until [`flush`] writes them. The first change of a path writes -/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or -/// locked, unless it changes nothing. A path 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 { +/// Changes the subpaths of the path of `item` with `f`, which adds or removes points when +/// `relayout`. The change waits in [`super::State`] with the path's other point changes until +/// [`flush`] writes them. The first change of a path writes the waiting changes of another path +/// first, and throws `Cannot edit` when the path is hidden or locked, unless it changes nothing. A +/// path 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, relayout: bool, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { + if relayout { + h.dom.relayouts.set(h.dom.relayouts.get().wrapping_add(1)); + h.dom.relaid.set(true); + } return Ok(f(subs)); } flush(h)?; @@ -198,6 +257,8 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) return Err(cannot_edit(item.id)); } *h.dom.pending.borrow_mut() = Some((item, subs)); + h.dom.relayouts.set(h.dom.relayouts.get().wrapping_add(1)); + h.dom.relaid.set(relayout); if aligned { flush(h)?; } @@ -207,7 +268,7 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) /// Gives the path of `item` the subpaths `subs` ([`edit_points`]). fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { - edit_points(h, item, |s| *s = subs) + edit_points(h, item, true, |s| *s = subs) } /// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless @@ -237,7 +298,8 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) } /// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active -/// layer, then puts the drawing mode back. +/// layer, or where drawing puts a new path while an object is isolated, then puts the drawing mode +/// back. fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); let r = f(); @@ -305,6 +367,11 @@ fn items_length(h: &super::Host, a: &[Data]) -> Answer { Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) } +fn items_typename(h: &super::Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("PathItems")) +} + fn items_parent(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) @@ -312,6 +379,9 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { /// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. fn items_at(h: &super::Host, a: &[Data]) -> Answer { + if let Some(r) = super::by_number_name(a, |a| items_by_name(h, a)) { + return r; + } let doc = items_doc(h, a)?; if let Data::String(_) = arg(a, 1) { return match items_by_name(h, a) { @@ -372,20 +442,19 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object. -fn made_id(r: &Data) -> std::result::Result { - let id = match r { - Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), - _ => None, - }; - id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// Runs the command `id` that makes an object, with `params`. → the new object's id, read from the +/// command's own result, so that an id above 2^53 stays exact. +fn make_object(h: &super::Host, id: &str, params: &Value) -> std::result::Result { + let (_, value) = super::command_value(h, id, params)?; + value.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. +/// Runs the command `id` that makes a path in `doc` on top of the active layer (or where drawing +/// puts a new path while an object is isolated), the selection kept, and reverses the new path's +/// direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { - let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; + let id = drawing_normally(h, || make_object(h, id, params))?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -534,7 +603,8 @@ fn items_star(h: &super::Host, a: &[Data]) -> Answer { make(h, doc, "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 +/// `pathItems.add()`: a path with no points on top of the active layer (or where drawing puts a new +/// path while an object is isolated), from `path.create` with /// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open /// path is set back to none in the same step. fn items_add(h: &super::Host, a: &[Data]) -> Answer { @@ -544,7 +614,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; + let id = drawing_normally(h, || make_object(h, "path.create", &json!({"d": ""})))?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -571,7 +641,7 @@ 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| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points(h, item, false, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; Ok(Data::Undefined) } @@ -1139,7 +1209,12 @@ fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result Answer { let item = points_path(h, a)?; - read_points(h, item, |subs| num(float(point_count(subs) as u64))) + Ok(num(float(layout(h, item)?.total as u64))) +} + +fn points_typename(h: &super::Host, a: &[Data]) -> Answer { + points_path(h, a)?; + Ok(text("PathPoints")) } fn points_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -1263,7 +1338,7 @@ fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - let n = read_points(h, item, point_count)?; + let n = layout(h, item)?.total; Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) } @@ -1281,7 +1356,8 @@ fn points_index(h: &super::Host, a: &[Data]) -> Answer { fn points_add(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0]))); - let (n, last) = read_points(h, item, |subs| (point_count(subs), subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p)))?; + let n = layout(h, item)?.total; + let last = read_points(h, item, |subs| subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p))?; if n >= MAX_POINTS { return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); } @@ -1289,7 +1365,7 @@ fn points_add(h: &super::Host, a: &[Data]) -> Answer { Some(p) => p, None => origin?, }; - edit_points(h, item, |subs| match subs.last_mut() { + edit_points(h, item, true, |subs| match subs.last_mut() { Some(sp) => sp.anchors.push(Anchor::corner(p)), None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)), })?; @@ -1315,8 +1391,7 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It return Err(HostError::Error(STALE_POINT.into())); } let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - let n = read_points(h, item, point_count)?; - if i >= n { + if i >= layout(h, item)?.total { return Err(HostError::Error(STALE_POINT.into())); } Ok((item, i)) @@ -1327,8 +1402,9 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, let (item, i) = this_point(h, a)?; let c = h.dom.coords.get(); let fr = with_doc(h, item.doc, |_, st| frame(st))?; + let at = layout(h, item)?.locate(i); read_points(h, item, |subs| { - let anchor = locate(subs, i).and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); + let anchor = at.and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) })? } @@ -1337,8 +1413,9 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { let (item, i) = this_point(h, a)?; - edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) + let at = layout(h, item)?.locate(i); + edit_points(h, item, false, |subs| { + if let Some((s, j)) = at && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { f(an); @@ -1395,6 +1472,12 @@ fn pt_set_type(h: &super::Host, a: &[Data]) -> Answer { edit_point(h, a, |an| an.kind = kind) } +/// `typename`, which throws as the other members do for a point that is stale. +fn pt_typename(h: &super::Host, a: &[Data]) -> Answer { + this_point(h, a)?; + Ok(text("PathPoint")) +} + fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { let (item, _) = this_point(h, a)?; Ok(path_ref(h, item)) @@ -1406,11 +1489,11 @@ fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) - d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer()))) } -/// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every +/// The point at subpath and place `at` is a selected anchor point of the path `id` in `sel`: every /// point of a path selected as a whole is (a path is when a group or compound path that holds it /// is selected, `held`), and of a path with direct-selected anchors only those anchors are. The /// endpoints of selected segments are not. -fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[SubPath], i: usize) -> bool { +fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, at: Option<(usize, usize)>) -> bool { if held { return true; } @@ -1419,31 +1502,23 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[ } match sel.partial(id) { None => true, - Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + Some(picked) => at.is_some_and(|r| picked.contains(&r)), } } -/// Whether the subpaths `a` and `b` have the same number of points in the same subpaths, so that a -/// point index names the same anchor in both. -fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { - a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.anchors.len() == y.anchors.len()) -} - /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point /// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in -/// [`super::State`] are written first only when they add or remove points of this path, since -/// the selection names anchors by their place in the document's path. +/// [`super::State`] are written first when any of them added or removed points of this path, since +/// the selection names anchors by their place in the document's path; changes that only move +/// points or handles stay waiting. fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - let moved = match &*h.dom.pending.borrow() { - Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, - _ => false, - }; + let moved = h.dom.relaid.get() && h.dom.pending.borrow().as_ref().is_some_and(|(waiting, _)| same_path(*waiting, item)); if moved { super::flush(h)?; } - let on = - read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), &pd.subpaths, i))?; + let at = layout(h, item)?.locate(i); + let on = read_path(h, item, |st, _, _| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), at))?; Ok(Data::String(if on { "PathPointSelection.ANCHORPOINT" } else { "PathPointSelection.NOSELECTION" }.into())) } @@ -1468,13 +1543,13 @@ fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { _ => return Err(HostError::Type("selected must be a PathPointSelection value".into())), }; let (item, i) = this_point(h, a)?; - let (now, at, selectable, held, guide) = with_doc(h, item.doc, |_, st| { + let at = layout(h, item)?.locate(i); + let (now, selectable, held, guide) = with_doc(h, item.doc, |_, st| { let node = st.doc.node(item.id); - let subs = node.and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]); let guide = node.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })); let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id); let held = held_selected(&st.doc, &st.selection, item.id); - (anchor_selected(&st.selection, item.id, held, subs, i), locate(subs, i), selectable, held, guide) + (anchor_selected(&st.selection, item.id, held, at), selectable, held, guide) }); if now == on { return Ok(Data::Undefined); @@ -1501,20 +1576,22 @@ fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { /// order of `pathPoints`. fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; + let lay = layout(h, item)?; let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; let held = held_selected(&st.doc, sel, item.id); if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { return Vec::new(); } - let mut out = Vec::new(); - let mut first = 0; - for (s, sp) in pd.subpaths.iter().enumerate() { - let n = sp.anchors.len(); - out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); - first += n; + match sel.partial(item.id).filter(|_| !held) { + // Direct-selected anchors, in subpath and anchor order, which is the order of `pathPoints`. + Some(anchors) => anchors + .iter() + .filter(|(s, j)| pd.subpaths.get(*s).is_some_and(|sp| *j < sp.anchors.len())) + .filter_map(|(s, j)| lay.starts.get(*s).map(|first| first + j)) + .collect(), + None => (0..lay.total).collect(), } - out })?; h.charge_call(picked.len() as u64)?; let [high, low] = id_parts(item.id); @@ -1526,8 +1603,9 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) + let at = layout(h, item)?.locate(i); + edit_points(h, item, true, |subs| { + if let Some((s, j)) = at && let Some(sp) = subs.get_mut(s) { sp.anchors.remove(j); @@ -1581,7 +1659,7 @@ pub(super) fn classes(l: &Link) -> Vec { "PathItems", None, named(vec![ - ("typename", typename_of("PathItems")), + ("typename", get(l, items_typename)), ("length", get(l, items_length)), ("parent", get(l, items_parent)), ("index", method(l, items_index)), @@ -1600,7 +1678,7 @@ pub(super) fn classes(l: &Link) -> Vec { "PathPoints", None, named(vec![ - ("typename", typename_of("PathPoints")), + ("typename", point_get(l, points_typename)), ("length", point_get(l, points_length)), ("parent", point_get(l, points_parent)), ("index", point_method(l, points_index)), @@ -1613,7 +1691,7 @@ pub(super) fn classes(l: &Link) -> Vec { "PathPoint", None, named(vec![ - ("typename", typename_of("PathPoint")), + ("typename", point_get(l, pt_typename)), ("parent", point_get(l, pt_parent)), ("anchor", point_property(l, pt_anchor, pt_set_anchor)), ("leftDirection", point_property(l, pt_left, pt_set_left)), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 3a39c71ba4..73806a7e7f 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2744,6 +2744,9 @@ thread_local! { pub(crate) static TEST_GROWTH_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; + /// Tests: how many times the object model worked out where the points of each subpath of a + /// path start. + pub(crate) static LAYOUTS_BUILT: Cell = const { Cell::new(0) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index aa373d09bb..af1d07f06a 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -178,6 +178,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { no_as_default: true, preset: String::new(), color: None, + cmyk_document: false, }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index b940b93325..46d530e122 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -707,6 +707,22 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { assert_eq!(more.boards().iter().filter(|b| b.x0 == more.boards()[0].x0).count(), 4); } +/// A layout that replaces the rows keeps the columns the rows gave the artboards there are now, +/// whether or not the change of artboards came with a layout of its own. +#[test] +fn replacing_rows_keeps_the_columns_of_the_artboards_there_are_now() { + use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; + let settings = DocSettings { artboards: 2, layout: ArtboardLayout::GridByColumn, ..DocSettings::default() }; + let settings = settings.with_params(&json!({"artboardLayout": {"rows": 4}}), "file.new").unwrap(); + for change in [json!({"artboards": 9}), json!({"artboards": 9, "artboardLayout": {"spacing": 20}})] { + let more = settings.clone().with_params(&change, "file.new").unwrap(); + for layout in [json!("gridByRow"), json!({"layout": "gridByRow"})] { + let by_row = more.clone().with_params(&json!({"artboardLayout": layout}), "file.new").unwrap(); + assert_eq!(by_row.grid_columns(), 3, "{change} then {layout}"); + } + } +} + #[test] fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index edd359282e..0945f15374 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::Point; use vectorcraft_geom::path::AnchorKind; use crate::*; @@ -262,6 +263,9 @@ fn path_point_setters_edit_one_anchor() { for i in [0, 2, 3] { assert_eq!(anchors[i], anchors_before[i], "point {i} did not change"); } + // The 300 pt tall document's y runs down, so script y 285 is document y 15. + let edited = &anchors[1]; + assert_eq!((edited.p, edited.h_in, edited.h_out), (Point::new(45.0, 15.0), Point::new(35.0, 15.0), Point::new(55.0, 15.0))); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType")); assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite")); @@ -1207,3 +1211,90 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } + +/// Reading and moving each point of a path with many subpaths works out where the subpaths' points +/// start a few times for the whole loop, not once or more for each point. +#[test] +fn reading_and_moving_points_counts_the_subpaths_a_few_times() { + let (mut s, _, _) = doc(); + let d: String = (0..500).map(|i| format!("M{x} 10 L{x} 20 ", x = i % 300)).collect(); + let id = NodeId(s.execute("path.create", &json!({"d": d})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + crate::script::LAYOUTS_BUILT.with(|n| n.set(0)); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints;\ + for (var i = 0; i < pp.length; i++) { var q = pp[i]; q.anchor = [q.anchor[0], q.anchor[1] + 1]; }\ + vc.log(pp.length);", + ); + assert_eq!(out, vec![json!(1000)]); + let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get); + assert!(built < 10, "{built} layouts for 1000 points"); + let n = node(&s, id); + assert!(n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).all(|an| an.p.y == 9.0 || an.p.y == 19.0), "every point moved up"); +} + +/// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the +/// order of `pathPoints`, whatever order they were selected in. +#[test] +fn selected_path_points_follow_the_order_of_path_points_across_subpaths() { + let (mut s, _, _) = doc(); + let id = NodeId(s.execute("path.create", &json!({"d": "M0 0 L10 0 L10 10 M20 0 L30 0"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[1, 1], [0, 2], [0, 0]], "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var sp = app.activeDocument.pathItems[0].selectedPathPoints, x = [];\ + for (var i = 0; i < sp.length; i++) x.push(sp[i].anchor[0]); vc.log(x);", + ); + assert_eq!(out, vec![json!([0, 10, 30])]); +} + +/// `pageItems` and `pathItems` find a name that reads as a number but is not an index, and such a +/// key that nothing has reads as `undefined`. +#[test] +fn collections_find_names_that_read_as_numbers() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "1.5"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, g = d.pageItems, p = d.pathItems;\ + vc.log([g['-1'].name, g[1.5].name, '-1' in g, p['-1'].name, p[-1].name, '1.5' in p]);\ + vc.log([g[-2] === undefined, '-2' in p, p[2.5] === undefined, p[0].name, p[1].name]);", + ); + assert_eq!(out, vec![json!(["-1", "1.5", true, "-1", "-1", true]), json!([true, false, true, "-1", "1.5"])]); +} + +/// `typename` of a point or a point list throws for one that is stale, as the other members do. +#[test] +fn stale_points_throw_on_typename() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[3]; vc.log(q.typename); pp[0].remove();\ + try { q.typename; vc.log('read'); } catch (e) { vc.log(e.message); }\ + var p = app.activeDocument.pathItems[0], ps = p.pathPoints; vc.log(ps.typename); p.remove();\ + try { ps.typename; vc.log('read'); } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out, vec![json!("PathPoint"), json!("Stale path point"), json!("PathPoints"), json!("Stale page item")]); +} + +/// A path the creators make in a document whose ids are past 2^53 is the new path, not one whose +/// id a double rounds to. +#[test] +fn made_paths_keep_ids_past_two_to_the_53() { + let (mut s, _, _) = doc(); + let big = 1u64 << 53; + s.edit("Raise Ids", |d, _| { + d.raise_next_id(big); + Ok(()) + }) + .unwrap(); + let old = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + assert_eq!(old.0, big); + s.execute("select.none", &json!({})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems; p.add().name = 'made'; p.rectangle(50, 50, 10, 10, true).name = 'reversed';"); + assert_eq!(node(&s, old).name, None); + assert_eq!(node(&s, NodeId(big + 1)).name.as_deref(), Some("made")); + assert_eq!(node(&s, NodeId(big + 2)).name.as_deref(), Some("reversed")); +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index e030723a16..9b64bd2dd6 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -48,8 +48,9 @@ pub(crate) enum Target { Artboard { document: u64, reverts: u64, index: usize }, /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, - /// The answer to a running script's `app.showColorPicker`, which opened it on this colour. - Script(Color), + /// The answer to a running script's `app.showColorPicker`, which opened it on `color`; `cmyk`: + /// the run's active document is in CMYK. + Script { color: Color, cmyk: bool }, } impl Target { @@ -62,7 +63,7 @@ impl Target { Self::Fill { document, reverts } | Self::Stroke { document, reverts } => (*document, *reverts), Self::Artboard { document, reverts, .. } => (Some(*document), *reverts), // A script's picker answers the run whichever document is active. - Self::Answer { .. } | Self::Script(_) => return None, + Self::Answer { .. } | Self::Script { .. } => return None, }; match (app.session.active(), document) { (None, None) => None, @@ -195,7 +196,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { (None, true) => "stroke", (None, false) => "fill", }; - let mut dialog = picker(app, key, &color); + let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk); + let mut dialog = picker(app, key, &color, cmyk); // The host replaces a picker only for the same document and artboard. if let Some((document, _, index, _)) = artboard { dialog = dialog.instance((document, index)); @@ -221,17 +223,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } /// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's -/// swatches and libraries, and in a CMYK document the working CMYK inks. -fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { +/// swatches and libraries, and with `cmyk` (a CMYK document) the working CMYK inks. +fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPickerDialog { let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color)) .eyedropper(true) .add_to_swatches(false) .gamut(gamut(app)) .working_rgb(WorkingRgb) .swatch_view(swatch_view(app)); - if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) - && let Some(converter) = working_cmyk() - { + if cmyk && let Some(converter) = working_cmyk() { dialog = dialog.cmyk(&converter); } if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { @@ -240,15 +240,18 @@ fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { dialog } -/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`. It +/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`: +/// the run's own active document is in CMYK, which the session does not show between slices. It /// previews nothing; its OK and Cancel answer the run ([`finish`]). -pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color) { +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool) { let Some(dialogs) = app.dialogs() else { return }; // The given colour's own values, so that OK can tell an untouched pick from another model's. - let dialog = picker(app, SCRIPT_KEY, &color).kept(model_values(&color)); + // The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given. + let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false); let id = dialogs.with(|h| h.open(dialog)); app.color_dialogs.pickers.retain(|o| o.id != id); - app.color_dialogs.pickers.push(Open { id, target: Target::Script(color), start: srgba(&color), keep: false, preview: LivePreview::default() }); + let target = Target::Script { color, cmyk }; + app.color_dialogs.pickers.push(Open { id, target, start: srgba(&color), keep: false, preview: LivePreview::default() }); } /// The key of the Color Picker a script opens. @@ -257,7 +260,7 @@ pub(crate) const SCRIPT_KEY: &str = "script"; /// The id of the Color Picker a running script waits at, while it is open or its answer is not /// yet given. pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { - app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script(_))).map(|o| o.id) + app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script { .. })).map(|o| o.id) } /// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. @@ -355,12 +358,12 @@ fn finish( } } // OK on the colour it opened with, in the model it opened with, gives that colour back. - (Some(DialogResult::Ok(r)), Target::Script(given)) => { + (Some(DialogResult::Ok(r)), Target::Script { color: given, cmyk }) => { let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); - let picked = if untouched { *given } else { in_document_model(app, color_of(&r.picked)) }; + let picked = if untouched { *given } else { in_model(*cmyk, color_of(&r.picked)) }; app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); } - (_, Target::Script(_)) => { + (_, Target::Script { .. }) => { app.session.script_answer(DialogAnswer::ColorPicker(None)); } (Some(DialogResult::Ok(r)), _) => { @@ -377,14 +380,19 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })), Target::Stroke { .. } => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill { .. } | Target::Answer { .. } | Target::Script(_) => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Fill { .. } | Target::Answer { .. } | Target::Script { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), } } -/// The picked colour as the document takes it: an RGB colour is CMYK in a CMYK document; CMYK, -/// grey and Lab colours stay as they are. +/// The picked colour as the active document takes it ([`in_model`]). fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { - if matches!(c, Color::Rgb { .. }) && app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) { + in_model(app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk), c) +} + +/// The picked colour as a document takes it: an RGB colour is CMYK in a CMYK document (`cmyk`); +/// CMYK, grey and Lab colours stay as they are. +fn in_model(cmyk: bool, c: Color) -> Color { + if cmyk && matches!(c, Color::Rgb { .. }) { let [cy, m, y, k] = c.to_cmyk_managed(cms::active().settings().intent); return Color::cmyk(cy, m, y, k); } @@ -397,7 +405,7 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { // A picker over a command dialog only fills a row; the dialog previews it. A script's picker // only answers the script. - if matches!(open.target, Target::Answer { .. } | Target::Script(_)) || !open.target.in_active_document(app) { + if matches!(open.target, Target::Answer { .. } | Target::Script { .. }) || !open.target.in_active_document(app) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7951fc4a7e..7f27a225a8 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -118,7 +118,7 @@ fn ask(app: &mut VectorcraftApp) -> bool { && !script_run::busy(app) && let Some(color) = dialog.color { - color_picker::open_for_script(app, color); + color_picker::open_for_script(app, color, dialog.cmyk_document); } } else if !script_run::busy(app) { script_run::open_notice(app, &dialog); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index ca5d67b800..5dfa72ff39 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -420,3 +420,64 @@ fn stopping_or_quitting_the_run_closes_its_color_picker() { assert!(!picker_open(&app), "no picker is left for the abandoned run"); assert_eq!(objects(&app), 0); } + +#[test] +fn the_color_picker_opens_on_the_scripts_color_with_only_web_colors_left_on() { + let mut app = app(); + let ctx = app.ui_ctx.clone().unwrap(); + // A frame of the window's dialogs starts the open pickers with the app's host, whose settings + // keep what a picker remembers. + let frame = |app: &mut VectorcraftApp| { + let _ = crate::testing::part_frame(app, &ctx, egui::RawInput::default(), |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + }); + }; + // A fill picker closed with Only Web Colors on, which later fill pickers recall. + color_picker::open(&mut app, &json!({})).unwrap(); + frame(&mut app); + set(&app, "fill", "webColors", json!(true)).unwrap(); + let id = open_id(&app, "fill"); + assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap()); + color_picker::pump(&mut app, &ctx); + color_picker::open(&mut app, &json!({})).unwrap(); + frame(&mut app); + assert_eq!(fields(&app, "fill")["webColors"], json!(true), "the next fill picker recalls Only Web Colors"); + let id = open_id(&app, "fill"); + assert!(script_run::with_host(&app, |host, ctx| host.confirm_by_id(ctx, id)).unwrap()); + color_picker::pump(&mut app, &ctx); + // A frame without the picker drops its overlay. + frame(&mut app); + assert!(!script_run::busy(&app), "no picker is left open"); + start( + &mut app, + "var c = new RGBColor(); c.red = 18; c.green = 52; c.blue = 86; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());", + ); + assert!(until_picker(&mut app)); + frame(&mut app); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor,18,52,86"]), "untouched OK gives the script's color, not its nearest web color"); +} + +#[test] +fn a_pick_takes_the_model_of_the_document_the_script_made() { + for (doc, made, want) in [("{}", "CMYK", "CMYKColor"), ("{\"colorMode\": \"cmyk\"}", "RGB", "RGBColor")] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), crate::Services::default())); + app.run("file.new", serde_json::from_str(doc).unwrap()).unwrap(); + app.session.prefs.show_external_script_warning = false; + start( + &mut app, + &format!( + "app.documents.add(DocumentColorSpace.{made}, 50, 60, 1); var c = new RGBColor(); c.red = 255; \ + var p = app.showColorPicker(c); vc.log(p.typename);" + ), + ); + assert!(until_picker(&mut app)); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!([want]), "an RGB pick in the {made} document the script made"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index be0c4e9c3f..e35ba44e66 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2782,7 +2782,7 @@ other files through `$`: describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level `var selection = ...` does the same and does not make a variable of the script. Assigning `documents` keeps its - value. `app.documents` + value; in strict-mode code it throws a `TypeError`. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -2909,7 +2909,8 @@ other files through `$`: radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing - mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + mode, which stays as it was, or, while an object is isolated, where drawing puts a new path (in an isolated group, + for example). 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 @@ -2919,8 +2920,8 @@ other files through `$`: stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one - `path.setAnchors` before the script uses any other member or command, or the points of another path, 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 + `path.setAnchors` before the script uses any other member or command, or changes the points of another path, and + when the script ends (reading the points of another path does not write them); 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. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and @@ -2933,7 +2934,8 @@ other files through `$`: `NOSELECTION` removes it, through `select.anchorsMany`, with the other selected objects and anchors kept. `selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as - https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` + https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it; a gray within about 1e-14 % of white reads as + 100, so assigning it back makes it white), `new LabColor()` and `new NoColor()` (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. @@ -3341,8 +3343,10 @@ empty object are the same. `app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, `CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a -`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in a CMYK -document an RGB pick is returned as CMYK. OK with the color unchanged and Cancel return a new object of the color the +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; when the +run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so the +color's `typename` can differ from the picker's model and from the color given. The picker opens on the color as +given, whatever Only Web Colors was left at in another picker. OK with the color unchanged and Cancel return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: "colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 292d08a18e..0a79cddfbf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1092,7 +1092,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, 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`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. - - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, and Cancel a new object of the color given. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. From 011f4775469c55ad0376f57894adbce746b4fe40 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:54:05 -0800 Subject: [PATCH 009/106] Scripts: reordered layers skip unchanged objects; opened paths drop their segments changed_ids pairs added, removed or reordered siblings by id, so an object that only moved is skipped and a changed one is compared level by level instead of listing every descendant of each shifted layer. A path that was opened or closed during a script keeps its anchor counts but not its segment indexes, so it is no longer selected again with a segment that does not exist (select.segments refused it after the change was applied). docs/mcp.md states that a hidden or locked Live Paint group throws the hidden-or-locked error rather than the Live Paint one. --- crates/engine/src/script/dom.rs | 6 ++- crates/engine/src/script/dom/paths.rs | 47 ++++++++++++++------- crates/engine/src/tests/script_dom_paths.rs | 14 ++++++ docs/mcp.md | 4 +- 4 files changed, 52 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e130af38e7..6df073368b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -788,10 +788,12 @@ fn on_doc_layer( s.active().filter(|st| st.uid == uid).map(|st| st.doc.clone()) }; // Anchors and segments are selected by index: a path that gained, lost or replaced anchors - // is not selected again, so that other anchors of it are not selected in their place. + // is not selected again, so that other anchors of it are not selected in their place. A path + // that was opened or closed keeps its anchors but not its segments, so it is not selected + // again either. if let Some(doc) = &doc { let counts = |d: &Document, id: NodeId| { - d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| sp.anchors.len()).collect::>()) + d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.segment_count())).collect::>()) }; let reshaped = h.dom.reshaping.get().filter(|it| it.doc.uid == uid).map(|it| it.id); let partial: Vec = before.anchors.keys().chain(before.segments.keys()).copied().collect(); diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index c4fb82be2f..4673e6277e 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1427,8 +1427,8 @@ pub(super) fn see_all_points(h: &super::Host) { /// The ids of the objects that differ between `was` and `now`, two versions of a document that /// share the objects they have in common: each object that is not the same object in both, and -/// everything in it. Lists that keep their objects in place are compared object by object, and -/// the rest by the part between the objects they start and end with in common. +/// everything in it. Lists are compared by the part between the objects they start and end with +/// in common, and in that part each object is compared with the object of the same id. fn changed_ids(was: &crate::Document, now: &crate::Document) -> Vec { type Nodes<'a> = &'a [Arc]; fn all(nodes: Nodes<'_>, out: &mut Vec) { @@ -1444,23 +1444,38 @@ fn changed_ids(was: &crate::Document, now: &crate::Document) -> Vec { let start = a.iter().zip(b).take_while(|(x, y)| Arc::ptr_eq(x, y)).count(); let end = a[start..].iter().rev().zip(b[start..].iter().rev()).take_while(|(x, y)| Arc::ptr_eq(x, y)).count(); let (a, b) = (&a[start..a.len() - end], &b[start..b.len() - end]); - if a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.id == y.id) { - for (x, y) in a.iter().zip(b) { - if Arc::ptr_eq(x, y) { - continue; + let pairs: Vec<(&Arc, &Arc)> = if a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.id == y.id) { + a.iter().zip(b).collect() + } else { + // Siblings were added, removed or reordered: the rest are paired by id, so an object that + // only moved is skipped and a changed one is compared level by level. Objects without a + // partner are listed with everything in them. + let by_id: std::collections::HashMap> = a.iter().map(|x| (x.id, x)).collect(); + let kept: std::collections::HashSet = b.iter().map(|y| y.id).collect(); + let mut pairs = Vec::new(); + for y in b { + match by_id.get(&y.id) { + Some(x) => pairs.push((*x, y)), + None => all(std::slice::from_ref(y), &mut out), } - out.push(y.id); - match (x.children(), y.children()) { - (Some(xc), Some(yc)) => work.push((xc, yc)), - (xc, yc) => { - all(xc.map_or(&[][..], Vec::as_slice), &mut out); - all(yc.map_or(&[][..], Vec::as_slice), &mut out); - } + } + for x in a.iter().filter(|x| !kept.contains(&x.id)) { + all(std::slice::from_ref(x), &mut out); + } + pairs + }; + for (x, y) in pairs { + if Arc::ptr_eq(x, y) { + continue; + } + out.push(y.id); + match (x.children(), y.children()) { + (Some(xc), Some(yc)) => work.push((xc, yc)), + (xc, yc) => { + all(xc.map_or(&[][..], Vec::as_slice), &mut out); + all(yc.map_or(&[][..], Vec::as_slice), &mut out); } } - } else { - all(a, &mut out); - all(b, &mut out); } } out diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 94b638ccc7..7df8022c5c 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -179,6 +179,20 @@ fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { assert!(!st.selection.anchors.contains_key(&b), "{:?}", st.selection); } +#[test] +fn opening_a_path_deselects_its_closing_segment() { + // `pathItems[1]` is `b`, a closed rectangle whose segment 3 closes it. + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 3]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[1].closed = false;"); + let st = s.active().unwrap(); + assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.subpaths[0].closed), Some(false)); + let sel = &st.selection; + assert!(!sel.objects.contains(&b) && !sel.segments.contains_key(&b), "{sel:?}"); + assert!(sel.objects.contains(&a)); +} + #[test] fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index f03daabc2b..8280d0f07a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2987,7 +2987,9 @@ other files through `$`: 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 `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + `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`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, From f6619ed732a998dd49500f1b6b6fb00a548fb403 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 03:21:05 -0800 Subject: [PATCH 010/106] Scripts: closing a path with no points throws PathItem.closed = true on a path with no points had no subpath to store the value in, so the assignment reported success while closed still read false. It now throws "Cannot close a path that has no points". --- crates/engine/src/script/dom/paths.rs | 4 ++++ crates/engine/src/tests/script_dom_paths.rs | 9 +++++++++ docs/mcp.md | 1 + 3 files changed, 14 insertions(+) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 4673e6277e..74d08e2972 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -760,6 +760,10 @@ 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)?; + // A path with no points has no subpath to keep the value in. + if closed && read_points(h, item, |subs| subs.is_empty())? { + return Err(HostError::Error("Cannot close a path that has no points".into())); + } edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 7df8022c5c..3be3901e7a 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -193,6 +193,15 @@ fn opening_a_path_deselects_its_closing_segment() { assert!(sel.objects.contains(&a)); } +#[test] +fn closing_a_path_without_points_throws() { + let (mut s, _, _) = doc(); + let e = failure(&mut s, "var p = app.activeDocument.pathItems.add(); p.closed = true;"); + assert!(e.contains("Cannot close a path that has no points"), "{e}"); + // Opening it stores nothing and is allowed. + log(&mut s, "var p = app.activeDocument.pathItems.add(); p.closed = false;"); +} + #[test] fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 8280d0f07a..8e3dd85484 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3001,6 +3001,7 @@ other files through `$`: `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the script uses any other member or command, or the points of another path, 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 throws `Cannot close a path that has no points`. Writing changes that added, removed or replaced points deselects the path's direct-selected anchors, even when the path ends with as many points as before; changes that only move points or handles, change a point's type or set `closed` keep them selected. From 118dcf9ef8a9436c17b5a47eff7579df606aab6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 07:14:10 -0800 Subject: [PATCH 011/106] Arrange Tools: Add Artboard Guides puts a guide rectangle inside or outside artboards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard, or around every artboard, at a typed offset: more than 0 puts it outside the artboard, less than 0 inside it. The dialog has Offset, Artboards (Active Artboard or All Artboards) and Preview, and OK applies as one undo step. - addon.arrange.artboardGuides {offset?, artboards?, artboard?, all?} puts the guide paths on the topmost top-level layer named Artboard Guides, made above the others when there is none. That layer keeps its lock and visibility. A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no undo step. - An inset that leaves an artboard no width or height, an edge past the canvas, and bad params are refused with an error. The command is off without artboards. - The command is in ON_ACTIVE_ARTBOARD, so the app passes the active artboard as `artboard`, and command.batch and action playback pass it to a step that names none; when it is left out, the journal records the artboard used, so a replay acts on the same one. The dialog sends the artboard the view showed when it opened. - Plug-ins may call it (plugin_call/reviewed.rs). Docs: docs/mcp.md › Arrange Tools add-on and app.doScript, docs/target-app-parity.md, docs/ui-parity.md; command.batch params text. --- crates/engine/src/cmd/addons/arrange.rs | 9 +- .../src/cmd/addons/arrange/artboard_guides.rs | 126 +++++++++++ .../addons/arrange/artboard_guides/tests.rs | 205 ++++++++++++++++++ crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/command_sets.rs | 9 +- crates/ui-egui/src/addons/arrange.rs | 38 +++- crates/ui-egui/src/addons/arrange/tests.rs | 88 ++++++++ crates/ui-egui/src/app/commands.rs | 9 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 4 + docs/ui-parity.md | 1 + 12 files changed, 485 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/cmd/addons/arrange/artboard_guides.rs create mode 100644 crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index f81d7a599a..2857b71f0d 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -5,9 +5,11 @@ //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the //! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in -//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection -//! (a view command) are the UI's. +//! that order. Add Artboard Guides puts a rectangular guide around artboards ([`artboard_guides`]). +//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view +//! command) are the UI's. +mod artboard_guides; #[cfg(test)] mod tests; @@ -107,6 +109,9 @@ pub fn specs() -> Vec { sort ), ] + .into_iter() + .chain(artboard_guides::specs()) + .collect() } /// Exactly two objects are selected (Swap Objects). diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs new file mode 100644 index 0000000000..69231b1f8e --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -0,0 +1,126 @@ +//! Add Artboard Guides (`addon.arrange.artboardGuides`): a rectangular guide around each chosen +//! artboard, `offset` outside its edges (inside when negative), on a top-level layer named +//! Artboard Guides. Its dialog is the UI's. + +#[cfg(test)] +mod tests; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::super::super::panelcmds::{artboard_at, listed_artboards}; +use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; +use super::{LIMIT, number_in}; +use crate::sanity::rect_in_range; +use crate::{DocState, Result, Session}; + +/// The command. +pub(crate) const COMMAND: &str = "addon.arrange.artboardGuides"; +/// The top-level layer the guides go on, made when the document has none of that name. +pub(crate) const LAYER: &str = "Artboard Guides"; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.arrange.artboardGuides", + "Add Artboard Guides", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{offset?: pt −1000000..1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside), artboards?: [index…] (0-based; default: the active artboard, `artboard`), artboard?: index (the active artboard, which the app passes; default the view's, which the journal then records as `artboard` for a replay), all?: false (true: every artboard; not with `artboards`)} add a rectangular guide path around each of those artboards, `offset` from its edges, as one undo step. The guides go on the topmost top-level layer named Artboard Guides, which keeps its lock and visibility; a new one is made above the others when there is none. The guide paths have the current paint (Release Guides makes them paths with it). A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. It is an error when an inset leaves an artboard no width or no height, and when an edge of a guide would lie more than 4,000,000 pt from the origin along either axis. Off without artboards → {ids, layer: id (null when nothing was added and there is no such layer), skipped (guides already there)}", + has_artboards, + artboard_guides + )] +} + +/// A document with at least one artboard is open. +fn has_artboards(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if s.doc().map_err(|e| e.to_string())?.doc.artboards.is_empty() { Err("the document has no artboards".into()) } else { Ok(()) } +} + +/// The index of the view's active artboard ([`DocState::active_artboard`]): when the document no +/// longer has it, the artboard the document opened on, else the first. +fn active_artboard(st: &DocState) -> usize { + let d = &st.doc; + let at = |id: Option| id.and_then(|id| d.artboards.iter().position(|a| a.id == id)); + at(st.active_artboard).or_else(|| at(d.opened_artboard)).unwrap_or(0) +} + +/// The topmost top-level layer named [`LAYER`]. +fn guide_layer(d: &Document) -> Option { + d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id) +} + +/// Does `layer` already hold a guide path drawn as `rect` is? +fn holds_guide(d: &Document, layer: Option, rect: Rect) -> bool { + let path = shapes::rectangle(rect); + layer.and_then(|id| d.node(id)).is_some_and(|n| { + let mut found = false; + n.walk(&mut |c| { + found |= matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if *p == path); + }); + found + }) +} + +fn artboard_guides(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?; + let all = switch_or(p, "all", false, C)?; + let listed = p.get("artboards").filter(|v| !v.is_null()); + if all && listed.is_some() { + return Err(bad(C, "give `all` or `artboards`, not both")); + } + let st = s.doc()?; + let d = &st.doc; + if d.artboards.is_empty() { + return Err(bad(C, "the document has no artboards")); + } + // The active artboard: the one the app passes, else the view's, recorded for a replay. + let active = artboard_at(d, p, "artboard", C)?; + let indices: Vec = match listed { + Some(v) => listed_artboards(d, v, "artboards", C)?, + None if all => (0..d.artboards.len()).collect(), + None => vec![active.unwrap_or_else(|| active_artboard(st))], + }; + if let (false, None, None, Some(&i)) = (all, listed, active, indices.first()) { + s.note_journal("artboard", json!(i)); + } + let st = s.doc()?; + let d = &st.doc; + let layer = guide_layer(d); + let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0); + for i in indices { + let Some(board) = d.artboards.get(i) else { continue }; + let r = board.rect.inflate(offset, offset); + if !(r.width() > 0.0 && r.height() > 0.0) { + return Err(bad(C, format!("the inset leaves artboard {i} ({}) no width or height", board.name))); + } + if !rect_in_range(r) { + return Err(bad(C, "the guide would reach past the edge of the canvas")); + } + if holds_guide(d, layer, r) || rects.contains(&r) { + skipped += 1; + } else { + rects.push(r); + } + } + if rects.is_empty() { + return Ok(json!({ "ids": [], "layer": layer.map(|l| l.0), "skipped": skipped })); + } + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let (layer, ids) = s.edit("Add Artboard Guides", |d, _| { + let layer = guide_layer(d).unwrap_or_else(|| d.add_layer(Some(LAYER))); + let mut ids = Vec::with_capacity(rects.len()); + for r in &rects { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), Default::default()); + look.apply(d, &mut n); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + ids.push(d.insert(Some(layer), usize::MAX, n)?); + } + Ok((layer, ids)) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "layer": layer.0, "skipped": skipped })) +} diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs new file mode 100644 index 0000000000..5b8093b07e --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -0,0 +1,205 @@ +//! Add Artboard Guides: the guide rectangles it adds and where, the artboards it takes, the layer +//! it reuses, one undo step (none when nothing is added), when it is off, and bad params refused +//! without a change. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::Rect; + +use super::{COMMAND, LAYER}; +use crate::Session; + +/// A new document with one 400 × 300 pt artboard and a second one beside it. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("artboard.new", &json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn board(s: &Session, i: usize) -> Rect { + s.doc().unwrap().doc.artboards[i].rect +} + +fn ids(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() +} + +/// The guide rectangle of path `id`: its bounds, and that it is a guide on layer `layer`. +fn guide(s: &Session, layer: NodeId, id: NodeId) -> Rect { + let d = &s.doc().unwrap().doc; + let n = d.node(id).unwrap(); + assert!(matches!(n.kind, NodeKind::Path { guide: true, .. }), "{id:?} is a guide path"); + assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == id), "{id:?} is on the guides layer"); + n.geometric_bounds().unwrap() +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-9) +} + +fn layer_names(s: &Session) -> Vec { + s.doc().unwrap().doc.layers.iter().map(|l| l.display_name()).collect() +} + +#[test] +fn a_positive_offset_puts_a_guide_outside_the_active_artboard_on_a_new_layer() { + let mut s = session(); + let n = steps(&s); + let before = layer_names(&s); + let r = s.execute(COMMAND, &json!({"offset": 9})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let layer = NodeId(r["layer"].as_u64().unwrap()); + assert_eq!(r["skipped"], json!(0)); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + // The active artboard is the first when the view has not picked one. + assert!(near(guide(&s, layer, id), board(&s, 0).inflate(9.0, 9.0)), "{:?}", guide(&s, layer, id)); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.last().unwrap().id, layer, "the new layer goes above the others"); + assert_eq!(d.layers.last().unwrap().display_name(), LAYER); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_names(&s), before, "undo takes the layer away with the guide"); +} + +#[test] +fn the_active_artboard_is_the_one_the_view_keeps() { + let mut s = session(); + let second = s.doc().unwrap().doc.artboards[1].id; + s.doc_mut().unwrap().active_artboard = Some(second); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 1)), "offset 0: on the artboard's edges"); + assert_eq!(s.journal.last().unwrap().1["artboard"], json!(1), "the journal records the artboard for a replay"); + // The artboard the app passes wins over the view's. + let r = s.execute(COMMAND, &json!({"offset": 4, "artboard": 0})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 0).inflate(4.0, 4.0))); + assert!(s.execute(COMMAND, &json!({"artboard": 5})).is_err(), "no such artboard"); +} + +#[test] +fn a_negative_offset_insets_every_artboard_and_reuses_the_layer_keeping_its_lock_and_visibility() { + let mut s = session(); + let layer = NodeId(s.execute("layer.new", &json!({"name": LAYER})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.new", &json!({"name": "Art"})).unwrap(); + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + s.execute("layer.setProps", &json!({"ids": [layer.0], "visible": false})).unwrap(); + let (layers, n) = (s.doc().unwrap().doc.layers.len(), steps(&s)); + let r = s.execute(COMMAND, &json!({"offset": -12, "all": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step for every artboard"); + assert_eq!(r["layer"], json!(layer.0), "the layer of that name is reused"); + assert_eq!(s.doc().unwrap().doc.layers.len(), layers, "no layer is added"); + let added = ids(&r); + assert_eq!(added.len(), 2); + for (i, id) in added.into_iter().enumerate() { + assert!(near(guide(&s, layer, id), board(&s, i).inflate(-12.0, -12.0)), "artboard {i}"); + } + let l = s.doc().unwrap().doc.node(layer).unwrap().clone(); + assert!(l.locked && !l.visible, "the layer keeps its lock and visibility"); +} + +#[test] +fn listed_artboards_get_a_guide_each_and_a_guide_already_there_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1]})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + assert!(near(guide(&s, layer, id), board(&s, 1).inflate(5.0, 5.0))); + // Again: nothing to add, and no undo step. + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({"offset": 5, "artboards": [1, 1]})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1})); + assert_eq!(steps(&s), n, "a run that adds nothing makes no step"); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before) || *s.doc().unwrap().doc == *before); + // Both artboards: only the new one is added. + let both = s.execute(COMMAND, &json!({"offset": 5, "artboards": [0, 1]})).unwrap(); + assert_eq!(both["skipped"], json!(1)); + let [first] = ids(&both)[..] else { panic!("one guide: {both}") }; + assert!(near(guide(&s, layer, first), board(&s, 0).inflate(5.0, 5.0))); + assert_eq!(steps(&s), n + 1); +} + +#[test] +fn a_guide_grouped_inside_the_layer_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + assert!(d.node(layer).unwrap().children().unwrap().iter().any(|c| c.id == group)); + assert!(d.node(group).unwrap().children().unwrap().iter().any(|c| c.id == id)); + let (before, n) = (d.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1})); + assert_eq!(steps(&s), n, "a run that adds nothing makes no step"); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); +} + +#[test] +fn release_guides_gives_back_a_rectangle_path() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 3})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + s.execute("view.guides.release", &json!({"ids": [id.0]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(matches!(n.kind, NodeKind::Path { guide: false, .. })); + assert!(near(n.geometric_bounds().unwrap(), board(&s, 0).inflate(3.0, 3.0))); +} + +#[test] +fn an_inset_that_leaves_no_width_or_height_and_bad_params_are_refused_without_a_change() { + let mut s = session(); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + // The second artboard is 100 pt tall: an inset of 50 leaves it no height. + for p in [ + json!({"offset": -50, "all": true}), + json!({"offset": -200}), + json!({"offset": "9 pt"}), + json!({"offset": 1_000_001}), + json!({"offset": -1e308}), + json!({"all": 1}), + json!({"all": true, "artboards": [0]}), + json!({"artboards": []}), + json!({"artboards": [2]}), + json!({"artboards": [-1]}), + json!({"artboards": [0.5]}), + json!({"artboards": "0"}), + ] { + assert!(s.execute(COMMAND, &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); + let e = s.execute(COMMAND, &json!({"offset": -150})).unwrap_err().to_string(); + assert!(e.contains("no width or height"), "{e}"); +} + +#[test] +fn a_guide_past_the_edge_of_the_canvas_is_refused() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 3_999_000, "y": 0, "width": 500, "height": 100})).unwrap(); + let n = steps(&s); + let e = s.execute(COMMAND, &json!({"offset": 600, "artboards": [2]})).unwrap_err().to_string(); + assert!(e.contains("past the edge of the canvas"), "{e}"); + assert_eq!(steps(&s), n); + s.execute(COMMAND, &json!({"offset": 400, "artboards": [2]})).unwrap(); +} + +#[test] +fn it_is_off_without_artboards() { + let mut s = session(); + let enabled = |s: &Session| s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled; + assert!(enabled(&s)); + Arc::make_mut(&mut s.doc_mut().unwrap().doc).artboards.clear(); + assert!(!enabled(&s)); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index a48ac3e85b..31db92bfd5 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Batch", [], None, - "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", + "{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each addon.arrange.artboardGuides, edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with two or more artboards selected when the step runs, gets those as indices instead; the journal records the indices or index an artboard.fitToArt step got)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included", has_doc, batch::batch ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c2699f219c..947f644be9 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -4,6 +4,7 @@ /// Commands a plug-in may call when its manifest lists them, in order. pub(super) const ALLOWED: &[&str] = &[ + "addon.arrange.artboardGuides", "addon.arrange.grid", "addon.arrange.groupOverlapping", "addon.arrange.randomizeOpacity", diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 1346dc40c5..75a30965ea 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -4,8 +4,10 @@ use super::{NodeId, Value, cmd, find_command}; /// Paste in Place, in Front and in Back paste onto it, Align to Artboard aligns to it, Distribute /// Objects and Distribute Spacing with Align to Artboard distribute objects across it, All on /// Active Artboard selects on it, and Edit Symbol from the Symbols panel centers the symbol's art -/// on it. A `command.batch` given `artboard` passes it on to each of their steps that names none. -pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ +/// on it, and Add Artboard Guides puts its guide around it. A `command.batch` given `artboard` +/// passes it on to each of their steps that names none. +pub const ON_ACTIVE_ARTBOARD: [&str; 9] = [ + "addon.arrange.artboardGuides", "edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack", @@ -35,8 +37,9 @@ pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.p /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 35] = [ +const REPLAY_ONLY: [(&str, &str); 36] = [ ("file.new", "created"), + ("addon.arrange.artboardGuides", "artboard"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), ("file.saveAs", "modified"), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index a26f5f7a28..bfb5d53bce 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,7 +1,8 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, -//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping -//! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. +//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity, Sort Objects and +//! Add Artboard Guides, which preview on the canvas and run their `addon.arrange.*` command on OK; +//! Group Overlapping Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the +//! selection. use std::borrow::Cow; @@ -26,14 +27,18 @@ const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; +const GUIDES: &str = "addon.arrange.artboardGuides"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 5] = [ +const DIALOGS: [(&str, &str); 6] = [ (GRID, "Arrange in Grid"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), + (GUIDES, "Add Artboard Guides"), ]; +/// The artboards Add Artboard Guides puts guides around: `all` false or true. +const SCOPES: [(&str, &str); 2] = [("active", "Active Artboard"), ("all", "All Artboards")]; /// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes. const SIZES: std::ops::RangeInclusive = 0.001..=1e6; const GAPS: std::ops::RangeInclusive = -1e6..=1e6; @@ -63,6 +68,7 @@ pub fn menu() -> Vec { cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), + c("Add Artboard Guides…", GUIDES), Sep, cp("Zoom to Selection", ZOOM, json!({})), ] @@ -73,6 +79,7 @@ static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, fou static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; +static GUIDES_SPEC: Spec = Spec { command: GUIDES, params: guides_params, found: None }; /// The dialog over `rows`, titled by the heading of `command`. fn dialog<'a>(command: &str, rows: Vec) -> ParamDialog<'a> { @@ -152,6 +159,11 @@ fn sort_rows() -> Vec { ] } +fn guides_rows(lengths: LengthUnits) -> Vec { + // More than 0 outside the artboard, less than 0 inside it. + vec![length("offset", "Offset:", 0.0, GAPS, lengths), choice("scope", "Artboards:", &SCOPES, "active")] +} + fn grid_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&grid_rows(POINTS), fields)) } @@ -181,6 +193,18 @@ fn sort_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&sort_rows(), fields)) } +/// Add Artboard Guides' offset, and `all` for All Artboards, else the artboard active when the dialog opened. +fn guides_params(fields: &DialogFields) -> Value { + let mut params = form::json_of(&guides_rows(POINTS), fields); + let all = fields.text("scope") == Some("all"); + params.remove("scope"); + if all { + params.remove("artboard"); + } + params.insert("all".into(), json!(all)); + Value::Object(params) +} + /// Opens the dialog of command `id` on the active document; `None` for another command and without a document. pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option> { let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?; @@ -207,6 +231,11 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option ( + guides_rows(lengths), + json!({ "offset": 0, "scope": "active", "artboard": crate::panels::artboards::selected(app, st.doc.artboards.len()) }), + ), // The first selected object's size, as the command measures it (a side it lacks: the least). _ => { let (w, h) = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| { @@ -229,6 +258,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), + GUIDES => super::dialogs::open(app, &GUIDES_SPEC, fields, move |fields| dialog(GUIDES, guides_rows(lengths)).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields)) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 420bfdb01d..44978f978b 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -109,6 +109,94 @@ fn real_opacity_edits_drive_validation_confirmation_and_cancel() { assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6); } +/// The bounds of the guide paths on the top-level layer Artboard Guides, from the back. +fn artboard_guides(app: &VectorcraftApp) -> Vec { + let d = &app.session.doc().unwrap().doc; + let layer = d.layers.iter().find(|l| l.name.as_deref() == Some("Artboard Guides")); + let guides = layer.and_then(|l| l.children()).into_iter().flatten(); + guides.filter(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: true, .. })).map(|n| n.geometric_bounds().unwrap()).collect() +} + +#[test] +fn real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step() { + for cancel in [true, false] { + let (app, _, _) = app(); + let board = app.session.doc().unwrap().doc.artboards[0].rect; + let (original, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len()); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Add Artboard Guides…"); + panel.frame(); + type_number(&mut panel, "Offset", "-12"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.number("offset")), Some(-12.0)); + assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)], "the preview insets the active artboard"); + panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX); + panel.frame(); + assert!(artboard_guides(&panel.app()).is_empty(), "no guide with Preview off"); + panel.click_role("Preview", craft::ui::contract::Role::CHECK_BOX); + panel.frame(); + assert_eq!(artboard_guides(&panel.app()), vec![board.inflate(-12.0, -12.0)]); + assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo, "a preview makes no step"); + panel.click(if cancel { "Cancel" } else { "OK" }); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + let state = app.session.doc().unwrap(); + if cancel { + assert!(*state.doc == *original, "Cancel leaves the document as it was"); + assert_eq!(state.history.undo.len(), undo); + } else { + assert_eq!(artboard_guides(&app), vec![board.inflate(-12.0, -12.0)]); + assert_eq!(state.history.undo.len(), undo + 1, "OK adds the guide as one undo step"); + } + } +} + +#[test] +fn add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset() { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + let boards: Vec<_> = app.session.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + assert_eq!(host::read(&app, id, |f| (f.number("offset"), f.text("scope").map(str::to_owned))), (Some(0.0), Some("active".to_owned()))); + host::set(&app, id, "offset", json!(18)); + host::set(&app, id, "scope", json!("all")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), boards.iter().map(|b| b.inflate(18.0, 18.0)).collect::>()); + // The second artboard is 100 pt tall: an inset of 50 leaves it nothing, so OK adds nothing. + let (before, undo) = (app.session.doc().unwrap().doc.clone(), app.session.doc().unwrap().history.undo.len()); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "offset", json!(-50)); + host::set(&app, id, "scope", json!("all")); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(*app.session.doc().unwrap().doc == *before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); +} + +#[test] +fn add_artboard_guides_uses_the_artboard_the_view_shows() { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + let second = app.session.doc().unwrap().doc.artboards[1].rect; + // The view moves to the second artboard without a command that tells the document, which + // still names the first. + app.view_mut().unwrap().artboard = 1; + let first = app.session.doc().unwrap().doc.artboards[0].id; + app.session.active_mut().unwrap().active_artboard = Some(first); + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "offset", json!(6)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "the preview"); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![second.inflate(6.0, 6.0)], "OK"); +} + #[test] fn set_size_of_each_sets_the_sides_ticked() { let (mut app, a, b) = app(); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index b7ff421414..35aeae8ea5 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -121,10 +121,11 @@ impl VectorcraftApp { } } - /// Paste in place, in front and in back (#693), Select › All on Active Artboard (#1006), and Align, - /// Distribute Objects and Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols - /// panel act on the active artboard, the view's, which the app adds to command `id`'s `params` as - /// `artboard`. A batch passes it on to those steps. While the Artboard tool has several artboards + /// Add Artboard Guides (Object › Plug-ins › Arrange Tools), Paste in place, in front and in + /// back (#693), Select › All on Active Artboard (#1006), and Align, Distribute Objects and + /// Distribute Spacing with Align to Artboard, and Edit Symbol from the Symbols panel act on the + /// active artboard, the view's, which the app adds to command `id`'s `params` as `artboard`. A + /// batch passes it on to those steps. While the Artboard tool has several artboards /// selected, the paste commands get those as `artboards` instead, and paste a copy on each; in a /// document without artboards they get neither. fn add_active_artboard(&self, id: &str, params: &mut Value) { diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..c64140765c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3238,7 +3238,8 @@ through `$`: https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it, and returns `undefined` once every step has run. The actions come from `script.run`'s `actions`; the app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own - steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and + steps. A step that acts on the active artboard (Add Artboard Guides, Paste in Place, in Front and in Back, Align, + Distribute Objects and Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one @@ -17441,10 +17442,13 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | +| `addon.arrange.artboardGuides` | `offset` pt −1000000…1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside); `artboards` [index…] (0-based; the active artboard); `artboard` index (the active artboard, which the app passes; the view's when left out, and the journal then records it for a replay); `all` (false; true: every artboard; not with `artboards`) | Adds a rectangular guide path around each of those artboards, `offset` from its edges, on the topmost top-level layer named Artboard Guides (made above the other layers when there is none; it keeps its lock and visibility). It acts on artboards, not on the selection. The guides have the current paint, which `view.guides.release` gives back with the path. A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. An inset that leaves an artboard no width or no height, and a guide edge more than 4,000,000 pt from the origin, are errors. Off without artboards. → `{ids, layer, skipped}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, -and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs +and fails with nothing selected. Add Artboard Guides… opens a dialog with Offset and Artboards (Active Artboard, or All +Artboards, which sends `all: true`) and a Preview; for Active Artboard it sends the artboard the view showed when the +dialog opened as `artboard`. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs (`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. @@ -17452,6 +17456,7 @@ fields are the command's parameters, with Preview (Randomize Opacity's seed, and {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} {"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} {"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} +{"name":"run_command","arguments":{"command":"addon.arrange.artboardGuides","params":{"offset":-18,"all":true}}} ``` ## Document Tools add-on diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..57c5ac4ae1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3156,6 +3156,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Sort Objects… sorts the top-level selected objects (or `ids`, at most 20000) by one attribute (width, height, area, x or y position, opacity or stacking order; small to large, large to small, or a random order from a seed) and gives them another in that order, the first the smallest value: the objects trade the values they have, or with Distribute Evenly the values step evenly from the smallest to the largest. Lining objects up left to right by size, restacking them so the largest is at the back, or giving them heights that step with their x position are each one run. Sizes and places are measured and set as `object.setBounds` measures them (Use Preview Bounds); a width, height or area changes about each object's centre (an area in proportion), and stacking order trades places only among objects of the same layer or group. One undo step; no step when nothing changes. Tests: `sort_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each attribute sorted by and applied, both directions, distribute, layers kept apart, the seeded random order, `ids`, no step when in order, bad params), `sort_objects_opens_its_dialog_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Add Artboard Guides (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard, or around every artboard, at the Offset typed: more than 0 puts it outside the artboard (a bleed line), less than 0 inside it (a safe-area line). The guides go on a top-level layer named Artboard Guides, made above the others the first time and reused after that with its lock and visibility as they are; a guide already anywhere in that layer with the same rectangle is not added again. The dialog acts on the artboard the view shows. One undo step; no step when nothing is added. An inset that leaves an artboard no width or no height is refused. `addon.arrange.artboardGuides` also takes a list of artboards. Tests: `cmd::addons::arrange::artboard_guides::tests` in `vectorcraft-engine` (outside and inside offsets, the active artboard and the one the journal records, every artboard and listed ones, the layer reused with its lock and visibility, no repeat and no step, a guide grouped inside the layer, Release Guides, bad params and too large an inset refused, off without artboards), `real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step`, `add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset` and `add_artboard_guides_uses_the_artboard_the_view_shows` in `vectorcraft-ui-egui`, and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Type Tools add-on: Text Tweaker (2026-11-03) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 453bda832d..82ff2667eb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -567,6 +567,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard or every artboard at an Offset (outside when more than 0, inside when less) on a reused Artboard Guides layer; a guide already there is not repeated; an inset that leaves no width or height is refused; Preview; one undo step | done | `addon.arrange.artboardGuides`, `crates/engine/src/cmd/addons/arrange/artboard_guides.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | From ff81deb8d76bb7622130908f91deb023b01e24eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:24:07 -0800 Subject: [PATCH 012/106] MCP: dialog params texts match the keys and fields ui.inspect lists ui.inspect lists each open dialog with a key and its fields. The params text of these commands, and docs/mcp.md, docs/control-protocol.md and docs/target-app-parity.md, named keys and fields that ui.inspect does not report: - Recolor Artwork (ui.recolorDialog) and JavaScript Files (ui.javascriptFilesDialog) were listed with key null. Both dialogs now report the key their texts name: recolor and javascriptFiles. - Print (file.print) and the print preset editor (ui.printPresetDialog): the texts said dialog print and printPreset; the key is null. The Print dialog lists section and sheet, not toFile, __section or __sheet, and Done is choice: done followed by ui.dialog.confirm, not discard: true. printer takes a name from print.printers, or PDF File, with which Print saves the job as a PDF. - Find and Replace (ui.findAndReplace, ui.paramDialog with edit.findReplace): the texts said dialog findReplace and named an action field that ui.dialog.confirm runs. The key is null, the dialog lists no action field, and the texts now name its fields and buttons. - Check Script (ui.checkScript): the texts said dialog scriptCheck with a report field. The key is null and the fields are lines, notes and groups; Copy copies the report as text. - Import Shortcut Set (ui.shortcutImportDialog): the review opens inside Keyboard Shortcuts, which ui.inspect does not list. The text no longer names a shortcutImport dialog or its fields, and says that shortcutSet.read reads a file and matches its entries and importMatches.set stores matches. - Data Recovery: the app asks about one copy at a time, with the field choice (recover or discard), not copies and discard. - Reset Preferences: the question over Preferences is not listed in dialogs, and has no resetPreferences key. Each command has a test that opens the dialog and checks its params text against what ui.inspect lists. --- crates/mcp/src/ui_catalog.rs | 17 ++++++---- .../ui-egui/src/dialogs/find_replace/tests.rs | 25 +++++++++++++++ .../ui-egui/src/dialogs/javascript_files.rs | 19 +++++++++++ crates/ui-egui/src/dialogs/recolor.rs | 21 ++++++++++++ crates/ui-egui/src/dialogs/tests_print.rs | 30 +++++++++++++++++ .../src/dialogs/tests_shortcut_import.rs | 17 ++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 17 ++++++---- crates/ui-egui/src/tests/script_check.rs | 18 +++++++++++ docs/control-protocol.md | 32 +++++++++---------- docs/mcp.md | 21 ++++++------ docs/target-app-parity.md | 2 +- 11 files changed, 179 insertions(+), 40 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..1b6ff1fe63 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -217,7 +217,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.shortcutImportDialog", "Import Shortcut Set…", "", - "{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded (dialog `shortcutImport`: name, start: defaults|current, remember, rows: [{name, section, line, key, modifiers, target: entry id | \"\" (no equivalent) | null (not chosen), from, choices, on}], keys and mods: {code: {text, from, votes, names}}); Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too", + "{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded. The review opens inside Edit › Keyboard Shortcuts, which ui.inspect does not list in `dialogs` and ui.dialog.set does not reach; with a file the reply is {entries, unread}. Without the window, shortcutSet.read reads a file and matches its entries, and importMatches.set stores matches. Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too", ), ("view.outline", "Outline", "Cmd+Y", "{} toggle Outline/Preview"), ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), @@ -1006,7 +1006,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (listed last in ui.inspect's `dialogs`, with key null), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers and lockedLayers (it also lists tab, more, goToKind, goToTarget and the read-only message), and the buttons Find Next (the next match, edit.findNext, shown in the dialog with its place among the matches), Replace (the match found, edit.replaceMatch), Replace & Find (both), Replace All (edit.findReplace) and Close. Replace and Replace & Find change a match that Find Next reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and the dialog does not open), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", @@ -1979,7 +1979,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (listed last in ui.inspect's `dialogs`, with key null; fields: the print.setup settings, `preset` (setting it loads that print preset; Save Preset… saves them as one), `printer` (a print.printers name, or PDF File, with which Print saves the job as a PDF), `section` and `sheet`; Print keeps the settings with the document and prints, Done (`choice`: done, then ui.dialog.confirm) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", ), ( "print.printers", @@ -1998,7 +1998,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.printPresetDialog", "Print Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (dialog `printPreset`: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (listed last in ui.inspect's `dialogs`, with key null; fields: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets", ), ( "plugin.dialog", @@ -2082,7 +2082,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.checkScript", "Check Script…", "", - "{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (dialog `scriptCheck`: `report`, script.check's result; Copy Report copies it as JSON); without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)", + "{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (listed last in ui.inspect's `dialogs`, with key null; fields `lines`, `notes` and `groups`); with a file the reply is script.check's result, and the report's Copy button copies the report as text; without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)", ), ( "ui.perspectiveGridDialog", @@ -2210,6 +2210,11 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{plane?: left|right|ground (default: the active plane)} open the plane's options, as double-clicking its plane widget does (dialog `perspectivePlane`: location (pt along the plane's normal), objects: none|move|copy): OK runs perspective.plane.move", ), - ("ui.findAndReplace", "Find and Replace…", "", "{} open the Find and Replace dialog (Edit › Find and Replace…; dialog `findReplace`)"), + ( + "ui.findAndReplace", + "Find and Replace…", + "", + "{} open the Find and Replace dialog (Edit › Find and Replace…; listed last in ui.inspect's `dialogs`, with key null; fields and buttons as ui.paramDialog with edit.findReplace)", + ), ("ui.retype", "Retype", "", "{} open the Retype panel (Window › Retype) or start Retype"), ]; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index e90efe3f8a..49d784e09f 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -443,3 +443,28 @@ fn edit_find_next_starts_at_the_first_restored_match_with_that_frame_selected() assert_eq!(selected(&p), vec![first]); assert_eq!(undo_steps(&p), before); } + +/// `ui.findAndReplace` and `ui.paramDialog` with edit.findReplace open the dialog that `ui.inspect` lists with key null +/// and the fields the params text names, as both params texts say. +#[test] +fn params_texts_match_what_ui_inspect_lists() { + const FIELDS: [&str; 7] = ["find", "replace", "matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers"]; + let doc = |command: &str| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3; + for (command, params) in [("ui.findAndReplace", json!({})), ("ui.paramDialog", json!({"command": super::COMMAND, "params": {}}))] { + let mut app = crate::testing::windowed(app_with(&["alpha"]).0); + app.run(command, params).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog"); + assert!(entry["key"].is_null(), "{command}: {entry}"); + assert!(doc(command).contains("with key null"), "{command} opens a dialog with key null, which its params text does not say"); + for field in FIELDS { + assert!(entry["fields"].get(field).is_some(), "{command}: ui.inspect does not list `{field}`"); + } + } + let named = doc("ui.paramDialog"); + for field in FIELDS { + assert!(named.contains(field), "the params text of ui.paramDialog does not name `{field}`"); + } + assert!(!named.contains("and action"), "the params text of ui.paramDialog names an `action` field that ui.inspect does not list"); +} diff --git a/crates/ui-egui/src/dialogs/javascript_files.rs b/crates/ui-egui/src/dialogs/javascript_files.rs index bbc16218e2..1475d2ca14 100644 --- a/crates/ui-egui/src/dialogs/javascript_files.rs +++ b/crates/ui-egui/src/dialogs/javascript_files.rs @@ -111,6 +111,10 @@ impl StackDialog for JavaScriptFiles { dialog_id(KEY) } + fn key(&self) -> Option<&str> { + Some(KEY) + } + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let Self { open, files, form } = self; let shown = Dialog::new(tl!("JavaScript Files")) @@ -418,4 +422,19 @@ mod tests { fixture.click(&add); assert_eq!(form.borrow().pending, Some(Pending::Add)); } + + /// `ui.javascriptFilesDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.javascriptFilesDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run(COMMAND, json!({})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KEY); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 9420119f94..27f0aeaab6 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1993,6 +1993,10 @@ impl StackDialog for RecolorDialog { self.id } + fn key(&self) -> Option<&str> { + Some(KIND) + } + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { self.shown(ui) } @@ -5634,4 +5638,21 @@ mod tests { rc.settled(); assert!(rc.by_label(tl!("Color Groups")).is_none(), "and hides with `groupStorage`"); } + + /// `ui.recolorDialog` opens the dialog whose `key` its params text names, as `ui.inspect` lists it. + #[test] + fn params_text_names_the_dialog_key_ui_inspect_lists() { + const COMMAND: &str = "ui.recolorDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let mut app = app(120); + let red = square(&mut app, 10.0, "#ff0000"); + app.run("select.set", json!({"ids": [red]})).unwrap(); + let rc = opened(app, json!({})); + let app = rc.app(); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + let key = ui["dialogs"].as_array().and_then(|d| d.last()).and_then(|d| d["key"].as_str()).expect("a dialog with a key"); + assert_eq!(key, KIND); + assert!(doc.contains(&format!("dialog `{key}`")), "{COMMAND} opens `{key}`, which its params text does not name"); + } } diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 183d6f1056..67acb6d962 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -620,3 +620,33 @@ fn every_number_and_length_field_is_named() { } } } + +/// Opens the dialog of `command` and checks its params text against the last dialog `ui.inspect` lists: the text says +/// the dialog's key is null, and names `fields`, each of which the dialog lists. +fn assert_params_text_matches_ui_inspect(command: &str, fields: &[&str]) { + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3; + let (mut app, _) = app(); + app.run(command, json!({})).unwrap(); + pump(&mut app); + let ui = crate::control::inspect(&app, &ctx(&app)); + let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog"); + assert!(entry["key"].is_null(), "{command}: {entry}"); + assert!(doc.contains("with key null"), "{command} opens a dialog with key null, which its params text does not say"); + for field in fields { + assert!(entry["fields"].get(field).is_some(), "{command}: ui.inspect does not list `{field}`"); + assert!(doc.contains(&format!("`{field}`")), "{command}: its params text does not name `{field}`"); + } +} + +/// `file.print` opens the Print dialog, which `ui.inspect` lists with key null and the fields its params text names. +#[test] +fn print_params_text_matches_what_ui_inspect_lists() { + assert_params_text_matches_ui_inspect("file.print", &["preset", "printer", "section", "sheet"]); +} + +/// `ui.printPresetDialog` opens the preset editor, which `ui.inspect` lists with key null and the fields its params +/// text names. +#[test] +fn preset_editor_params_text_matches_what_ui_inspect_lists() { + assert_params_text_matches_ui_inspect("ui.printPresetDialog", &["name"]); +} diff --git a/crates/ui-egui/src/dialogs/tests_shortcut_import.rs b/crates/ui-egui/src/dialogs/tests_shortcut_import.rs index 3123a2891f..4cbf4d396f 100644 --- a/crates/ui-egui/src/dialogs/tests_shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/tests_shortcut_import.rs @@ -263,3 +263,20 @@ fn an_imported_shortcut_reaches_a_filter_plugin_picked_as_its_target() { vectorcraft_plugins::registry::remove(id); assert!(shortcut_editor::entries().iter().all(|e| e.key != key), "a removed filter is no target"); } + +/// `ui.shortcutImportDialog` shows its review inside Keyboard Shortcuts, which `ui.inspect` does not list in `dialogs`, +/// so its params text names no dialog key. +#[test] +fn params_text_names_no_dialog_key_for_the_review() { + const COMMAND: &str = "ui.shortcutImportDialog"; + let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let mut app = crate::testing::windowed(app()); + let b64 = vectorcraft_format::base64_encode(SET.as_bytes()); + let r = app.run(COMMAND, json!({"dataBase64": b64, "name": "Sent.kys"})).unwrap(); + assert!(r["entries"].is_u64() && r["unread"].is_u64(), "{r}"); + assert!(app.shortcuts_dialog.as_ref().is_some_and(|d| d.pending_review.is_some()), "the review waits in Keyboard Shortcuts"); + let ctx = app.ui_ctx.clone().unwrap(); + let ui = crate::control::inspect(&app, &ctx); + assert_eq!(ui["dialogs"], json!([]), "{COMMAND} opens no dialog that ui.inspect lists"); + assert!(!doc.contains("dialog `"), "the params text of {COMMAND} names a dialog key that ui.inspect does not list"); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..723282ca0f 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -218,7 +218,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.shortcutImportDialog", "Import Shortcut Set…", "", - "{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded (dialog `shortcutImport`: name, start: defaults|current, remember, rows: [{name, section, line, key, modifiers, target: entry id | \"\" (no equivalent) | null (not chosen), from, choices, on}], keys and mods: {code: {text, from, votes, names}}); Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too", + "{path? | dataBase64?, name?} open Import Shortcut Set for a shortcut set another app saved as text (.kys; without a file, pick one): each entry matched to a tool, command or panel, and its key and modifier codes decoded. The review opens inside Edit › Keyboard Shortcuts, which ui.inspect does not list in `dialogs` and ui.dialog.set does not reach; with a file the reply is {entries, unread}. Without the window, shortcutSet.read reads a file and matches its entries, and importMatches.set stores matches. Apply assigns the ready rows over Edit › Keyboard Shortcuts' working set, remembers the matches (importMatches.set) and shows Keyboard Shortcuts, whose OK keeps them. File › Open of a .kys opens it too", ), ("view.outline", "Outline", "Cmd+Y", "{} toggle Outline/Preview"), ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), @@ -1007,7 +1007,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.paramDialog", "Command Dialog", "", - "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed", + "{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (listed last in ui.inspect's `dialogs`, with key null), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers and lockedLayers (it also lists tab, more, goToKind, goToTarget and the read-only message), and the buttons Find Next (the next match, edit.findNext, shown in the dialog with its place among the matches), Replace (the match found, edit.replaceMatch), Replace & Find (both), Replace All (edit.findReplace) and Close. Replace and Replace & Find change a match that Find Next reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and the dialog does not open), and Edit › Find Next goes on from it in the same document while the dialog is closed", ), ( "ui.recolorDialog", @@ -1980,7 +1980,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (listed last in ui.inspect's `dialogs`, with key null; fields: the print.setup settings, `preset` (setting it loads that print preset; Save Preset… saves them as one), `printer` (a print.printers name, or PDF File, with which Print saves the job as a PDF), `section` and `sheet`; Print keeps the settings with the document and prints, Done (`choice`: done, then ui.dialog.confirm) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", ), ( "print.printers", @@ -1999,7 +1999,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.printPresetDialog", "Print Preset", "", - "{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (dialog `printPreset`: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets", + "{name?: a saved preset to edit | preset?: the preset a new one starts from (default [Default])} open the preset editor (listed last in ui.inspect's `dialogs`, with key null; fields: the Print dialog's settings fields plus `name`); OK runs print.presets.save and returns to Print Presets", ), ( "plugin.dialog", @@ -2083,7 +2083,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.checkScript", "Check Script…", "", - "{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (dialog `scriptCheck`: `report`, script.check's result; Copy Report copies it as JSON); without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)", + "{path? | data? | dataBase64?, name?, includes?: true with a path} check a script written for the reference app without running it (script.check; with a path, the files its #include lines name are checked too) and show the report (listed last in ui.inspect's `dialogs`, with key null; fields `lines`, `notes` and `groups`); with a file the reply is script.check's result, and the report's Copy button copies the report as text; without a file pick one (the web opens the browser's file picker; File › Open of a .jsx, .jsxinc or .jsxbin file shows the report too)", ), ( "ui.perspectiveGridDialog", @@ -2211,6 +2211,11 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{plane?: left|right|ground (default: the active plane)} open the plane's options, as double-clicking its plane widget does (dialog `perspectivePlane`: location (pt along the plane's normal), objects: none|move|copy): OK runs perspective.plane.move", ), - ("ui.findAndReplace", "Find and Replace…", "", "{} open the Find and Replace dialog (Edit › Find and Replace…; dialog `findReplace`)"), + ( + "ui.findAndReplace", + "Find and Replace…", + "", + "{} open the Find and Replace dialog (Edit › Find and Replace…; listed last in ui.inspect's `dialogs`, with key null; fields and buttons as ui.paramDialog with edit.findReplace)", + ), ("ui.retype", "Retype", "", "{} open the Retype panel (Window › Retype) or start Retype"), ]; diff --git a/crates/ui-egui/src/tests/script_check.rs b/crates/ui-egui/src/tests/script_check.rs index 6978e86f4f..7238e77195 100644 --- a/crates/ui-egui/src/tests/script_check.rs +++ b/crates/ui-egui/src/tests/script_check.rs @@ -222,3 +222,21 @@ fn every_id_a_report_holds_has_a_label() { assert!(problem_label(code).is_some(), "{code}"); } } + +/// `ui.checkScript` with a script opens the report that `ui.inspect` lists with key null and the fields its params text +/// names. +#[test] +fn params_text_matches_what_ui_inspect_lists() { + const COMMAND: &str = "ui.checkScript"; + let doc = menus::UI_COMMANDS.iter().find(|c| c.0 == COMMAND).expect("registered").3; + let mut app = app(); + menus::run_ui_command(&mut app, COMMAND, &json!({"data": "var a = 1;", "name": "Clean.jsx"})).unwrap().unwrap(); + let ui = crate::control::inspect(&app, &window(&app)); + let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog"); + assert!(entry["key"].is_null(), "{COMMAND}: {entry}"); + assert!(doc.contains("with key null"), "{COMMAND} opens a dialog with key null, which its params text does not say"); + for field in ["lines", "notes", "groups"] { + assert!(entry["fields"].get(field).is_some(), "{COMMAND}: ui.inspect does not list `{field}`"); + assert!(doc.contains(&format!("`{field}`")), "{COMMAND}: its params text does not name `{field}`"); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df9b36eee8..421cd60566 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -939,11 +939,11 @@ with `overprints: "preserve"`. Its `ui.dialog.confirm` sets every option as `fla in the dropdown or with `ui.dialog.set {flattenerPreset}`, drops `flattener`, and so does `ui.epsOptionsDialog` with a `flattenerPreset` and no `flattener`. -Data Recovery: at launch, copies left behind by a crash open the `recovery` dialog (never copies another running -instance keeps, so instances started side by side for screenshots don't get it). Fields: `copies` (`[{file, title, -saved}]`, from `file.recovery.list`) and `discard`. `ui.dialog.confirm` restores them all (`file.recovery.restore` -each, opening " [Recovered]" documents), `discard: true` then confirm deletes them, `ui.dialog.cancel` keeps them -for the next launch. While copies are written in the background `ui.inspect` lists them under `background` +Data Recovery: at launch, the app asks about each copy left behind by a crash in turn (never copies another running +instance keeps, so instances started side by side for screenshots don't get it). `ui.inspect` lists each question in +`dialogs` with key null and one field, `choice`: `recover` (the default) or `discard`. `ui.dialog.confirm` answers for that copy: `recover` restores it (`file.recovery.restore`, opening a +" [Recovered]" document) and `discard` deletes it (`file.recovery.discard`); the next copy is then asked about. +`ui.dialog.cancel` keeps that copy and every later one for the next launch. While copies are written in the background `ui.inspect` lists them under `background` ("Saving recovery data for "). After a restore the status bar shows the count followed by the first of the restored documents' notes: each document's lines about its linked files, then its warnings (what reading the copy left out first), named with the document's title when more than one was restored. Hovering the message lists them all. The @@ -1010,15 +1010,15 @@ document starts on `cmyk`), `layers` (true: Write Layers; false: Flat Image, who `preserveText`, `maxEditability` and `hiddenLayers` (with layers) and `embedIcc`. `ui.dialog.set` the fields and `ui.dialog.confirm` writes the file(s) with `document.export`; with Flat Image it leaves `preserveText` out. -Print: File → Print… (`file.print` with no params, Ctrl/Cmd+P) opens the `print` dialog on the document's print -settings. Its fields are the `print.setup` settings (`copies`, `artboards`, `range`, `media`, `orientation`, -`placement`, `scaling`, `marks`, `bleed`, `output`, `graphics`, `color`, `margin`…; a section is an object, as -`{field: "marks", value: {"trim": true}}`) plus `printer` (a name from `print.printers`, `""` the system's default) and -`toFile` (save the job as a PDF), and the UI-only `__section` (General, Marks and Bleed, Output, Graphics, Color -Management, Advanced, Summary) and `__sheet` (the page the preview shows, 0-based). `ui.dialog.confirm` (Print) keeps -the settings with the document (`print.setup`, one undo step) and prints them: to the printer through the system's -print queue (the web: the browser's print dialog), else, with `toFile` or no printing available, a save panel for the -PDF. With `discard: true` it is Done: it only keeps the settings. Settings that can't print (a missing artboard, a +Print: File → Print… (`file.print` with no params, Ctrl/Cmd+P) opens the Print dialog on the document's print +settings. `ui.inspect` lists it last in `dialogs`, with key null. Its fields are the `print.setup` settings (`copies`, +`artboards`, `range`, `media`, `orientation`, `placement`, `scaling`, `marks`, `bleed`, `output`, `graphics`, +`color`, `margin`…; a section is an object, as `{field: "marks", value: {"trim": true}}`) plus `printer` (a name from +`print.printers`, or `PDF File`, with which Print saves the job as a PDF), and the UI-only `section` (General, Marks and Bleed, Output, Graphics, Color Management, Advanced, +Summary) and `sheet` (the page the preview shows, 0-based). `ui.dialog.confirm` (Print) keeps the settings with the +document (`print.setup`, one undo step) and prints them: to the printer through the system's print queue (the web: +the browser's print dialog), else, with `PDF File` or no printing available, a save panel for the PDF. After +`ui.dialog.set {field: "choice", value: "done"}`, `ui.dialog.confirm` is Done: it only keeps the settings. Settings that can't print (a missing artboard, a range of no tiles) answer with an error and keep the dialog open. `file.print {settings?, printer?, toFile?, path?}` prints without the dialog; `print.printers` lists the printers and `print.printerSetup {printer?}` opens their system settings (Setup…). Desktop submission returns `{background: true, printed: false, printer, status}` @@ -1033,13 +1033,13 @@ reply `{ok: false, error: "…"}`; later spooler failures appear in `ui.inspect` no second reply or structured backend error object. Headless MCP keeps its engine-only `file.print` result (`path` or `dataBase64`, plus the same print metadata); no spooler fields are added there. -Print presets: in the `print` dialog, `preset` names the print preset whose settings were loaded last; setting it +Print presets: in the Print dialog, `preset` names the print preset whose settings were loaded last; setting it (`ui.dialog.set {field: "preset", value: "Posters"}`) loads that preset's settings, and the list reads `[Custom]` once they differ. Save Preset… shows a name field (`__savePresetAs`): while it shows, `ui.dialog.confirm` saves the dialog's settings as that preset (`print.presets.save`) and selects it instead of printing. `ui.printPresetsDialog {selected?}` opens Edit → Print Presets (dialog `printPresets`, field `selected`); `[Default]` is protected. New… and Edit… open the preset editor, which `ui.printPresetDialog {name? (a saved preset to edit) | preset? (the preset a new one starts -from)}` opens too: dialog `printPreset`, the Print dialog's settings fields plus `name`; `ui.dialog.confirm` runs +from)}` opens too, listed last in `dialogs` with key null: the Print dialog's settings fields plus `name`; `ui.dialog.confirm` runs `print.presets.save` and returns to Print Presets (a new preset can't take a name in use). Delete, Import… and Export… are `print.presets.delete`, `print.presets.import` and `print.presets.export`; `ui.dialog.confirm` closes. Opening a `.vcprintpresets` file with `app.open` imports its presets. diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..d863ff41f4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10430,8 +10430,8 @@ settings whose label, section or category contains it, ignoring case, in the int "No settings found". Choosing a setting sets `__category` to its category, sets `__found` to its key (the row is highlighted until another category is shown) and clears `__search`. Cmd/Ctrl+F focuses the field again; Escape in the field with text clears it, and Escape in the empty field closes the dialog. Its Reset Preferences button opens a -`resetPreferences` question (fields `message`, `detail`) over Preferences: `ui.dialog.cancel` shows Preferences again -as it was, and `ui.dialog.confirm` shows it again with every preference at its default value, applied by OK in +question over Preferences, which `ui.inspect` does not list in `dialogs`. While it shows, `ui.dialog.cancel` on +Preferences answers it and shows Preferences again as it was, and `ui.dialog.confirm` shows it again with every preference at its default value, applied by OK in Preferences. `prefs.reset` resets the preferences at once, without the question. OK in Preferences writes only the fields changed in the dialog since it opened or since its last Apply, so a preference, Smart Guides, Snap to Grid, Enable Contextual Task Bar or the document's units changed some other way while it is open (a command, a panel menu, @@ -13661,19 +13661,18 @@ nothing changes, no undo step is recorded. An empty `find` is an error in all th {"name":"run_command","arguments":{"command":"edit.findNext","params":{"find":"colour","wholeWord":true,"from":{"id":12,"start":4,"end":9}}}} ``` -In the app, Edit › Find and Replace… opens a dialog that stays open (kind `findReplace`), with Find and Replace With -fields, Match Case, Find Whole Word, Search Backwards, Check Hidden Layers and Check Locked Layers, and Find, Replace, -Replace & Find, Replace All and Done. Its fields are `find`, `replace`, `matchCase`, `wholeWord`, `backwards`, -`hiddenLayers`, `lockedLayers` and `action`; `ui.dialog.confirm` runs the `action`: `find` (the default), `replace`, -`replaceFind`, `replaceAll` or `done`, which closes the dialog. The dialog shows the match found in its line of text -with its place among the matches. Replace and Replace & Find change a match that Find reached with the Find text and -the options as they are now, and find one otherwise. Enter runs Find. Edit › Find Next goes on from the dialog's last +In the app, Edit › Find and Replace… opens a dialog that stays open, with Find and Replace With fields, Match Case, +Find Whole Word, Search Backwards, Check Hidden Layers and Check Locked Layers, and Find Next, Replace, Replace & Find, +Replace All and Close. `ui.inspect` lists it last in `dialogs`, with key null. Its fields are `find`, `replace`, +`matchCase`, `wholeWord`, `backwards`, `hiddenLayers` and `lockedLayers`, and it also lists `tab`, `more`, +`goToKind`, `goToTarget` and the read-only `message`. The dialog shows the match found in its line of text +with its place among the matches. Replace and Replace & Find change a match that Find Next reached with the Find text +and the options as they are now, and find one otherwise. Enter runs Find Next. Edit › Find Next goes on from the dialog's last search while the dialog is closed, and opens the dialog when there has been none. A place the search reached in one document is not used in another, nor once the Find text or an option that decides a match changes: the search then starts again as it does without `from`. `ui.paramDialog` opens the dialog on the last search, with the fields its `params` give in its place. A null field gives none, and a field of -the wrong type is an error that leaves the dialog closed. Once it is open, `ui.dialog.confirm` with a field of the -wrong type runs no action and returns the error. +the wrong type is an error that leaves the dialog closed. For other command dialogs, `params.__doc` can supply a document uid. The dialog previews and confirms only while that document is active. Confirming after a document switch closes the dialog without running its command. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ee49042298..cebff387af 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -967,7 +967,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Export and Import Preferences (#6435):** an optional VectorCraft feature. The Preferences dialog's Export Preferences… saves the applied preferences to a JSON file (`prefs.export`; the web build downloads it), and Import Preferences… applies such a file (`prefs.import`). The file leaves out the folder preferences. The import checks every value first and changes nothing on an error; it keeps the open document's units and records no undo step. The file format is VectorCraft's own. Tests: `crates/engine/src/tests/prefs_file.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. -- **Reset Preferences asks first (#6435):** the Preferences dialog's Reset Preferences button opens a question over the dialog (`resetPreferences`). Cancel or Escape goes back to Preferences unchanged, with its category, search and edits kept; OK goes back with every preference at its default value, which OK in Preferences applies and Cancel there discards. The question and its wording are VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Reset Preferences asks first (#6435):** the Preferences dialog's Reset Preferences button opens a question over the dialog, which `ui.inspect` does not list in `dialogs`. Cancel or Escape goes back to Preferences unchanged, with its category, search and edits kept; OK goes back with every preference at its default value, which OK in Preferences applies and Cancel there discards. The question and its wording are VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Reset Preferences resets every setting the dialog shows:** Smart Guides and Snap to Grid also return to their defaults (on and off) when Reset Preferences is confirmed, and General's Enable Contextual Task Bar takes the value the current workspace was saved with. OK in Preferences applies them with the other defaults, and Cancel keeps the values in use. A category's own reset resets the row of that category, and File Handling's also resets the app chosen for Edit Original. `prefs.reset` (the Command Palette's Reset Preferences) resets them too, each only when it resets every category or the setting's own, and with every category or File Handling it also clears the app chosen for Edit Original. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`, `crates/ui-egui/src/original_editor.rs`. - **Preferences OK keeps changes made outside the dialog:** OK preserves command or script changes to fields left unchanged in the dialog, including preferences, Smart Guides, Snap to Grid, Enable Contextual Task Bar and document units. A field edited in both places takes the dialog's value. OK saves an opening-time Hold Shortcut Delay correction unless a later command changed that value. An external reset preserves dialog edits, and Apply refreshes the baseline from current preferences and UI values. A workspace switched to while the dialog is open keeps its own Contextual Task Bar. With no field change or delay correction, OK writes nothing. The rule is VectorCraft's own. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. From c7e4a43c1a80a3620b03d1a2ecf09dd3e06ce89b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 21:32:17 -0800 Subject: [PATCH 013/106] Match Objects: refuse restacks into locked, blend or Live Paint containers; keep turned live-effect art's reference point A stacking match is now refused when the source's layer or group is locked, when the Layers panel would not take a target beside the source (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A rotation match on an object with a live effect that moves it (a Transform effect's offset) puts the measured reference point back where it was after the turn, and is refused, with no undo step, when the object cannot keep both its size and that point once pixel snapping has run. Builds on #10072. --- crates/engine/src/cmd/addons/arrange.rs | 56 +++++- crates/engine/src/cmd/addons/arrange/tests.rs | 164 ++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 221 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index c1e99bb155..43397e9421 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path, restack into a locked layer or group, put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -436,6 +436,8 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { }; let angle = s.doc()?.doc.bbox_angle(&[source]); let mut xfs = Vec::with_capacity(targets.len()); + // Where each turned target's reference point is before the match; it stays there. + let mut pinned: HashMap = HashMap::new(); for &id in &targets { let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 }; let Some(b) = s.transform_box(&[id]) else { @@ -458,6 +460,12 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { // Rotation uses the reference point that sizing keeps in place. let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); xf = Affine::rotate_about(-turn.to_radians(), at) * xf; + if s.bounds_measure().preview && { + let d = &s.doc()?.doc; + d.node(id).is_some_and(|n| effects::preview::draws_geometry(&d.symbol_boxes(), n)) + } { + pinned.insert(id, at); + } } if wanted.is_some() { let sc = scaling(s, &json!({ "strokes": strokes })); @@ -498,6 +506,19 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "a clipping path can't change its place in the stacking order")); } let parent = d.parent_of(source); + if parent.is_some_and(|p| crate::cmd::layer::locked_within(d, p)) { + return Err(bad(C, "the layer or group is locked")); + } + // Live Paint art is rebuilt from its paths when they move: Match Objects leaves it in place. + let in_live_paint = + |id: NodeId| d.ancestry(id).unwrap_or_default().iter().any(|a| d.node(*a).is_some_and(vectorcraft_tools::builder::is_live_paint)); + if parent.is_some_and(in_live_paint) || targets.iter().any(|t| d.parent_of(*t).is_some_and(in_live_paint)) { + return Err(bad(C, "Live Paint art can't be restacked here: use the Layers panel")); + } + // The source's container takes each target only as the Layers panel would (not a blend's inputs). + if let Some(n) = targets.iter().filter_map(|id| d.node(*id)).find(|n| !crate::cmd::layer::accepts(d, parent, n)) { + return Err(bad(C, format!("{} can't go beside the source object", n.display_name()))); + } if let Some(what) = targets.iter().filter_map(|id| d.node(*id)).find_map(|n| crate::cmd::intertwine::refused_in(d, parent, n)) { return Err(bad(C, format!("{what} can't be intertwined"))); } @@ -512,11 +533,26 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let ids: Vec = xfs.iter().map(|(id, _)| *id).collect(); let mut sc = scaling(s, &q); sc.patterns = transform_patterns(s, &q, &ids)?; + let measure = s.bounds_measure(); + let before = s.doc()?.doc.clone(); s.edit("Match Objects", |d, _| { for (id, xf) in &xfs { if let Some(n) = d.node_mut(*id) { transform_node(n, *xf, sc, true); } + // A live effect that moves the art in page space (a Transform effect's offset) does + // not turn with it: the measured reference point is put back where it was. + if let Some(at) = pinned.get(id) + && let Some(b) = effects::preview::oriented_bounds_with(d, &[*id], measure) + { + let now = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); + let off = *at - now; + if off.hypot() > 1e-9 + && let Some(n) = d.node_mut(*id) + { + transform_node(n, Affine::translate(off), sc, true); + } + } } if restack { let moved = d.remove_many(&targets)?; @@ -524,6 +560,24 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { // Targets moved out of an Intertwine group leave it as ordinary art. crate::cmd::intertwine::settle_members(d, &placed, &left)?; } + if !pinned.is_empty() { + crate::cmd::refresh_pixel_aligned(&before, d); + for (id, _) in &xfs { + let Some(at) = pinned.get(id) else { continue }; + let ob = effects::preview::oriented_bounds_with(d, &[*id], measure); + let kept = ob.is_some_and(|b| (*at - b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize)).hypot() <= 1e-6); + let misses = !kept + || ob.is_none_or(|b| match size { + "none" => false, + "width" => (b.rect.width() - w).abs() > 1e-6, + "height" => (b.rect.height() - h).abs() > 1e-6, + _ => (b.rect.width() - w).abs() > 1e-6 || (b.rect.height() - h).abs() > 1e-6, + }); + if misses { + return Err(bad(C, format!("object {} can't keep its size and reference point as it turns", id.0))); + } + } + } Ok(()) })?; Ok(count) diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 265ab50a6a..0231d39e5b 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -689,6 +689,170 @@ fn match_stacking_refuses_intertwine_nesting_beside_an_empty_group() { assert!(*s.doc().unwrap().doc == *before); } +#[test] +fn match_refuses_restacking_into_a_locked_container() { + for lock_ancestor in [false, true] { + let mut s = session(); + let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[source]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[group]); + let ancestor = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let locked = if lock_ancestor { ancestor } else { group }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(locked).unwrap().locked = true; + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"size": "both", "stacking": true})).unwrap_err(); + assert!(e.to_string().contains("the layer or group is locked"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + } +} + +#[test] +fn match_refuses_restacking_among_a_blends_inputs() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let target = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, target]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("can't go beside the source object"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn match_refuses_restacking_live_paint_art_but_moves_beside_a_whole_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let target = rect(&mut s, 250.0, 0.0, 20.0, 20.0); + assert_eq!(layer_order(&s), [g, between, target]); + let member = s.doc().unwrap().doc.children(Some(g)).unwrap()[0].id; + select(&mut s, &[member, target]); + s.execute("select.key", &json!({"id": member.0})).unwrap(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("Live Paint art"), "{e}"); + assert_eq!(steps(&s), n); + select(&mut s, &[g, target]); + s.execute("select.key", &json!({"id": g.0})).unwrap(); + let before = s.doc().unwrap().doc.node(g).unwrap().clone(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(layer_order(&s), [g, target, between]); + assert_eq!(s.doc().unwrap().doc.node(g).unwrap(), &before); +} + +#[test] +fn match_turns_art_with_a_moving_effect_about_its_measured_point() { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + s.execute("effect.apply", &json!({"ids": [b.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let center = |s: &Session| { + let bx = s.transform_box(&[b]).unwrap(); + bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4) + }; + let before = center(&s); + select(&mut s, &[a, b]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap(); + let after = center(&s); + assert!((after - before).hypot() < 1e-6, "{before:?} -> {after:?}"); +} + +#[test] +fn match_checks_a_pixel_aligned_symbols_measured_point_after_snapping() { + for size in ["none", "both"] { + for dx in [0.0, 0.25] { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0); + let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + select(&mut s, &[art]); + let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("object.move", &json!({"dx": dx})).unwrap(); + s.execute("effect.apply", &json!({"ids": [target.0], "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let center = |s: &Session| { + let b = s.transform_box(&[target]).unwrap(); + b.to_doc() * vectorcraft_geom::reference_point(b.rect, 4) + }; + let at = center(&s); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let result = s.execute("addon.arrange.match", &json!({"rotate": true, "size": size})); + if dx == 0.0 { + result.unwrap(); + assert!((center(&s) - at).hypot() < 1e-6, "{size}"); + let b = s.transform_box(&[target]).unwrap(); + assert!(b.angle.abs() < 1e-6, "{size}: {b:?}"); + if size == "both" { + let wanted = s.transform_box(&[source]).unwrap(); + assert!((b.rect.width() - wanted.rect.width()).abs() < 1e-6, "{size}: {b:?}"); + assert!((b.rect.height() - wanted.rect.height()).abs() < 1e-6, "{size}: {b:?}"); + } + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + } else { + let error = result.unwrap_err().to_string(); + assert!(error.contains("can't keep its size and reference point as it turns"), "{size}: {error}"); + } + assert_eq!(steps(&s), n, "{size}, dx={dx}"); + assert!(*s.doc().unwrap().doc == *before, "{size}, dx={dx}"); + } + } +} + +#[test] +fn match_turns_art_with_a_moving_fill_effect_about_its_measured_point() { + for grouped in [false, true] { + let mut s = session(); + s.prefs.use_preview_bounds = true; + let a = rect(&mut s, 0.0, 0.0, 20.0, 40.0); + select(&mut s, &[a]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + let b = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + s.execute("effect.apply", &json!({"ids": [b.0], "item": 0, "effect": "distort.transform", "params": {"moveH": 30}})).unwrap(); + let b = if grouped { + select(&mut s, &[b]); + NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) + } else { + b + }; + let center = |s: &Session| { + let bx = s.transform_box(&[b]).unwrap(); + bx.to_doc() * vectorcraft_geom::reference_point(bx.rect, 4) + }; + let before = center(&s); + select(&mut s, &[a, b]); + s.execute("select.key", &json!({"id": a.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap(); + let after = center(&s); + assert!((after - before).hypot() < 1e-6, "grouped={grouped}: {before:?} -> {after:?}"); + let d = &s.doc().unwrap().doc; + assert!((d.bbox_angle(&[b]) - d.bbox_angle(&[a])).abs() < 1e-6); + } +} + #[test] fn match_replays_with_the_stroke_scaling_it_ran_with() { replays_the_stroke_scaling_it_ran_with("addon.arrange.match", json!({"size": "both"})); diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..6e4d9e0907 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17581,7 +17581,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. A `stacking` match is also refused when the source's layer or group is locked, when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 395fdda4de..9d0a40193c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3148,7 +3148,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` ## Arrange Tools add-on: Match Objects (2026-11-29) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (a clipping path keeps its place, so such a match is refused). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (a clipping path keeps its place, so such a match is refused, as is one into a locked layer or group, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) From bdb753eef968a24beb8b44cb2450e61d8a52f517 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 21:40:40 -0800 Subject: [PATCH 014/106] Scripts: a color picker answer refuses out-of-range color keys A headless colorPicker answer written as a color key, such as "rgb 300 0 0" or "rgb 255.000001 0 0", was clamped into range and accepted, while the same color as an array or object was refused. The key's components are now checked as written, in f64, before the key is read. The near-white gray note in docs/mcp.md and colors.rs now says which paint keeps its color when the read-back gray is assigned. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 27 ++++++++++++++++++++++- crates/engine/src/script/dom/colors.rs | 7 +++--- crates/engine/src/tests/script_dialogs.rs | 15 ++++++++++++- docs/mcp.md | 5 +++-- docs/target-app-parity.md | 2 +- 6 files changed, 49 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b2812cb8c2..b3cc43bed3 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 04fb0b49f7..5daae5bb1d 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -168,6 +168,31 @@ fn in_range(c: &Color) -> bool { } } +/// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key +/// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components +/// into their ranges. +fn answer_color(v: &Value) -> Option { + if let Value::String(s) = v + && Color::from_hex(s).is_none() + { + let mut it = s.split_whitespace(); + let model = it.next()?.to_ascii_lowercase(); + // Parsed as f64, so that a value just past a limit is not rounded onto it. + let n: Vec = it.map(|t| t.parse::().ok().filter(|x| x.is_finite())).collect::>()?; + let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x)); + let written_in_range = match (model.as_str(), n.as_slice()) { + ("rgb", [_, _, _]) => within(&n, 0.0, 255.0), + ("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0), + ("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0), + _ => return None, + }; + if !written_in_range { + return None; + } + } + crate::cmd::color_value(v).filter(in_range) +} + /// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together /// is a line break; every other control character, and with `lines` false every line break too, /// shows as its Unicode Control Picture, as the Script Console shows it. @@ -242,7 +267,7 @@ fn known_answer(o: &Map) -> Result { (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), (Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)), - (Some("colorPicker"), v) => match crate::cmd::color_value(v).filter(in_range) { + (Some("colorPicker"), v) => match answer_color(v) { Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))), None => Err("is a color picker's answer, whose `value` must be a color or null"), }, diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 8f04ed384c..00bcdfa6f6 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -13,9 +13,10 @@ //! VectorCraft's own rules, which the help pages do not state: components left out count as 0; //! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` //! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page -//! says. A color read from an object gives that object the same color when it is assigned back, -//! except a gray within about 1e-14 % of white: one number cannot hold it, so it reads as 100 and -//! assigning it back makes the gray white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not +//! says. A color read from an object gives that object the same color when it is assigned back. +//! A gray within about 1e-14 % of white reads as 100, since one number cannot hold it; assigning it +//! to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it to +//! any other paint gives white. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not //! assigned yet. use std::rc::Rc; diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index af1d07f06a..dbd727e33c 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -372,10 +372,23 @@ fn the_color_picker_refuses_what_is_not_a_solid_color() { let r = headless(&mut s, source, json!([])).unwrap(); assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}"); assert_eq!(r["dialogCount"], 0, "no picker opened"); - for bad in [json!("not a color"), json!([255, 0, 0]), json!({"model": "lab", "l": 120, "a": 0, "b": 0}), json!(true)] { + for bad in [ + json!("not a color"), + json!([255, 0, 0]), + json!({"model": "lab", "l": 120, "a": 0, "b": 0}), + json!(true), + json!("rgb 300 0 0"), + json!("cmyk 0 0 0 101"), + json!("gray -1"), + json!("lab 50 200 0"), + json!("rgb 255.000001 0 0"), + ] { let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); assert!(e.contains("color picker's answer"), "{bad}: {e}"); } + for good in [json!("rgb 255 0 0"), json!("cmyk 0 100 100 0"), json!("gray 100"), json!("lab 50 -128 128")] { + assert!(headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": good})])).is_ok(), "{good}"); + } } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index c2ceaff161..dd885ea436 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3136,7 +3136,8 @@ through `$`: `selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it; a gray within about 1e-14 % of white reads as - 100, so assigning it back makes it white), `new LabColor()` and `new NoColor()` + 100; assigning it to a fill or stroke whose gray also reads as 100 leaves that paint as it is, and assigning it + to any other paint gives white), `new LabColor()` and `new NoColor()` (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. @@ -3726,7 +3727,7 @@ given, whatever Only Web Colors was left at in another picker. OK with the color script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: "colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its -range, or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and +range (a color key such as `"rgb 300 0 0"` is refused, not clamped), or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and `ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. ```sh diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 17c88f6361..ab023f4b05 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1129,7 +1129,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. From d141f166d5fbb74e176a5ad09606e97b8a8efff6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 22:23:04 -0800 Subject: [PATCH 015/106] Match Objects: docs say the stacking refusals apply only when a restack is needed Targets already directly above the source keep their places, and the clipping-path, locked, blend and Live Paint checks do not run for them. The parity doc line, docs/mcp.md and the command's params text now say so. --- crates/engine/src/cmd/addons/arrange.rs | 2 +- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 43397e9421..5c2415ae9e 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match that would move a clipping path, restack into a locked layer or group, put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into a locked layer or group, put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), diff --git a/docs/mcp.md b/docs/mcp.md index 6e4d9e0907..e47310c1b5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17581,7 +17581,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. A `stacking` match is also refused when the source's layer or group is locked, when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. When the others are already directly above the source, a `stacking` match leaves their places as they are; otherwise it is also refused when the source's layer or group is locked, when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9d0a40193c..315a8a998d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3148,7 +3148,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` ## Arrange Tools add-on: Match Objects (2026-11-29) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (a clipping path keeps its place, so such a match is refused, as is one into a locked layer or group, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (targets already there keep their places; otherwise a clipping path keeps its place, so a match that would move one is refused, as is one that would move a target into a locked layer or group, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) From ea0768443aa83001cb64a085a0c060a8cc0db55c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:26:49 -0800 Subject: [PATCH 016/106] New Document: the rows test follows main's rounding of rows Cause of the CI failure on 6308fefe2e: main's 6ef6df34072 made file.new round artboardLayout.rows and refuse only a value that rounds outside 1 to 1000, and the New Document dialog reads rows through the same parser. This branch's the_dialog_reads_rows_as_file_new_does still expected 3.5 to be refused, so set() returned Ok and unwrap_err panicked. The test now sets 3.6, expects 4, and checks that 0.4, 0 and 1001 are refused with the rows left as they were. --- crates/ui-egui/src/dialogs/new_document.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 22842c599b..e90bf7e09e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1047,16 +1047,16 @@ 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. + /// The dialog reads rows as `file.new` does: rounded to a whole number from 1 to the artboard + /// limit, and a count that rounds to 0 or is larger 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(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6})).unwrap(); assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); - for rows in [json!(3.5), json!(MAX_ARTBOARDS + 1), json!(0)] { + for rows in [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}"); From ff90087a6b55907c08458bbf8c5cc3b3b8b78280 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:50:54 -0800 Subject: [PATCH 017/106] Match Objects: docs list the pixel-snapping refusal With Use Preview Bounds, Match Objects refuses a match when pixel snapping would move the reference point of a turned object that carries a geometry or 3D effect, or change a dimension it was asked to match. The parity doc line, docs/mcp.md and the command's params text now say so. --- crates/engine/src/cmd/addons/arrange.rs | 2 +- docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 5c2415ae9e..98b4b253a3 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into a locked layer or group, put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into a locked layer or group, put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), diff --git a/docs/mcp.md b/docs/mcp.md index e47310c1b5..332a428537 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17581,7 +17581,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. When the others are already directly above the source, a `stacking` match leaves their places as they are; otherwise it is also refused when the source's layer or group is locked, when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. When the others are already directly above the source, a `stacking` match leaves their places as they are; otherwise it is also refused when the source's layer or group is locked, when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. With Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 315a8a998d..0d41b73abf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3148,7 +3148,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` ## Arrange Tools add-on: Match Objects (2026-11-29) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (targets already there keep their places; otherwise a clipping path keeps its place, so a match that would move one is refused, as is one that would move a target into a locked layer or group, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place, and strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (targets already there keep their places; otherwise a clipping path keeps its place, so a match that would move one is refused, as is one that would move a target into a locked layer or group, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place; with Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. Strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) From 99cf25f90c4c26ad6d79472165fef6de63964933 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:33:39 -0800 Subject: [PATCH 018/106] Scripts: closing a Color Picker ends only the screen sample it started Stopping or quitting the run that waits at app.showColorPicker, and closing any Color Picker, now ends a screen color sample that picker started and drops a sampled color it has not taken yet. A sample started for the fill, the stroke or another picker keeps running. The test that the script's picker shows no preview now has a selected object and checks that no preview edit begins, so it fails when the picker's Target::Script exclusion is removed. --- crates/ui-egui/src/dialogs/color_picker.rs | 5 +++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/screen_color.rs | 32 ++++++++++++++++++++++ crates/ui-egui/src/screen_color/tests.rs | 29 ++++++++++++++++++++ crates/ui-egui/src/tests/script_dialogs.rs | 28 +++++++++++++++++++ docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 7 files changed, 98 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 9b64bd2dd6..7cb567b731 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -263,10 +263,12 @@ pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script { .. })).map(|o| o.id) } -/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. +/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. A +/// screen pick the picker started ends with it; a pick another owner started keeps running. pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(id) = script_picker(app) else { return }; app.color_dialogs.pickers.retain(|o| o.id != id); + screen_color::cancel_for(app, ctx, owner(id)); if let Some(dialogs) = app.dialogs() { dialogs.with(|h| { h.cancel_by_id(ctx, id); @@ -316,6 +318,7 @@ fn settle(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &craft::ui::sh }) }); let Some((current, gesture)) = live else { + screen_color::cancel_for(app, ctx, owner(open.id)); let result = dialogs.with(|h| h.take_by_id::(open.id)); finish(app, dialogs, open, result); return false; diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f5e6908a8a..f08a6a35d3 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1121,7 +1121,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.sampleScreenColor", "Sample Color from Screen", "", - "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", + "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", ), ( "ui.newBrush", diff --git a/crates/ui-egui/src/screen_color.rs b/crates/ui-egui/src/screen_color.rs index c644b9b7a2..d7495adb83 100644 --- a/crates/ui-egui/src/screen_color.rs +++ b/crates/ui-egui/src/screen_color.rs @@ -41,6 +41,33 @@ fn remember_doc(app: &VectorcraftApp, ctx: &egui::Context) { ctx.data_mut(|d| d.insert_temp(doc_key(), uid)); } +/// Where the owner of the running pick is kept, as a hash of its key. +fn owner_key() -> egui::Id { + egui::Id::unique("screen-color-owner") +} + +fn owner_hash(owner: impl Hash) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + owner.hash(&mut hasher); + hasher.finish() +} + +fn remember_owner(ctx: &egui::Context, owner: impl Hash) { + let key = owner_hash(owner); + ctx.data_mut(|d| d.insert_temp(owner_key(), key)); +} + +/// Ends the running pick when `owner` started it, and drops a color `owner` has not taken yet; a +/// pick another owner started keeps running. The next pass finishes a capture the cancel ends. +pub(crate) fn cancel_for(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash) { + let started_by = ctx.data(|d| d.get_temp::(owner_key())); + if app.screen_pick.busy() && started_by == Some(owner_hash(&owner)) { + app.screen_pick.cancel(); + ctx.request_repaint(); + } + let _ = app.screen_pick.take(owner); +} + /// The platform can capture the screen: the shell's capabilities say so and no capture has said it /// cannot. Without a window there is nothing to capture. pub fn available(app: &VectorcraftApp) -> bool { @@ -65,6 +92,10 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result { } if let Some(ctx) = app.ui_ctx.clone() { remember_doc(app, &ctx); + match picker { + Some(id) => remember_owner(&ctx, crate::dialogs::color_picker::owner(id)), + None => remember_owner(&ctx, if stroke { STROKE } else { FILL }), + } } match picker { Some(id) => app.screen_pick.start(crate::dialogs::color_picker::owner(id)), @@ -78,6 +109,7 @@ pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result { pub(crate) fn hold(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash, gesture: ScreenPickGesture) -> Option { if !app.screen_pick.busy() { remember_doc(app, ctx); + remember_owner(ctx, &owner); } app.screen_pick.hold(ctx, owner, gesture) } diff --git a/crates/ui-egui/src/screen_color/tests.rs b/crates/ui-egui/src/screen_color/tests.rs index f36e669422..414a1a41c0 100644 --- a/crates/ui-egui/src/screen_color/tests.rs +++ b/crates/ui-egui/src/screen_color/tests.rs @@ -89,6 +89,35 @@ fn the_color_pickers_eyedropper_samples_into_it() { assert_eq!(paints(&app).0, "#123456"); } +/// Closing the Color Picker ends the sample its eyedropper started. +#[test] +fn closing_the_color_picker_ends_its_sample() { + let (mut app, ctx) = app(); + app.run("ui.colorPicker", json!({})).unwrap(); + let id = app.color_dialogs.pickers.last().unwrap().id; + assert_eq!(hold(&mut app, &ctx, crate::dialogs::color_picker::owner(id), ScreenPickGesture::Clicked), None); + assert!(app.screen_pick.busy()); + assert!(app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id))); + let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::color_picker::pump(&mut app, ui.ctx())); + out.textures_delta.clear(); + assert!(app.color_dialogs.pickers.is_empty()); + assert!(!app.screen_pick.busy(), "the sample ends with the picker"); +} + +/// Ending a picker's pick drops the color it sampled and has not taken yet; another owner's color +/// stays. +#[test] +fn ending_a_pick_drops_the_color_its_owner_has_not_taken() { + let (mut app, ctx) = app(); + for own in [true, false] { + assert_eq!(hold(&mut app, &ctx, "picker", ScreenPickGesture::Clicked), None); + finish(&mut app, &ctx, Ok(srgba("#123456"))); + assert!(!app.screen_pick.busy(), "the capture finished"); + cancel_for(&mut app, &ctx, if own { "picker" } else { "other" }); + assert_eq!(take(&mut app, &ctx, "picker").is_some(), !own, "own {own}"); + } +} + /// A canceled capture changes nothing; a failed one reaches the status line. #[test] fn cancel_and_errors_leave_the_art_alone() { diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 5dfa72ff39..832a96e875 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -352,6 +352,8 @@ fn answer_picker(app: &mut VectorcraftApp, ok: bool) { #[test] fn the_color_picker_waits_and_answers_the_run() { let mut app = app(); + // A selected object, which a picker that previews would paint. + app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 10, "height": 10})).unwrap(); let gray = "var g = new GrayColor(); g.gray = 40;"; start( &mut app, @@ -364,7 +366,10 @@ fn the_color_picker_waits_and_answers_the_run() { assert!(!is_open::(&app), "the picker opens in place of a notice"); set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); let ctx = app.ui_ctx.clone().unwrap(); + app.ui.status.clear(); color_picker::pump(&mut app, &ctx); + // A preview would begin an edit, which the running script refuses with a status message. + assert_eq!(app.ui.status, "", "the picker starts no preview"); assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview"); answer_picker(&mut app, true); assert!(until_picker(&mut app), "the next call opens the picker again"); @@ -421,6 +426,29 @@ fn stopping_or_quitting_the_run_closes_its_color_picker() { assert_eq!(objects(&app), 0); } +#[test] +fn stopping_the_run_ends_only_the_screen_pick_its_color_picker_started() { + use craft::color_ui::ui::ScreenPickGesture; + let source = "var c = new RGBColor(); app.showColorPicker(c);"; + for own in [true, false] { + let mut app = app(); + start(&mut app, source); + assert!(until_picker(&mut app)); + let ctx = app.ui_ctx.clone().unwrap(); + let id = color_picker::script_picker(&app).unwrap(); + let started = if own { + crate::screen_color::hold(&mut app, &ctx, color_picker::owner(id), ScreenPickGesture::Clicked) + } else { + crate::screen_color::hold(&mut app, &ctx, "fill", ScreenPickGesture::Clicked) + }; + assert_eq!(started, None); + assert!(app.screen_pick.busy()); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert_eq!(app.screen_pick.busy(), !own, "own pick {own}: only the picker's own pick ends with it"); + } +} + #[test] fn the_color_picker_opens_on_the_scripts_color_with_only_web_colors_left_on() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index dd885ea436..d14c51a78b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3725,7 +3725,9 @@ run's active document (a document the script made included) is in CMYK, an RGB p color's `typename` can differ from the picker's model and from the color given. The picker opens on the color as given, whatever Only Web Colors was left at in another picker. OK with the color unchanged and Cancel return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting -end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: +end the run as they do at the other dialogs, and close the picker. They also end a screen color sample +(`ui.sampleScreenColor` with `picker`, or the picker's eyedropper) that the picker started, and drop a sampled color +it has not taken; a sample started for the fill, the stroke or another picker keeps running. A run with nobody to ask takes `{kind: "colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its range (a color key such as `"rgb 300 0 0"` is refused, not clamped), or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and `ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ab023f4b05..9986490a00 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1129,7 +1129,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, an RGB pick as CMYK when the run's active document is in CMYK, while Cancel and OK with the color unchanged return a new object of the color given, in its own model. Stopping the run closes the picker and ends a screen color sample the picker started. A run with nobody to ask takes the pick from `answers`, refusing a color with a component out of its range (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. From e49b11ff4bd138bf3c0610a48dd777aae4bf22cb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 04:27:31 -0800 Subject: [PATCH 019/106] Match Objects: check the reference point of turned pixel-aligned art after snapping A turned target that is pixel-aligned, holds pixel-aligned art or holds an instance of a pixel-aligned symbol is snapped to the pixel grid after the match, which could move its reference point while the command succeeded. Its reference point and matched dimensions are now checked after the snap, with or without Use Preview Bounds, and the match is refused when either moved. Only targets with a geometry effect are still moved back to their measured point, so aligned art is not pushed off the grid. The params text, docs/mcp.md and docs/target-app-parity.md state the refusal. --- crates/engine/src/cmd/addons/arrange.rs | 29 ++++--- crates/engine/src/cmd/addons/arrange/tests.rs | 82 +++++++++++++++++++ crates/engine/src/cmd/object.rs | 4 +- crates/engine/src/cmd/object/pixelgrid.rs | 12 +++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 6 files changed, 117 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 98b4b253a3..6ca758ab1f 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -27,7 +27,7 @@ use super::super::colorcmds::edit_if_changed; use super::super::edit::selected_roots; use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; -use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; +use super::super::object::{aligned_symbols, choice, object_bounds_transform, scaling, snaps_after_edit, transform_node, transform_patterns}; use super::super::typecmd::refresh_bounds_of; use super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_multi, has_selection, number_or, switch_or}; use crate::{EngineError, Result, Session}; @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into a locked layer or group, put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into a locked layer or group, put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match, as it is for a turned target that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol, with or without Use Preview Bounds; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -438,6 +438,9 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { let mut xfs = Vec::with_capacity(targets.len()); // Where each turned target's reference point is before the match; it stays there. let mut pinned: HashMap = HashMap::new(); + // The turned targets whose reference point is checked after pixel snapping. + let mut checked: HashMap = HashMap::new(); + let symbols = if rotate { aligned_symbols(&s.doc()?.doc) } else { HashMap::new() }; for &id in &targets { let turn = if rotate { vectorcraft_geom::normalize_deg(angle - s.doc()?.doc.bbox_angle(&[id])) } else { 0.0 }; let Some(b) = s.transform_box(&[id]) else { @@ -460,12 +463,16 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { // Rotation uses the reference point that sizing keeps in place. let at = b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize); xf = Affine::rotate_about(-turn.to_radians(), at) * xf; - if s.bounds_measure().preview && { - let d = &s.doc()?.doc; - d.node(id).is_some_and(|n| effects::preview::draws_geometry(&d.symbol_boxes(), n)) - } { + let preview = s.bounds_measure().preview; + let d = &s.doc()?.doc; + if preview && d.node(id).is_some_and(|n| effects::preview::draws_geometry(&d.symbol_boxes(), n)) { pinned.insert(id, at); } + // Pixel snapping after the turn can move a pixel-aligned target: its point is checked + // too, but not put back, since that would move its aligned art off the grid. + if pinned.contains_key(&id) || d.node(id).is_some_and(|n| snaps_after_edit(n, &symbols)) { + checked.insert(id, at); + } } if wanted.is_some() { let sc = scaling(s, &json!({ "strokes": strokes })); @@ -560,11 +567,13 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { // Targets moved out of an Intertwine group leave it as ordinary art. crate::cmd::intertwine::settle_members(d, &placed, &left)?; } - if !pinned.is_empty() { - crate::cmd::refresh_pixel_aligned(&before, d); + if !checked.is_empty() { + // Measured on a snapped copy: the edit itself snaps once, after Global Edit. + let mut snapped = d.clone(); + crate::cmd::refresh_pixel_aligned(&before, &mut snapped); for (id, _) in &xfs { - let Some(at) = pinned.get(id) else { continue }; - let ob = effects::preview::oriented_bounds_with(d, &[*id], measure); + let Some(at) = checked.get(id) else { continue }; + let ob = effects::preview::oriented_bounds_with(&snapped, &[*id], measure); let kept = ob.is_some_and(|b| (*at - b.to_doc() * vectorcraft_geom::reference_point(b.rect, reference as usize)).hypot() <= 1e-6); let misses = !kept || ob.is_none_or(|b| match size { diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 0231d39e5b..eedc772e28 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -451,6 +451,67 @@ fn match_size_and_rotation_measure_pixel_aligned_art_in_its_final_frame() { } } +#[test] +fn match_rotation_refuses_when_pixel_snapping_would_move_the_reference_point() { + for wrap in ["path", "group", "compound"] { + let mut s = session(); + let target = rect(&mut s, 0.0, 0.0, 10.0, 11.0); + if wrap != "compound" { + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + } + let target = match wrap { + "group" => NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()), + "compound" => NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()), + _ => target, + }; + select(&mut s, &[target]); + if wrap == "compound" { + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + } + let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0); + select(&mut s, &[source]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + // Turned a quarter about its center (5, 5.5), the 10 x 11 path's edges land on half points, + // and snapping them back to the grid would move that center. + let e = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string(); + assert!(e.contains("reference point"), "{wrap}: {e}"); + assert_eq!(steps(&s), n, "{wrap}: no undo step"); + assert!(*s.doc().unwrap().doc == *before, "{wrap}"); + } +} + +#[test] +fn match_rotation_keeps_a_mixed_group_in_one_piece_or_refuses() { + let mut s = session(); + let aligned = rect(&mut s, 0.0, 0.0, 10.0, 11.0); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + let loose = rect(&mut s, 20.0, 0.0, 10.0, 11.0); + select(&mut s, &[aligned, loose]); + let target = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let source = rect(&mut s, 100.0, 0.0, 10.0, 10.0); + select(&mut s, &[source]); + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + select(&mut s, &[target, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let gap = |s: &Session| { + let (a, b) = (s.transform_box(&[aligned]).unwrap().center(), s.transform_box(&[loose]).unwrap().center()); + b - a + }; + let before = s.doc().unwrap().doc.clone(); + match s.execute("addon.arrange.match", &json!({"rotate": true})) { + // Turned a quarter, the members' centers keep their distance and only change direction. + Ok(_) => assert!((gap(&s).hypot() - 20.0).abs() < 1e-6, "the members moved apart: {:?}", gap(&s)), + Err(e) => { + assert!(e.to_string().contains("reference point"), "{e}"); + assert!(*s.doc().unwrap().doc == *before); + } + } +} + #[test] fn match_rotation_refuses_a_target_without_bounds_when_its_angle_differs() { for angle in [0, 30] { @@ -822,6 +883,27 @@ fn match_checks_a_pixel_aligned_symbols_measured_point_after_snapping() { } } +#[test] +fn match_refuses_when_snapping_moves_a_pixel_aligned_symbol_instance_without_preview_bounds() { + let mut s = session(); + s.prefs.use_preview_bounds = false; + let source = rect(&mut s, 0.0, 0.0, 40.0, 20.0); + let art = rect(&mut s, 100.0, 100.0, 40.0, 20.0); + select(&mut s, &[art]); + let target = NodeId(s.execute("symbol.new", &json!({"name": "Aligned", "alignToPixelGrid": true})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.rotate", &json!({"angle": 30})).unwrap(); + s.execute("object.move", &json!({"dx": 0.25})).unwrap(); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + // Turned back to its natural angle, the instance snaps to whole points, which moves its center. + let error = s.execute("addon.arrange.match", &json!({"rotate": true})).unwrap_err().to_string(); + assert!(error.contains("can't keep its size and reference point as it turns"), "{error}"); + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); +} + #[test] fn match_turns_art_with_a_moving_fill_effect_about_its_measured_point() { for grouped in [false, true] { diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index b2d857a464..80eebac762 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -37,8 +37,8 @@ pub(crate) use bounds::{bounds_rewrite, object_bounds_transform}; pub use commands::specs; pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip}; pub(crate) use pixelgrid::{ - align_new_object, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, - snap_if_aligned, snap_symbol_art, + align_new_object, aligned_symbols, can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, + resnap, snap_if_aligned, snap_symbol_art, snaps_after_edit, }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; diff --git a/crates/engine/src/cmd/object/pixelgrid.rs b/crates/engine/src/cmd/object/pixelgrid.rs index 7bef1cbc69..2eab76bf2b 100644 --- a/crates/engine/src/cmd/object/pixelgrid.rs +++ b/crates/engine/src/cmd/object/pixelgrid.rs @@ -449,6 +449,18 @@ pub(crate) fn snap_if_aligned(n: &mut Node) { } } +/// Whether the pixel-grid snap after an edit ([`refresh`]) can move object `n`: `n` holds +/// pixel-aligned art ([`holds_aligned`]) or an instance of a symbol in `symbols`, the document's +/// pixel-aligned symbols ([`aligned_symbols`]). +pub(crate) fn snaps_after_edit(n: &Node, symbols: &HashMap) -> bool { + holds_aligned(n) || !symbols.is_empty() && holds_instance(n, symbols) +} + +/// The pixel-aligned symbols of `d`, keyed by name, for [`snaps_after_edit`]. +pub(crate) fn aligned_symbols(d: &Document) -> HashMap { + d.pixel_aligned_symbols().into_iter().map(|name| (name, Affine::IDENTITY)).collect() +} + /// Whether `n` or an object in it, or in the art of a linked opacity mask in it, is pixel-aligned. /// It goes only where a transform of `n` goes: not into unlinked masks. fn holds_aligned(n: &Node) -> bool { diff --git a/docs/mcp.md b/docs/mcp.md index 332a428537..c4f27652f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17581,7 +17581,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. When the others are already directly above the source, a `stacking` match leaves their places as they are; otherwise it is also refused when the source's layer or group is locked, when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. With Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. When the others are already directly above the source, a `stacking` match leaves their places as they are; otherwise it is also refused when the source's layer or group is locked, when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. With Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. The same refusal applies, with or without Use Preview Bounds, to a turned object that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0d41b73abf..ee1c69ce88 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3148,7 +3148,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` ## Arrange Tools add-on: Match Objects (2026-11-29) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (targets already there keep their places; otherwise a clipping path keeps its place, so a match that would move one is refused, as is one that would move a target into a locked layer or group, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place; with Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. Strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (targets already there keep their places; otherwise a clipping path keeps its place, so a match that would move one is refused, as is one that would move a target into a locked layer or group, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place; with Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. The same refusal applies, with or without Use Preview Bounds, to a turned object that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol. Strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) From 344545f623d65784937cb9cf40ae6f79e4433554 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:27:51 -0800 Subject: [PATCH 020/106] MCP: regenerate ui_catalog for the showColorPicker description The merge of main left crates/mcp/src/ui_catalog.rs without the sentence the branch added to the screen sampler's description in crates/ui-egui/src/menus/ui_commands.rs, so the gate's ui-commands step failed. The file is regenerated with cargo xtask ui-commands. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 9730bd7853..efd3c19495 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1120,7 +1120,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.sampleScreenColor", "Sample Color from Screen", "", - "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", + "{} or {stroke?: bool (default: the active proxy), picker?: bool (the open Color Picker instead)} show the system's color sampler (macOS; Linux through the XDG desktop portal's PickColor; Windows, a still copy of every monitor under a crosshair; browsers with an EyeDropper) and answer at once; the color the person picks anywhere on the screen then runs paint.setFill / paint.setStroke (one undo step) or becomes the Color Picker's color (field `color`), converted from display sRGB into the working RGB space; a cancel (Escape on macOS, Windows and in browsers; also a click of another mouse button or switching to another window on Windows) leaves the colors as they were. Closing the Color Picker a `picker` sample is for, or stopping the script that opened it, ends the sample. ui.inspect reports `screenSampler: true` until it answers; on Windows, a screen that can't be copied ends the wait with a status message; on Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way end the wait with a status message. An error without a sampler, while one is open, or with `picker` and no Color Picker open", ), ( "ui.newBrush", From 8ef6d0de4169c3e98eb30180c7499fd3d530dcb1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:25:35 -0800 Subject: [PATCH 021/106] Match Objects: keep targets in locked containers and blend inputs in place A stacking match checked only the source's container for a lock and only the destination for what it may hold. A target in a locked layer or group was taken out of it, and a blend's input object (or art inside one) was taken out of the blend and placed beside the source. The match is now refused, with no change to the document, when a target's own layer or group is locked or when a target would leave the blend input it is in. Selecting the whole blend still restacks it. --- crates/engine/src/cmd/addons/arrange.rs | 19 ++++++-- crates/engine/src/cmd/addons/arrange/tests.rs | 43 +++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 61 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 6ca758ab1f..07dd758c35 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{Node, NodeId, OrientedBox}; +use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use vectorcraft_render::effects; @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "Match Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into a locked layer or group, put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match, as it is for a turned target that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol, with or without Use Preview Bounds; to match places, use object.align {to: \"key\"} → {source, count}", + "{source?: \"key\" (the key object, select.key) | \"top\" (the frontmost selected object) | \"bottom\" (the backmost) (default: the key object when the selection has one, else \"top\"), size?: \"none\" | \"width\" (each target takes the source's width, its height following in proportion) | \"height\" (the source's height, the width following in proportion) | \"both\" (the source's width and height, each on its own) (\"none\"), rotate?: false (true: each target takes the source's bounding-box angle, measured counter-clockwise, turning the shorter way, at most 180°), stacking?: false (true: the targets go directly above the source in the stacking order, in its layer or group, in the order they had), reference?: 0..8 (the 9-point grid row by row from the top-left; 4, the center: the point of each target that stays put as it is sized and turned), scaleStrokes?: the Scale Strokes & Effects preference, patterns?: the Transform Pattern Tiles preference (at least one of size, rotate and stacking)} make the other selected objects (the top-level ones, at most 20000) match the source, which stays as it is, as one undo step (none when nothing changes). Sizes are measured and set as object.setBounds measures them (Use Preview Bounds), each in the object's own bounding-box frame, and a size that a target has no width or height to take is refused, as is a stacking match whose targets are not already directly above the source and that would move a clipping path, restack into or out of a locked layer or group, take a target out of the blend input it is in (to restack the blend itself, select the whole blend), put a target where the Layers panel can't (a blend's inputs, for one) or move Live Paint art; a turned target with a live effect that moves it keeps its measured reference point in place, and with Use Preview Bounds, for a target the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or inside it, or a visible geometry or 3D effect in a placed symbol's art, the match is refused when pixel snapping would move that target's reference point or change a dimension it was asked to match, as it is for a turned target that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol, with or without Use Preview Bounds; to match places, use object.align {to: \"key\"} → {source, count}", has_multi, match_objects ), @@ -513,9 +513,22 @@ fn match_objects(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "a clipping path can't change its place in the stacking order")); } let parent = d.parent_of(source); - if parent.is_some_and(|p| crate::cmd::layer::locked_within(d, p)) { + // Each target leaves its own container, so a target's locked container refuses too. + let locked = |p: Option| p.is_some_and(|p| crate::cmd::layer::locked_within(d, p)); + if locked(parent) || targets.iter().any(|t| locked(d.parent_of(*t))) { return Err(bad(C, "the layer or group is locked")); } + // A blend's input objects, and art inside them, stay in the blend: the whole blend can still be + // restacked, and art can still move within the blend's input it is in. + let is_blend = |a: &NodeId| d.node(*a).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. })); + let destination = parent.and_then(|p| d.ancestry(p)).unwrap_or_default(); + let leaves_blend = |t: &NodeId| { + let chain = d.ancestry(*t).unwrap_or_default(); + chain.windows(2).filter(|w| is_blend(&w[0])).any(|w| !destination.windows(2).any(|v| v == w)) + }; + if targets.iter().any(leaves_blend) { + return Err(bad(C, "a blend's input objects can't leave their blend input: to restack the blend, select the whole blend")); + } // Live Paint art is rebuilt from its paths when they move: Match Objects leaves it in place. let in_live_paint = |id: NodeId| d.ancestry(id).unwrap_or_default().iter().any(|a| d.node(*a).is_some_and(vectorcraft_tools::builder::is_live_paint)); diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index eedc772e28..e33dca907c 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -791,6 +791,49 @@ fn match_refuses_restacking_among_a_blends_inputs() { assert_eq!(s.doc().unwrap().doc.layers, before.layers); } +#[test] +fn match_refuses_taking_a_target_out_of_a_locked_container() { + let mut s = session(); + let target = rect(&mut s, 100.0, 0.0, 40.0, 40.0); + select(&mut s, &[target]); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let source = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[source, target]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(group).unwrap().locked = true; + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("the layer or group is locked"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn match_refuses_taking_a_target_out_of_a_blend_but_restacks_the_whole_blend() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let blend = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let between = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let source = rect(&mut s, 250.0, 0.0, 20.0, 20.0); + assert_eq!(layer_order(&s), [blend, between, source]); + select(&mut s, &[a, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let e = s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap_err(); + assert!(e.to_string().contains("a blend's input objects"), "{e}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); + select(&mut s, &[blend, source]); + s.execute("select.key", &json!({"id": source.0})).unwrap(); + s.execute("addon.arrange.match", &json!({"stacking": true})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(layer_order(&s), [between, source, blend]); +} + #[test] fn match_refuses_restacking_live_paint_art_but_moves_beside_a_whole_group() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index c4f27652f5..58a861430b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17581,7 +17581,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.swap` | `size` (false); `scaleStrokes` (the Scale Strokes & Effects preference) | Swaps the bounds centres of exactly two selected objects (off otherwise); with `size`, each also takes the other's width and height. | | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | -| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. When the others are already directly above the source, a `stacking` match leaves their places as they are; otherwise it is also refused when the source's layer or group is locked, when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. With Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. The same refusal applies, with or without Use Preview Bounds, to a turned object that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol. To match places, use `object.align {to: "key"}`. → `{source, count}` | +| `addon.arrange.match` | `source`: `key` (the key object, `select.key`), `top` (the frontmost selected object), `bottom` (the backmost) (the key object when the selection has one, else `top`); `size`: `none`, `width` (the height follows in proportion), `height` (the width follows in proportion), `both` (`none`); `rotate` (false); `stacking` (false); `reference` 0…8 (4, the center); `scaleStrokes`; `patterns` (the Transform Pattern Tiles preference); at least one of `size`, `rotate` and `stacking` | Makes the other selected objects (at most 20000) match the source, which stays as it is. `size` gives each one the source's width, height or both, measured in each object's own bounding-box frame; `rotate` turns each one to the source's bounding-box angle; both keep each object's reference point in place. `stacking` puts the others directly above the source, in its layer or group, in the order they had. `source: "key"` without a key object, and a `size` that takes a width or a height the source or a target does not have, and a `stacking` match that would move a clipping path, are refused. When the others are already directly above the source, a `stacking` match leaves their places as they are; otherwise it is also refused when the source's layer or group or a target's own layer or group is locked, when it would take a target out of the blend input it is in (a blend's input objects and the art inside each one stay in that input; to restack the blend itself, select the whole blend), when it would put a target where the Layers panel does not allow it (among a blend's inputs, for example), or when it would move art into, out of or within a Live Paint group. A turned object with a live effect that moves it keeps its measured reference point in place. With Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. The same refusal applies, with or without Use Preview Bounds, to a turned object that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol. To match places, use `object.align {to: "key"}`. → `{source, count}` | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ee1c69ce88..d9bbcfab52 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3148,7 +3148,7 @@ dialogs, Preview and Cancel, Zoom to Selection) and `command_sweep`. Commands: ` ## Arrange Tools add-on: Match Objects (2026-11-29) -A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (targets already there keep their places; otherwise a clipping path keeps its place, so a match that would move one is refused, as is one that would move a target into a locked layer or group, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place; with Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. The same refusal applies, with or without Use Preview Bounds, to a turned object that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol. Strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Arrange Tools › Match Objects… makes the other top-level selected objects (at most 20000) match one of them, the source: the key object, or the top or the bottom selected object. Each can take the source's width (the height following in proportion), its height (the width following), or both, measured as `object.setBounds` measures them (Use Preview Bounds) in each object's own bounding-box frame; its bounding-box angle; and its stacking place, directly above the source in its layer or group, in the order they had (targets already there keep their places; otherwise a clipping path keeps its place, so a match that would move one is refused, as is one that would move a target into or out of a locked layer or group, out of the blend input it is in, among a blend's inputs or into, out of or within a Live Paint group). Sizing and turning keep each object's reference point in place; with Use Preview Bounds, for an object the match turns that carries a visible geometry or 3D effect or a live compound shape on itself or on art inside it, or a visible geometry or 3D effect in the art of a symbol it places, the match is refused when pixel snapping would move that object's reference point or change a dimension it was asked to match. The same refusal applies, with or without Use Preview Bounds, to a turned object that is pixel-aligned or holds pixel-aligned art or an instance of a pixel-aligned symbol. Strokes, effects and pattern tiles follow Scale Strokes & Effects and Transform Pattern Tiles. The source stays as it is, the dialog previews on the canvas, and OK is one undo step; no step when nothing changes. Places are matched with Align to Key Object (`object.align {to: "key"}`). Tests: `match_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (each size, the key, top and bottom sources, angles about the center, stacking within and across layers, no step when matched, bad params), `real_match_keyboard_edits_preview_confirm_and_cancel` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group Overlapping Objects (2026-11-01) From 8107acadf22439ef4cd46b70fd449d103887968b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 10:50:24 -0800 Subject: [PATCH 022/106] Scripts: a color picker answer refuses out-of-range arrays and objects An answer given as an array or object, such as [1.00000001, 0, 0] or {c: 100.000001, m: 0, y: 0, k: 0}, was narrowed to f32 before its range check, so a component just past a limit rounded onto it and passed. Its components are now checked as written, in f64 and on the scale paint.setFill reads them in, as color keys already were. Boundary values are still accepted. docs/mcp.md and script.run's params text list "stop" as a colorPicker answer, which a run stopped at the picker records. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 58 ++++++++++++++++------- crates/engine/src/tests/script_dialogs.rs | 18 ++++++- docs/mcp.md | 5 +- 4 files changed, 62 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b3cc43bed3..37d3c52c8f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name) | a color as paint.setFill takes it, with each component in its range (a color key such as \"rgb 300 0 0\" is refused, not clamped), or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK when the run's active document is CMYK), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)} or {kind: \"colorPicker\", color, answer: a color | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 5daae5bb1d..bcb6e1a551 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -170,25 +170,49 @@ fn in_range(c: &Color) -> bool { /// The color of a `colorPicker` answer, each component in its range ([`in_range`]). A color key /// such as `"rgb 300 0 0"` is checked as written, since reading it as a key puts its components -/// into their ranges. +/// into their ranges. An array or object is checked as written too, in f64 and with the scale +/// [`crate::cmd::color_value`] reads it in, so that a component just past a limit is not rounded +/// onto it when it narrows to f32. fn answer_color(v: &Value) -> Option { - if let Value::String(s) = v - && Color::from_hex(s).is_none() - { - let mut it = s.split_whitespace(); - let model = it.next()?.to_ascii_lowercase(); - // Parsed as f64, so that a value just past a limit is not rounded onto it. - let n: Vec = it.map(|t| t.parse::().ok().filter(|x| x.is_finite())).collect::>()?; - let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x)); - let written_in_range = match (model.as_str(), n.as_slice()) { - ("rgb", [_, _, _]) => within(&n, 0.0, 255.0), - ("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0), - ("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0), - _ => return None, - }; - if !written_in_range { - return None; + // Parsed as f64, so that a value just past a limit is not rounded onto it. + let within = |v: &[f64], lo: f64, hi: f64| v.iter().all(|x| (lo..=hi).contains(x)); + let num = |o: &serde_json::Map, key: &str| o.get(key).and_then(Value::as_f64); + let written_in_range = match v { + Value::String(s) if Color::from_hex(s).is_none() => { + let mut it = s.split_whitespace(); + let model = it.next()?.to_ascii_lowercase(); + let n: Vec = it.map(|t| t.parse::().ok().filter(|x| x.is_finite())).collect::>()?; + match (model.as_str(), n.as_slice()) { + ("rgb", [_, _, _]) => within(&n, 0.0, 255.0), + ("cmyk", [_, _, _, _]) | ("gray", [_]) => within(&n, 0.0, 100.0), + ("lab", [l, a, b]) => within(&[*l], 0.0, 100.0) && within(&[*a, *b], -128.0, 128.0), + _ => return None, + } } + Value::Array(a) if a.len() >= 3 => within(&[a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?], 0.0, 1.0), + Value::Object(o) => { + if let (Some(c), Some(m), Some(y), Some(k)) = (num(o, "c"), num(o, "m"), num(o, "y"), num(o, "k")) { + let scale = if [c, m, y, k].iter().any(|x| *x > 1.0) { 100.0 } else { 1.0 }; + within(&[c, m, y, k], 0.0, scale) + } else if let Some(g) = o.get("gray") { + let g = g.as_f64()?; + within(&[if g > 1.0 { g / 100.0 } else { g }], 0.0, 1.0) + } else if let (Some(l), Some(a), Some(b), None) = (num(o, "l"), num(o, "a"), num(o, "b"), o.get("model")) { + within(&[l], 0.0, 100.0) && within(&[a, b], -128.0, 128.0) + } else { + match o.get("model").and_then(Value::as_str) { + Some("rgb") => within(&[num(o, "r")?, num(o, "g")?, num(o, "b")?], 0.0, 1.0), + Some("cmyk") => within(&[num(o, "c")?, num(o, "m")?, num(o, "y")?, num(o, "k")?], 0.0, 1.0), + Some("gray") => within(&[num(o, "k")?], 0.0, 1.0), + Some("lab") => within(&[num(o, "l")?], 0.0, 100.0) && within(&[num(o, "a")?, num(o, "b")?], -128.0, 128.0), + _ => true, + } + } + } + _ => true, + }; + if !written_in_range { + return None; } crate::cmd::color_value(v).filter(in_range) } diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index dbd727e33c..7b154e607a 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -382,11 +382,27 @@ fn the_color_picker_refuses_what_is_not_a_solid_color() { json!("gray -1"), json!("lab 50 200 0"), json!("rgb 255.000001 0 0"), + json!([1.00000001, 0, 0]), + json!({"c": 100.000001, "m": 0, "y": 0, "k": 0}), + json!({"gray": 100.000001}), + json!({"l": 100.000001, "a": 0, "b": 0}), + json!({"model": "rgb", "r": 1.00000001, "g": 0, "b": 0}), + json!({"model": "lab", "l": 50, "a": -128.000001, "b": 0}), ] { let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); assert!(e.contains("color picker's answer"), "{bad}: {e}"); } - for good in [json!("rgb 255 0 0"), json!("cmyk 0 100 100 0"), json!("gray 100"), json!("lab 50 -128 128")] { + for good in [ + json!("rgb 255 0 0"), + json!("cmyk 0 100 100 0"), + json!("gray 100"), + json!("lab 50 -128 128"), + json!([1, 0, 0]), + json!({"c": 0, "m": 100, "y": 100, "k": 0}), + json!({"gray": 100}), + json!({"l": 100, "a": -128, "b": 128}), + json!({"model": "rgb", "r": 1, "g": 0, "b": 0}), + ] { assert!(headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": good})])).is_ok(), "{good}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index f0cb382b42..d38719f8f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3669,8 +3669,9 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"` for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a `show()` that ended with an error. `app.showColorPicker` is listed as `{kind: "colorPicker", color, answer}`, with - the color it opened on and the color picked, `null` for Cancel or `"missing"`, each color as `paint.setFill` takes - it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at its limit. + the color it opened on and the color picked, `null` for Cancel, `"stop"` or `"missing"`, each color as + `paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at + its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} From 38342a5c6f3ef8b8d66f9b89fff8c28938f42ed6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:26:13 -0800 Subject: [PATCH 023/106] Scripts: reshaped and opened paths keep the right selection - path.setAnchors on a member of a compound path drops the compound path from the selection too, unless another member still has anchors or segments selected, so a following Join does not act on the unselected sibling paths. A script's put-back selection follows the same rule. - Opening a path in a script drops its segments and the anchors that only ended them; other selected anchors stay selected. - Removing a point that waits to be written with replaced points no longer puts the old selection back on the new points. --- crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/path.rs | 17 ++++++- crates/engine/src/script/dom.rs | 19 +++++++- crates/engine/src/script/dom/paths.rs | 4 ++ crates/engine/src/tests/script_dom_paths.rs | 54 +++++++++++++++++++++ 5 files changed, 92 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 42e3f1d960..412245b917 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -865,6 +865,7 @@ pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; pub use docmenu::guide_indexes; pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; +pub(crate) use path::deselect_path; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. pub use object::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 57d6a517ef..3737b3692b 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -869,7 +869,7 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result { // Direct-selected anchors and segments are kept by index: when anchors were added, // removed or replaced, the path is deselected rather than left with other anchors selected. if reshaped && (sel.anchors.remove(&id).is_some() | sel.segments.remove(&id).is_some()) { - sel.objects.retain(|o| *o != id); + deselect_path(d, sel, id); sel.prune(d); } Ok(()) @@ -877,6 +877,21 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result { ok() } +/// Removes the path `id`, whose direct-selected anchors and segments were dropped, from +/// `sel.objects`. A member of a compound path is selected through the compound path, which leaves +/// the selection too unless another of its members still has anchors or segments selected; +/// otherwise every open member of the compound path would count as selected. +pub(crate) fn deselect_path(d: &Document, sel: &mut Selection, id: NodeId) { + let top = compound_or_self(d, id); + let direct = |c: &Node| sel.anchors.get(&c.id).is_some_and(|a| !a.is_empty()) || sel.segments.get(&c.id).is_some_and(|g| !g.is_empty()); + let sibling = top != id + && d.node(top).is_some_and(|n| match &n.kind { + NodeKind::Compound { children, .. } => children.iter().any(|c| c.id != id && direct(c)), + _ => false, + }); + sel.objects.retain(|o| *o != id && (sibling || *o != top)); +} + /// The compound path enclosing `id`, or `id` itself if it is not inside a compound path. pub(crate) fn compound_or_self(d: &Document, id: NodeId) -> NodeId { d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))).unwrap_or(id) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 67748408f6..5641822bc4 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -926,7 +926,9 @@ fn on_doc_steps( // it are not selected in their place. Anchors and segments a change removed are left out // when the selection is put back ([`restore_selection`]). A path that was opened or closed // keeps its anchors but not its segments: when it had segments selected and none of them - // is left, it is not selected again either. + // is left, the segments and the anchors that only ended them are dropped, and it is + // selected again only when other anchors of it were selected. A member of a compound path + // that is not selected again takes the compound path with it ([`crate::cmd::deselect_path`]). if let Some(doc) = &doc { let counts = |d: &Document, id: NodeId| { d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| (sp.anchors.len(), sp.segment_count())).collect::>()) @@ -943,10 +945,23 @@ fn on_doc_steps( && anchors(&was) == anchors(&now) && before.segments.get(&id).is_some_and(|g| !g.is_empty()) && !before.segments.get(&id).is_some_and(|g| g.iter().any(segment_left)); + if reopened && reshaped != Some(id) { + // Segment k of a subpath of n anchors ends at anchors k and (k + 1) mod n. + let len = |p: usize| old.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(p)).map_or(1, |sp| sp.anchors.len().max(1)); + let ends: HashSet<(usize, usize)> = + before.segments.remove(&id).into_iter().flatten().flat_map(|(p, k)| [(p, k), (p, (k + 1) % len(p))]).collect(); + if let Some(kept) = before.anchors.get_mut(&id) { + kept.retain(|r| !ends.contains(r)); + } + if let Some(kept) = before.anchors.get(&id).filter(|a| !a.is_empty()) { + before.key_anchor = before.key_anchor.filter(|(k, r)| *k != id || kept.contains(r)); + continue; + } + } if reshaped == Some(id) || reopened { before.anchors.remove(&id); before.segments.remove(&id); - before.objects.retain(|o| *o != id); + crate::cmd::deselect_path(doc, &mut before, id); before.key_anchor = before.key_anchor.filter(|(k, _)| *k != id); before.key = before.key.filter(|k| *k != id); } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index aa8f355167..0585c78359 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1893,6 +1893,10 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option) -> std::result::Result<(), HostError> { // A direct selection that is renumbered here is not dropped when the points are written. let was_reshaped = matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) && h.dom.pending_reshaped.get(); + // Points that wait to be written with added, removed or replaced points drop the path's direct + // selection when they are written, so the selection from before them is not renumbered or + // put back on the new points. + let selected = selected.filter(|_| !was_reshaped); let keeps_selection = selected.is_some(); let removed = edit_points(h, item, |subs| { let (s, j) = locate(subs, i)?; diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b0cc3c4b5a..9ba8b92089 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -195,6 +195,60 @@ fn opening_a_path_deselects_its_closing_segment() { assert!(sel.objects.contains(&a)); } +#[test] +fn opening_a_path_keeps_its_other_selected_anchors() { + // `b` has anchor 1 selected and its closing segment 3, which ends at anchors 3 and 0. + let (mut s, _, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 3]], "mode": "add"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[1].closed = false;"); + let sel = &s.active().unwrap().selection; + assert!(sel.objects.contains(&b) && !sel.segments.contains_key(&b), "{sel:?}"); + assert_eq!(sel.anchors.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 1)]), "{sel:?}"); +} + +#[test] +fn removing_a_replaced_point_does_not_restore_the_old_selection() { + // Anchor 1 of `b` is selected; the new points and the removal wait to be written together. + let (mut s, _, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems[1]; p.setEntirePath([[1, 2], [31, 2], [31, 42], [1, 42]]); p.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)); + assert!(!st.selection.anchors.contains_key(&b), "{:?}", st.selection); +} + +#[test] +fn set_anchors_on_a_compound_member_leaves_its_siblings_unselected() { + 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 c = s.active().unwrap().doc.parent_of(b).unwrap(); + assert_eq!(s.active().unwrap().doc.parent_of(a), Some(c)); + let pt = |x: f64, y: f64| json!({"x": x, "y": y, "in": [x, y], "out": [x, y], "smooth": false}); + let three = json!([{"anchors": [pt(0.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); + // A direct selection of a member selects the compound path and the member's anchors. + let direct = |s: &mut Session, others: bool| { + s.select(|_, sel| { + sel.set([c]); + sel.anchors.insert(b, [(0, 1)].into()); + if others { + sel.anchors.insert(a, [(0, 0)].into()); + } + }) + .unwrap(); + }; + direct(&mut s, false); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": three})).unwrap(); + let sel = &s.active().unwrap().selection; + assert!(!sel.objects.contains(&c) && !sel.anchors.contains_key(&b), "{sel:?}"); + // A sibling's direct selection keeps the compound path selected. + direct(&mut s, true); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": three, "reshaped": true})).unwrap(); + let sel = &s.active().unwrap().selection; + assert!(sel.objects.contains(&c) && !sel.anchors.contains_key(&b) && sel.anchors.contains_key(&a), "{sel:?}"); +} + #[test] fn closing_a_path_without_points_throws() { let (mut s, _, _) = doc(); From 9fdf53ce0f785d1ca2f85d530bd311decd73c05c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:55:04 -0800 Subject: [PATCH 024/106] fmt: order the deselect_path use and wrap the segment-ends closure --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/script/dom.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index f4149af860..6d41322115 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -881,11 +881,11 @@ pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; pub use docmenu::guide_indexes; pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; -pub(crate) use path::deselect_path; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. pub use object::{reflect_axis, scale_factors, shear_tangent}; pub(crate) use paint::{asks_defaults_only, painting_tool_of}; +pub(crate) use path::deselect_path; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 5641822bc4..257e214992 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -947,7 +947,8 @@ fn on_doc_steps( && !before.segments.get(&id).is_some_and(|g| g.iter().any(segment_left)); if reopened && reshaped != Some(id) { // Segment k of a subpath of n anchors ends at anchors k and (k + 1) mod n. - let len = |p: usize| old.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(p)).map_or(1, |sp| sp.anchors.len().max(1)); + let len = + |p: usize| old.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(p)).map_or(1, |sp| sp.anchors.len().max(1)); let ends: HashSet<(usize, usize)> = before.segments.remove(&id).into_iter().flatten().flat_map(|(p, k)| [(p, k), (p, (k + 1) % len(p))]).collect(); if let Some(kept) = before.anchors.get_mut(&id) { From 4fed06a3a68479bbfc6ac2f221ba61df3e18cf91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:02:20 -0800 Subject: [PATCH 025/106] MCP: ui.menuDialog's params text lists addon.arrange.artboardGuides Add Artboard Guides opens its dialog through ui.menuDialog, but the command list in the params text (ui_commands.rs and the MCP catalog) left it out, so menu_dialog_params_text_lists_every_command_whose_dialog_it_opens failed. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..66d931f39f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..d0adeef1b8 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 04198e416ea74c17de6aae95d93c7821819f83ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:17:29 -0800 Subject: [PATCH 026/106] Add Artboard Guides: a guide drawn from another corner is a duplicate, and the dialog needs an artboard A guide already on the Artboard Guides layer with the same four corners is skipped whichever corner its path starts from and whichever way it runs. The dialog no longer opens on a document without artboards; ui.menuDialog returns an error instead. --- .../src/cmd/addons/arrange/artboard_guides.rs | 29 ++++++++++++++++--- .../addons/arrange/artboard_guides/tests.rs | 23 ++++++++++++++- crates/ui-egui/src/addons/arrange.rs | 3 ++ crates/ui-egui/src/addons/arrange/tests.rs | 9 ++++++ docs/mcp.md | 3 +- 5 files changed, 61 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs index 69231b1f8e..862eef710e 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -7,7 +7,7 @@ mod tests; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes}; use super::super::super::panelcmds::{artboard_at, listed_artboards}; use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; @@ -51,18 +51,39 @@ fn guide_layer(d: &Document) -> Option { d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id) } -/// Does `layer` already hold a guide path drawn as `rect` is? +/// Does `layer` already hold a guide path with `rect`'s four corners, starting at any corner and +/// running either way round? fn holds_guide(d: &Document, layer: Option, rect: Rect) -> bool { - let path = shapes::rectangle(rect); + let r = rect.abs(); + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; layer.and_then(|id| d.node(id)).is_some_and(|n| { let mut found = false; n.walk(&mut |c| { - found |= matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if *p == path); + found |= matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if traces(p, &corners)); }); found }) } +/// Is `path` one closed run of straight segments through `corners`, from any corner, either way round? +fn traces(path: &PathData, corners: &[Point; 4]) -> bool { + let [sp] = &path.subpaths[..] else { return false }; + if !sp.closed || sp.anchors.len() != 4 { + return false; + } + let anchors: Vec<&Anchor> = sp.anchors.iter().collect(); + let [first, second, ..] = anchors[..] else { return false }; + if anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { + return false; + } + let (Some(start), Some(next)) = (corners.iter().position(|&c| c == first.p), corners.iter().position(|&c| c == second.p)) else { + return false; + }; + // 1 runs the way `corners` does, 3 the other way. + let step = (next + 4 - start) % 4; + (step == 1 || step == 3) && anchors.iter().enumerate().all(|(k, a)| a.p == corners[(start + k * step) % 4]) +} + fn artboard_guides(s: &mut Session, p: &Value) -> Result { const C: &str = COMMAND; let offset = number_in(p, "offset", 0.0, (-LIMIT, LIMIT), C)?; diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs index 5b8093b07e..ba345a85ca 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; -use vectorcraft_geom::Rect; +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; use super::{COMMAND, LAYER}; use crate::Session; @@ -145,6 +145,27 @@ fn a_guide_grouped_inside_the_layer_is_not_added_again() { assert!(*s.doc().unwrap().doc == *before, "the document is unchanged"); } +#[test] +fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + let layer = NodeId(r["layer"].as_u64().unwrap()); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0).inflate(5.0, 5.0); + let corners = [Point::new(b.x0, b.y1), Point::new(b.x1, b.y1), Point::new(b.x1, b.y0), Point::new(b.x0, b.y0)]; + // Reversed from the top-left corner, reversed from the bottom-left one, and the same way round from the bottom-right one. + for points in [vec![corners[3], corners[0], corners[1], corners[2]], corners.to_vec(), vec![corners[1], corners[0], corners[3], corners[2]]] { + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if let Some(NodeKind::Path { path, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *path = PathData::single(SubPath::polyline(&points, true)); + } + let n = steps(&s); + let again = s.execute(COMMAND, &json!({"offset": 5})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": layer.0, "skipped": 1}), "{points:?}"); + assert_eq!(steps(&s), n); + } +} + #[test] fn release_guides_gives_back_a_rectangle_path() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 6aad8c5fbb..224cbddf50 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -249,6 +249,9 @@ fn guides_params(fields: &DialogFields) -> Value { pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option> { let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?; let st = app.session.active()?; + if command == GUIDES && st.doc.artboards.is_empty() { + return Some(Err("the document has no artboards".into())); + } let strokes = app.session.prefs.scale_strokes; let key = st.selection.key.is_some(); let lengths = general_lengths(app); diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 924c3064a7..e659e2ee79 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -232,6 +232,15 @@ fn add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_i assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); } +#[test] +fn add_artboard_guides_does_not_open_without_artboards() { + let (mut app, _, _) = app(); + std::sync::Arc::make_mut(&mut app.session.active_mut().unwrap().doc).artboards.clear(); + let opened = crate::addons::dialogs::open_from_menu(&mut app, "addon.arrange.artboardGuides"); + assert!(matches!(opened, Some(Err(_))), "{opened:?}"); + assert!(!app.any_dialog_open()); +} + #[test] fn add_artboard_guides_uses_the_artboard_the_view_shows() { let (mut app, _, _) = app(); diff --git a/docs/mcp.md b/docs/mcp.md index aad5c88e8c..ab10050e91 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17751,7 +17751,8 @@ Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mod active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, and fails with nothing selected. Add Artboard Guides… opens a dialog with Offset and Artboards (Active Artboard, or All Artboards, which sends `all: true`) and a Preview; for Active Artboard it sends the artboard the view showed when the -dialog opened as `artboard`. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs +dialog opened as `artboard`. It does not open, and `ui.menuDialog` returns an error, when the document has no +artboards. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs (`ui.menuDialog {command}`; each dialog's `key` is its command id, such as `addon.arrange.grid`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. Match Objects… opens a dialog of its own in the same way, keyed by its command, whose fields are the command's From 0b5e647aa1bc302bb880b466047c8611d08e4e18 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:35:02 -0800 Subject: [PATCH 027/106] Add Artboard Guides: the duplicate check stops at the first match without allocating ui.menuDialog's params text and the progress line say the dialog needs an artboard. --- .../src/cmd/addons/arrange/artboard_guides.rs | 23 +++++++++++-------- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs index 862eef710e..4c4f42d719 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -7,7 +7,7 @@ mod tests; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes}; +use vectorcraft_geom::{PathData, Point, Rect, shapes}; use super::super::super::panelcmds::{artboard_at, listed_artboards}; use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; @@ -57,11 +57,14 @@ fn holds_guide(d: &Document, layer: Option, rect: Rect) -> bool { let r = rect.abs(); let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; layer.and_then(|id| d.node(id)).is_some_and(|n| { - let mut found = false; - n.walk(&mut |c| { - found |= matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if traces(p, &corners)); - }); - found + n.try_walk(&mut |c| { + if matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if traces(p, &corners)) { + std::ops::ControlFlow::Break(()) + } else { + std::ops::ControlFlow::Continue(()) + } + }) + .is_break() }) } @@ -71,9 +74,9 @@ fn traces(path: &PathData, corners: &[Point; 4]) -> bool { if !sp.closed || sp.anchors.len() != 4 { return false; } - let anchors: Vec<&Anchor> = sp.anchors.iter().collect(); - let [first, second, ..] = anchors[..] else { return false }; - if anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { + let mut anchors = sp.anchors.iter(); + let (Some(first), Some(second)) = (anchors.next(), anchors.next()) else { return false }; + if sp.anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { return false; } let (Some(start), Some(next)) = (corners.iter().position(|&c| c == first.p), corners.iter().position(|&c| c == second.p)) else { @@ -81,7 +84,7 @@ fn traces(path: &PathData, corners: &[Point; 4]) -> bool { }; // 1 runs the way `corners` does, 3 the other way. let step = (next + 4 - start) % 4; - (step == 1 || step == 3) && anchors.iter().enumerate().all(|(k, a)| a.p == corners[(start + k * step) % 4]) + (step == 1 || step == 3) && sp.anchors.iter().enumerate().all(|(k, a)| a.p == corners[(start + k * step) % 4]) } fn artboard_guides(s: &mut Session, p: &Value) -> Result { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 66d931f39f..6bb92bc665 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d0adeef1b8..c19d0a4401 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.artboardGuides|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); addon.arrange.artboardGuides fails when the document has no artboards; Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6973a56d11..77ed9f6a3c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3158,7 +3158,7 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov ## Arrange Tools add-on: Add Artboard Guides (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard, or around every artboard, at the Offset typed: more than 0 puts it outside the artboard (a bleed line), less than 0 inside it (a safe-area line). The guides go on a top-level layer named Artboard Guides, made above the others the first time and reused after that with its lock and visibility as they are; a guide already anywhere in that layer with the same rectangle is not added again. The dialog acts on the artboard the view shows. One undo step; no step when nothing is added. An inset that leaves an artboard no width or no height is refused. `addon.arrange.artboardGuides` also takes a list of artboards. Tests: `cmd::addons::arrange::artboard_guides::tests` in `vectorcraft-engine` (outside and inside offsets, the active artboard and the one the journal records, every artboard and listed ones, the layer reused with its lock and visibility, no repeat and no step, a guide grouped inside the layer, Release Guides, bad params and too large an inset refused, off without artboards), `real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step`, `add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset` and `add_artboard_guides_uses_the_artboard_the_view_shows` in `vectorcraft-ui-egui`, and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Add Artboard Guides… adds a rectangular guide around the active artboard, or around every artboard, at the Offset typed: more than 0 puts it outside the artboard (a bleed line), less than 0 inside it (a safe-area line). The guides go on a top-level layer named Artboard Guides, made above the others the first time and reused after that with its lock and visibility as they are; a guide already anywhere in that layer with the same rectangle, from whichever corner and in whichever direction its path runs, is not added again. The dialog acts on the artboard the view shows. One undo step; no step when nothing is added. The dialog does not open, and `ui.menuDialog` returns an error, when the document has no artboards. An inset that leaves an artboard no width or no height is refused. `addon.arrange.artboardGuides` also takes a list of artboards. Tests: `cmd::addons::arrange::artboard_guides::tests` in `vectorcraft-engine` (outside and inside offsets, the active artboard and the one the journal records, every artboard and listed ones, the layer reused with its lock and visibility, no repeat and no step, a guide grouped inside the layer, a guide drawn from another corner or the other way round, Release Guides, bad params and too large an inset refused, off without artboards), `real_artboard_guide_edits_reach_the_preview_and_ok_adds_one_undo_step`, `add_artboard_guides_puts_one_around_every_artboard_and_refuses_too_large_an_inset`, `add_artboard_guides_does_not_open_without_artboards` and `add_artboard_guides_uses_the_artboard_the_view_shows` in `vectorcraft-ui-egui`, and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Offset Objects (2026-11-29) From fe36fe67d08b02142ff04d82ebe20fa96982ff7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:43:56 -0800 Subject: [PATCH 028/106] Scripts: layer collections go stale after Revert, addDocument keeps the built-in layout - A layer's, group's or compound path's layers, pageItems, groupItems, compoundPathItems and pathItems read before File > Revert now throw instead of listing the loaded document's art under the same id. - addDocument with a saved preset of the built-in preset's name lays out several artboards as the built-in preset does, with presetSettings over it. - Layer.zOrderPosition reads the kept list of sibling layers. - PathItems.parent is described as any container, and the docs say when PathPoint.remove() keeps the direct selection. --- crates/engine/src/script/dom.rs | 32 ++++++++++-------- crates/engine/src/script/dom/layers.rs | 31 +++++++++--------- crates/engine/src/script/dom/paths.rs | 11 +++---- crates/engine/src/tests/script_dom.rs | 45 +++++++++++++++++++++++++- docs/mcp.md | 15 ++++++--- 5 files changed, 93 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b9bb40ef98..df1233b18e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -53,8 +53,8 @@ //! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at //! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an //! error. A run that fails leaves the tool as it was. -//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path -//! in the object. +//! - `controlBounds` is the visible bounds, widened to take in the direction points of the paths +//! those bounds take in. //! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]), //! in view-number order, and none without one. View objects keep their window's identity when //! windows are renumbered. The screen mode is the app's: @@ -569,6 +569,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)?; @@ -1596,21 +1605,16 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { 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()); - // `file.new` would find the saved preset of that name first: the built-in preset's - // settings go as params instead, under the ones `presetSettings` gives. - if let Value::Object(base) = first.to_json() { - for (k, v) in base.into_iter().filter(|(k, _)| !matches!(k.as_str(), "name" | "size" | "orientation" | "profile")) { - p.entry(k).or_insert(v); - } - } } 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) { - p.insert((*key).into(), v.clone()); - } + } + if let Value::Object(settings) = full.to_json() { + for key in BUILT_IN_SETTINGS { + if let Some(v) = settings.get(*key) { + p.insert((*key).into(), v.clone()); } } } diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 1b716639ca..ace2a0b7a7 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -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, class_text, 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, num, number, on_doc, on_doc_layer, page_items, placement_of, property, returns, text, typed, - typename, whole, with_doc, + arg, boolean, class_text, 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, returns, text, typed, typename, whole, + with_doc, }; use crate::script::{Host, Link}; use crate::{DocState, Document, NodeId, NodeKind}; @@ -294,9 +294,9 @@ fn layer_typename(h: &Host, a: &[Data]) -> Answer { fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let list = layer_list(&st.doc, st.doc.parent_of(id)); - list.iter().position(|l| *l == id).map(|i| list.len() - i) - }); + let list = layer_ids(h, st, st.doc.parent_of(id))?; + Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) + })?; at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into())) } @@ -476,9 +476,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] => { - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; - let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; + [_, _, _, _, _] => { + // A collection read before its document was reverted is stale, as its layer is. + let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?; let (doc, id) = held_layer(h, doc, id)?; Ok((doc, Some(id))) } @@ -530,8 +530,7 @@ fn layer_ids(h: &Host, st: &DocState, parent: Option) -> Result Answer { let (doc, id) = this_layer(h, a)?; - let [high, low] = id_parts(id); - Ok(host_ref("Layers", &[float(h.run), float(doc.uid), high, low])) + Ok(host_ref("Layers", &super::scoped_handle(h, doc.uid, id))) } fn layers_length(h: &Host, a: &[Data]) -> Answer { @@ -622,9 +621,9 @@ 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] => { - 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 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 { .. })) }); @@ -684,12 +683,12 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R /// 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() == 4) + 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]]), + Some(c) => host_ref(kind.class(), &super::scoped_handle(h, uid, c)), None => host_ref(kind.class(), &[float(h.run), float(uid)]), } } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 63cc362dff..4bb24fdf5c 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -475,8 +475,7 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { /// The `pathItems` of the layer or group `id` in the document `uid`. pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { - let [high, low] = id_parts(id); - host_ref("PathItems", &[float(h.run), float(uid), high, low]) + 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 @@ -485,9 +484,9 @@ fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option< let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) }; match handle.as_slice() { [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)), - [run, uid, high, low] => { - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + [_, _, _, _, _] => { + // 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 { .. })) }); @@ -2083,7 +2082,7 @@ pub(super) fn classes(l: &Link) -> Vec { named(vec![ ("typename", get(l, items_typename), typed("string")), ("length", get(l, items_length), typed("number")), - ("parent", get(l, items_parent), typed("Document")), + ("parent", get(l, items_parent), typed("*")), ("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])), ("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])), ("removeAll", method(l, items_remove_all), returns("undefined", &[])), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 1b27954ab7..066c52a71b 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1642,11 +1642,25 @@ fn add_document_starts_from_the_built_in_preset_when_a_saved_one_has_its_name() #[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] @@ -1967,6 +1981,23 @@ 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}"); + } +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); @@ -2872,6 +2903,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")); } diff --git a/docs/mcp.md b/docs/mcp.md index 0d489df1d7..0fc8a5aceb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3095,7 +3095,9 @@ through `$`: tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was deleted, that a named engine kept from an earlier run, or whose document was reverted with `file.revert`, throws - `Stale page item`. Layer objects also become stale after their document is reverted. `remove()` on an object that + `Stale page item`. Layer objects also become stale after their document is reverted, and so do the `layers`, + `pageItems`, `groupItems`, `compoundPathItems` and `pathItems` of a layer, group or compound path read before the + revert; the document's own collections stay usable. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` @@ -3318,9 +3320,14 @@ through `$`: 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 throws `Cannot close a path that has no points`. - Writing changes that added, removed or replaced points deselects the path's direct-selected anchors, even when the - path ends with as many points as before; changes that only move points or handles, change a point's type or set - `closed` keep them selected. + Writing changes that added or replaced points, or that removed points along with other such changes, deselects the + path's direct-selected anchors, even when the path ends with as many points as before. `PathPoint.remove()` on its + own 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. Changes that + only move points or handles, change a point's type or set `closed` keep them selected. `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`, From e0d9b3118584fd5d8775a6416b294cd44671d7c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 15:29:40 -0800 Subject: [PATCH 029/106] New Document: the rows test follows main's whole-number rows again Cause of the CI failure on 56b4248f0f: main's #10153 made file.new refuse artboardLayout.rows that are not whole numbers on a direct call (replays still round). The New Document dialog reads rows through the same parser, so setting rows to 3.6 now returns an error and the test's unwrap panicked. The test again sets 4.0 and expects 4, and checks that 3.5, 0.4, 0 and 1001 are refused with the rows left as they were. --- crates/ui-egui/src/dialogs/new_document.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 80babf2275..914a813a43 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1057,16 +1057,16 @@ mod tests { }) } - /// The dialog reads rows as `file.new` does: rounded to a whole number from 1 to the artboard - /// limit, and a count that rounds to 0 or is larger is refused with nothing changed. + /// 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": 3.6})).unwrap(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4.0})).unwrap(); assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); - for rows in [json!(0.4), json!(MAX_ARTBOARDS + 1), json!(0)] { + 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}"); From c1a2df3912118fffcefed52624301448ad5e3ff2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:43:18 -0800 Subject: [PATCH 030/106] Scripts: numeric names in scoped collections, stale artboards after Revert - A layer's, group's or compound path's pageItems, pathItems, groupItems, compoundPathItems and layers, and the document's artboards, look up a key such as "-1" or 1.5 as a name, as the document's pageItems does. index() still takes a number as a position only. - pageItems.index() on a layer, group or compound path reads that container's list instead of throwing a type error. - An Artboard read before File > Revert throws Stale artboard instead of changing the loaded artboard with the same id. A retained artboards collection still lists the loaded artboards. - Opening a path with some of its selected segments left drops the anchors that only ended the removed segments and keeps the segments that are left. - PathPoint.selected writes waiting point changes first when they replaced the path's points, so the read matches the selection after the write. - PageItems.parent is described as any container. --- crates/engine/src/script/dom.rs | 64 +++++++++++++++------ crates/engine/src/script/dom/layers.rs | 45 ++++++++++++--- crates/engine/src/script/dom/paths.rs | 19 ++++-- crates/engine/src/tests/script_dom.rs | 34 +++++++++++ crates/engine/src/tests/script_dom_paths.rs | 24 ++++++++ docs/mcp.md | 6 +- 6 files changed, 159 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a5a3896096..af249adc0d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -84,7 +84,7 @@ //! more than one type. use std::cell::{Cell, RefCell}; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::rc::Rc; use std::sync::Arc; @@ -960,9 +960,9 @@ fn on_doc_steps( // with added, removed or replaced points is not selected again, so that other anchors of // it are not selected in their place. Anchors and segments a change removed are left out // when the selection is put back ([`restore_selection`]). A path that was opened or closed - // keeps its anchors but not its segments: when it had segments selected and none of them - // is left, the segments and the anchors that only ended them are dropped, and it is - // selected again only when other anchors of it were selected. A member of a compound path + // keeps its anchors but not the segments it lost: the segments that are gone and the + // anchors that only ended them are dropped, and when none of its selected segments is + // left it is selected again only when other anchors of it were selected. A member of a compound path // that is not selected again takes the compound path with it ([`crate::cmd::deselect_path`]). if let Some(doc) = &doc { let counts = |d: &Document, id: NodeId| { @@ -976,18 +976,26 @@ fn on_doc_steps( let segment_left = |&(p, k): &(usize, usize)| { doc.node(id).and_then(|n| n.path_data()).is_some_and(|pd| pd.subpaths.get(p).is_some_and(|sp| sp.has_segment(k, true))) }; - let reopened = was != now - && anchors(&was) == anchors(&now) - && before.segments.get(&id).is_some_and(|g| !g.is_empty()) - && !before.segments.get(&id).is_some_and(|g| g.iter().any(segment_left)); - if reopened && reshaped != Some(id) { + let opened = was != now && anchors(&was) == anchors(&now) && before.segments.get(&id).is_some_and(|g| !g.is_empty()); + let reopened = opened && !before.segments.get(&id).is_some_and(|g| g.iter().any(segment_left)); + if opened && reshaped != Some(id) { // Segment k of a subpath of n anchors ends at anchors k and (k + 1) mod n. let len = |p: usize| old.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(p)).map_or(1, |sp| sp.anchors.len().max(1)); - let ends: HashSet<(usize, usize)> = - before.segments.remove(&id).into_iter().flatten().flat_map(|(p, k)| [(p, k), (p, (k + 1) % len(p))]).collect(); + let ends = |&(p, k): &(usize, usize)| [(p, k), (p, (k + 1) % len(p))]; + let (left, gone): (BTreeSet<(usize, usize)>, BTreeSet<(usize, usize)>) = + before.segments.remove(&id).into_iter().flatten().partition(|s| segment_left(s)); + // The anchors that only ended removed segments are dropped; the ends of the + // segments that are left stay selected. + let still: HashSet<(usize, usize)> = left.iter().flat_map(ends).collect(); + let dropped: HashSet<(usize, usize)> = gone.iter().flat_map(ends).filter(|r| !still.contains(r)).collect(); if let Some(kept) = before.anchors.get_mut(&id) { - kept.retain(|r| !ends.contains(r)); + kept.retain(|r| !dropped.contains(r)); + } + before.key_anchor = before.key_anchor.filter(|(k, r)| *k != id || !dropped.contains(r)); + if !left.is_empty() { + before.segments.insert(id, left); + continue; } if let Some(kept) = before.anchors.get(&id).filter(|a| !a.is_empty()) { before.key_anchor = before.key_anchor.filter(|(k, r)| *k != id || kept.contains(r)); @@ -2288,6 +2296,28 @@ 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. @@ -2300,10 +2330,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer { 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), } @@ -2334,6 +2361,9 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { } fn items_index(h: &Host, a: &[Data]) -> Answer { + if layers::is_scoped(a) { + return layers::scoped_index(h, a); + } match arg(a, 1) { Data::String(_) => items_by_name(h, a), Data::Number(n) => { @@ -3270,7 +3300,7 @@ fn classes(link: &Link) -> Vec { named(vec![ ("typename", get(l, items_typename), typed("string")), ("length", get(l, items_length), typed("number")), - ("parent", get(l, items_parent), typed("Document")), + ("parent", get(l, items_parent), typed("*")), ("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])), ("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])), ("removeAll", method(l, items_remove_all), returns("undefined", &[])), diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index ace2a0b7a7..d00eea4999 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -548,14 +548,18 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer { Ok(text("Layers")) } -/// `layers[i]`, and `layers["name"]` as `getByName` reads it. +/// `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 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) }; + 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)))) } @@ -573,6 +577,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), @@ -704,14 +710,18 @@ 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. +/// `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 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) }; - 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) }; with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } @@ -730,6 +740,8 @@ 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 here, never a name ([`art_at`]). + Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())), Data::Number(_) => match art_at(h, a, kind)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -788,6 +800,10 @@ pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { art_by_name(h, a, Kind::Any) } +pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Any) +} + pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer { art_remove_all(h, a, Kind::Any) } @@ -1050,17 +1066,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] = handle.as_slice() 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()))?; - let index = with_doc(h, doc, |_, st| board_index(st, id)).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?; + 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)]) + 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)> { @@ -1261,14 +1282,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. +/// `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 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)))) } @@ -1285,6 +1310,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), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 4bb24fdf5c..4d36f1d45a 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -520,14 +520,18 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer { }) } -/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. +/// `pathItems[i]`, and `pathItems["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 items_at(h: &super::Host, a: &[Data]) -> Answer { let (doc, c) = items_scope(h, a)?; if let Data::String(_) = arg(a, 1) { return super::by_name_or_probe(a, items_by_name(h, a)); } + if let Some(named) = super::number_named(a) { + return super::named_or_undefined(items_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) }; with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } @@ -545,6 +549,8 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { fn items_index(h: &super::Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), + // A number is a position here, never a name ([`items_at`]). + Data::Number(n) if super::position(*n).is_none() => Err(HostError::Error(NOT_FOUND.into())), Data::Number(_) => match items_at(h, a)? { Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), d => Ok(d), @@ -1787,12 +1793,15 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point /// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in -/// [`super::State`] are written first only when they add or remove points of this path, since -/// the selection names anchors by their place in the document's path. +/// [`super::State`] are written first only when they add, remove or replace points of this path, +/// since the selection names anchors by their place in the document's path and a write that +/// replaced points deselects the path's anchors ([`flush`]). fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; let moved = match &*h.dom.pending.borrow() { - Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, + Some((waiting, subs)) if same_path(*waiting, item) => { + h.dom.pending_reshaped.get() || !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))? + } _ => false, }; if moved { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 97d7b5a672..a3b9c913f3 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2002,6 +2002,40 @@ fn a_layers_collections_read_before_a_revert_are_stale() { } } +/// 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")]); +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { 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 d3b53c9f78..4bb35b8702 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -207,6 +207,30 @@ fn opening_a_path_keeps_its_other_selected_anchors() { assert_eq!(sel.anchors.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 1)]), "{sel:?}"); } +#[test] +fn opening_a_path_drops_the_anchor_that_only_ended_its_closing_segment() { + // `b` has segment 0 (anchors 0 and 1) and its closing segment 3 (anchors 3 and 0) selected. + let (mut s, _, b) = doc(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 0], [0, 3]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[1].closed = false;"); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.segments.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 0)]), "{sel:?}"); + assert_eq!(sel.anchors.get(&b).map(|g| g.iter().copied().collect::>()), Some(vec![(0, 0), (0, 1)]), "{sel:?}"); +} + +#[test] +fn a_replaced_point_reads_as_unselected_before_and_after_the_write() { + // Anchor 1 of `b` is selected; the replacement has as many points and waits to be written. + let (mut s, _, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[1]; p.setEntirePath([[1, 2], [31, 2], [31, 42], [1, 42]]);\ + vc.log(p.pathPoints[1].selected); vc.log(p.pathPoints.length); vc.log(p.pathPoints[1].selected);", + ); + assert_eq!(out, vec![json!("PathPointSelection.NOSELECTION"), json!(4), json!("PathPointSelection.NOSELECTION")]); +} + #[test] fn removing_a_replaced_point_does_not_restore_the_old_selection() { // Anchor 1 of `b` is selected; the new points and the removal wait to be written together. diff --git a/docs/mcp.md b/docs/mcp.md index b2e14061cf..3d5d18500d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3080,7 +3080,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 @@ -3101,7 +3102,8 @@ 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 `layers`, + `Stale page item`. Layer and artboard objects also become stale after their document is reverted (an artboard + throws `Stale artboard`), and so do the `layers`, `pageItems`, `groupItems`, `compoundPathItems` and `pathItems` of a layer, group or compound path read before the revert; the document's own collections stay usable. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` From 020cc1333a73dfaa4fdd7c2e813615037ed0e0d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:26:18 -0800 Subject: [PATCH 031/106] Scripts: name the partitioned segment sets' type so clippy 1.100 passes Clippy 1.100's type_complexity lint rejects the two-set tuple annotation in the segment partition of crates/engine/src/script/dom.rs, which stopped the CI gate at its clippy step. The set type now goes on the partition call. --- crates/engine/src/script/dom.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index af249adc0d..41aba7766a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -983,8 +983,8 @@ fn on_doc_steps( let len = |p: usize| old.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(p)).map_or(1, |sp| sp.anchors.len().max(1)); let ends = |&(p, k): &(usize, usize)| [(p, k), (p, (k + 1) % len(p))]; - let (left, gone): (BTreeSet<(usize, usize)>, BTreeSet<(usize, usize)>) = - before.segments.remove(&id).into_iter().flatten().partition(|s| segment_left(s)); + let (left, gone) = + before.segments.remove(&id).into_iter().flatten().partition::, _>(|s| segment_left(s)); // The anchors that only ended removed segments are dropped; the ends of the // segments that are left stay selected. let still: HashSet<(usize, usize)> = left.iter().flat_map(ends).collect(); From 75d3fbca6213353b1edafa4cc3b054ccff2e8ff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:43:59 -0800 Subject: [PATCH 032/106] Arrange Tools: Add Artboard Guides keeps its artboard and matches guides with extra anchors The dialog keeps the opening artboard's id and resolves its index for Preview and OK, so reordering artboards while it is open no longer moves the guide to another artboard, and a deleted artboard is an error with no undo step. A guide rectangle with collinear anchors along its sides counts as the same rectangle. Each run walks the guides layer once. The dialog's menu item is available without a selection. --- .../src/cmd/addons/arrange/artboard_guides.rs | 67 +++++++++++----- .../addons/arrange/artboard_guides/tests.rs | 48 +++++++++++ crates/ui-egui/src/addons/arrange.rs | 22 +++++- crates/ui-egui/src/addons/arrange/tests.rs | 79 +++++++++++++++++++ crates/ui-egui/src/addons/dialogs.rs | 34 ++++++-- crates/ui-egui/src/menus/state.rs | 8 +- docs/mcp.md | 5 ++ 7 files changed, 232 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs index 4c4f42d719..98c6598d87 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -5,6 +5,8 @@ #[cfg(test)] mod tests; +use std::collections::HashSet; + use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, Rect, shapes}; @@ -51,40 +53,64 @@ fn guide_layer(d: &Document) -> Option { d.layers.iter().rev().find(|l| matches!(l.kind, NodeKind::Layer { .. }) && l.name.as_deref() == Some(LAYER)).map(|l| l.id) } -/// Does `layer` already hold a guide path with `rect`'s four corners, starting at any corner and -/// running either way round? -fn holds_guide(d: &Document, layer: Option, rect: Rect) -> bool { - let r = rect.abs(); - let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; - layer.and_then(|id| d.node(id)).is_some_and(|n| { - n.try_walk(&mut |c| { - if matches!(&c.kind, NodeKind::Path { path: p, guide: true, .. } if traces(p, &corners)) { - std::ops::ControlFlow::Break(()) - } else { - std::ops::ControlFlow::Continue(()) +/// `r`'s corners as an exact hash key, whichever way round `r` runs. +fn rect_key(r: Rect) -> [u64; 4] { + let r = r.abs(); + [r.x0, r.y0, r.x1, r.y1].map(|v| if v == 0.0 { 0 } else { v.to_bits() }) +} + +#[cfg(test)] +thread_local! { + static GUIDE_NODES_VISITED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn guide_rectangles(d: &Document, layer: Option) -> HashSet<[u64; 4]> { + let mut rects = HashSet::new(); + if let Some(n) = layer.and_then(|id| d.node(id)) { + n.walk(&mut |c| { + #[cfg(test)] + GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1)); + if let NodeKind::Path { path, guide: true, .. } = &c.kind + && let Some(r) = path.bounds() + { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + if traces(path, &corners) { + rects.insert(rect_key(r)); + } } - }) - .is_break() - }) + }); + } + rects } /// Is `path` one closed run of straight segments through `corners`, from any corner, either way round? fn traces(path: &PathData, corners: &[Point; 4]) -> bool { let [sp] = &path.subpaths[..] else { return false }; - if !sp.closed || sp.anchors.len() != 4 { + if !sp.closed || sp.anchors.len() < 4 { return false; } - let mut anchors = sp.anchors.iter(); - let (Some(first), Some(second)) = (anchors.next(), anchors.next()) else { return false }; if sp.anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { return false; } - let (Some(start), Some(next)) = (corners.iter().position(|&c| c == first.p), corners.iter().position(|&c| c == second.p)) else { + let points: Vec = sp + .anchors + .iter() + .enumerate() + .filter_map(|(i, a)| { + let prev = sp.anchors[(i + sp.anchors.len() - 1) % sp.anchors.len()].p; + let next = sp.anchors[(i + 1) % sp.anchors.len()].p; + let interior = (prev.x == a.p.x && a.p.x == next.x && a.p.y > prev.y.min(next.y) && a.p.y < prev.y.max(next.y)) + || (prev.y == a.p.y && a.p.y == next.y && a.p.x > prev.x.min(next.x) && a.p.x < prev.x.max(next.x)); + (!interior).then_some(a.p) + }) + .collect(); + let [first, second, _, _] = &points[..] else { return false }; + let (Some(start), Some(next)) = (corners.iter().position(|c| c == first), corners.iter().position(|c| c == second)) else { return false; }; // 1 runs the way `corners` does, 3 the other way. let step = (next + 4 - start) % 4; - (step == 1 || step == 3) && sp.anchors.iter().enumerate().all(|(k, a)| a.p == corners[(start + k * step) % 4]) + (step == 1 || step == 3) && points.iter().enumerate().all(|(k, p)| *p == corners[(start + k * step) % 4]) } fn artboard_guides(s: &mut Session, p: &Value) -> Result { @@ -113,6 +139,7 @@ fn artboard_guides(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let d = &st.doc; let layer = guide_layer(d); + let mut existing = guide_rectangles(d, layer); let (mut rects, mut skipped) = (Vec::with_capacity(indices.len()), 0); for i in indices { let Some(board) = d.artboards.get(i) else { continue }; @@ -123,7 +150,7 @@ fn artboard_guides(s: &mut Session, p: &Value) -> Result { if !rect_in_range(r) { return Err(bad(C, "the guide would reach past the edge of the canvas")); } - if holds_guide(d, layer, r) || rects.contains(&r) { + if !existing.insert(rect_key(r)) { skipped += 1; } else { rects.push(r); diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs index ba345a85ca..3013130f3f 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -166,6 +166,54 @@ fn a_guide_drawn_the_other_way_round_or_from_another_corner_is_not_added_again() } } +#[test] +fn collinear_midpoints_do_not_add_another_guide_or_history_step() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0); + let points = [ + Point::new(b.center().x, b.y0), + Point::new(b.x1, b.y0), + Point::new(b.x1, b.center().y), + Point::new(b.x1, b.y1), + Point::new(b.center().x, b.y1), + Point::new(b.x0, b.y1), + Point::new(b.x0, b.center().y), + Point::new(b.x0, b.y0), + ]; + for reverse in [false, true] { + let mut points = points.to_vec(); + if reverse { + points.reverse(); + } + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") }; + *path = PathData::single(SubPath::polyline(&points, true)); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1})); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc, before); + } +} + +#[test] +fn every_artboard_shares_one_walk_of_existing_guides() { + let mut s = session(); + s.execute(COMMAND, &json!({"all": true})).unwrap(); + super::GUIDE_NODES_VISITED.with(|count| count.set(0)); + s.execute(COMMAND, &json!({})).unwrap(); + let single = super::GUIDE_NODES_VISITED.with(|count| count.replace(0)); + assert!(single > 0); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({"all": true})).unwrap(); + assert_eq!(super::GUIDE_NODES_VISITED.with(|count| count.get()), single); + assert!(ids(&r).is_empty()); + assert_eq!(r["skipped"], json!(2)); + assert_eq!(steps(&s), n); +} + #[test] fn release_guides_gives_back_a_rectangle_path() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index 9ef6be163a..df763b4425 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -276,12 +276,26 @@ fn guides_params(fields: &DialogFields) -> Value { let all = fields.text("scope") == Some("all"); params.remove("scope"); if all { - params.remove("artboard"); + params.remove("artboardId"); } params.insert("all".into(), json!(all)); Value::Object(params) } +pub(super) fn resolve_guides_artboard(app: &VectorcraftApp, params: &mut Value) -> Result<(), String> { + if params["all"] == true { + return Ok(()); + } + let id = params["artboardId"].as_u64(); + let index = app.session.active().and_then(|st| st.doc.artboards.iter().position(|a| Some(u64::from(a.id)) == id)); + let Some(index) = index else { return Err("The artboard no longer exists.".into()) }; + if let Some(params) = params.as_object_mut() { + params.remove("artboardId"); + params.insert("artboard".into(), json!(index)); + } + Ok(()) +} + /// Opens the dialog of command `id` on the active document; `None` for another command and without a document. pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option> { let &(command, _) = DIALOGS.iter().find(|(command, _)| *command == id)?; @@ -322,10 +336,12 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option ( guides_rows(lengths), - json!({ "offset": 0, "scope": "active", "artboard": crate::panels::artboards::selected(app, st.doc.artboards.len()) }), + json!({ + "offset": 0, "scope": "active", + "artboardId": st.doc.artboards.get(crate::panels::artboards::selected(app, st.doc.artboards.len())).map(|a| a.id), + }), ), MARKS => (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })), // The first selected object's size, as the command measures it (a side it lacks: the least). diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index fa360d6f6e..2e9beac838 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -241,6 +241,85 @@ fn add_artboard_guides_does_not_open_without_artboards() { assert!(!app.any_dialog_open()); } +#[test] +fn add_artboard_guides_keeps_the_opening_artboard_after_reordering() { + for preview in [false, true] { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + app.view_mut().unwrap().artboard = 0; + let board = app.session.doc().unwrap().doc.artboards[0].rect; + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "preview", json!(preview)); + if preview { + host::frame(&mut app); + app.session.cancel_interaction().unwrap(); + } + app.run("artboard.reorder", json!({"index": 0, "to": 1})).unwrap(); + let n = steps(&app); + if preview { + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![board]); + assert_eq!(steps(&app), n); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![board]); + assert_eq!(steps(&app), n + 1); + } +} + +#[test] +fn add_artboard_guides_does_not_replace_a_deleted_artboard_with_its_neighbor() { + for preview in [false, true] { + let (mut app, _, _) = app(); + app.run("artboard.new", json!({"x": 600, "y": 0, "width": 200, "height": 100})).unwrap(); + app.view_mut().unwrap().artboard = 0; + click(&mut app, "Add Artboard Guides…"); + let id = host::dialog_id(&app); + host::set(&app, id, "preview", json!(preview)); + if preview { + host::frame(&mut app); + app.session.cancel_interaction().unwrap(); + } + app.run("artboard.delete", json!({"index": 0})).unwrap(); + let (before, n) = (app.session.doc().unwrap().doc.clone(), steps(&app)); + if preview { + host::frame(&mut app); + assert!(artboard_guides(&app).is_empty()); + assert_eq!(steps(&app), n); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(artboard_guides(&app).is_empty()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(steps(&app), n); + assert_eq!(app.ui.status, "The artboard no longer exists."); + } +} + +#[test] +fn artboard_guides_menu_dialog_is_available_without_a_selection() { + let (mut app, _, _) = app(); + app.run("select.none", json!({})).unwrap(); + assert!(menus::enabled(&app, "ui.menuDialog")); + let guides = json!({"command": "addon.arrange.artboardGuides"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &guides).map(|s| s.0), Some(true)); + let transform = json!({"command": "object.move"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(false)); + let grid = json!({"command": "addon.arrange.grid"}); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(false)); + app.run("select.all", json!({})).unwrap(); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &transform).map(|s| s.0), Some(true)); + assert_eq!(menus::shown_state(&app, "ui.menuDialog", &grid).map(|s| s.0), Some(true)); + app.run("select.none", json!({})).unwrap(); + app.run("ui.menuDialog", guides).unwrap(); + let id = host::dialog_id(&app); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(artboard_guides(&app), vec![app.session.doc().unwrap().doc.artboards[0].rect]); +} + #[test] fn add_artboard_guides_uses_the_artboard_the_view_shows() { let (mut app, _, _) = app(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 18816efa11..0d21c2dc32 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -29,6 +29,16 @@ pub(crate) struct Spec { pub found: Option, } +impl Spec { + fn params(&self, app: &VectorcraftApp, fields: &DialogFields) -> Result { + let mut params = (self.params)(fields); + if self.command == "addon.arrange.artboardGuides" { + super::arrange::resolve_guides_artboard(app, &mut params)?; + } + Ok(params) + } +} + /// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document. #[derive(Default)] pub(crate) struct AddonDialogs { @@ -140,11 +150,19 @@ fn pump_commit(app: &mut VectorcraftApp) { app.addon_dialogs.preview = LivePreview::default(); app.addon_dialogs.preview_error = None; } - let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); + let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), spec.params(app, d.fields())))); if on_document && let Some((previewing, params)) = &live { let mut preview = mem::take(&mut app.addon_dialogs.preview); let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); - let answer = preview.run(app, *previewing, label, spec.command, params); + let answer = match params { + Ok(params) => preview.run(app, *previewing, label, spec.command, params), + Err(error) => { + preview.cancel(app); + preview = LivePreview::default(); + app.status(error.clone()); + Some(Err(error.clone())) + } + }; app.addon_dialogs.preview = preview; if spec.command == super::select::points_only::COMMAND { match &answer { @@ -171,11 +189,13 @@ fn pump_commit(app: &mut VectorcraftApp) { } else if !on_document { app.status("The add-on settings apply only to the drawing where the dialog opened."); } else { - let params = (spec.params)(&result.fields); - let answer = if spec.command == super::select::points_only::COMMAND { - preview.commit_selection(app, spec.command, params) - } else { - preview.commit(app, spec.command, params) + let answer = match spec.params(app, &result.fields) { + Ok(params) if spec.command == super::select::points_only::COMMAND => preview.commit_selection(app, spec.command, params), + Ok(params) => preview.commit(app, spec.command, params), + Err(error) => { + preview.cancel(app); + Err(error) + } }; if let Err(error) = answer { app.status(error); diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 6ae7c66be0..a174769e60 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -186,6 +186,12 @@ pub(crate) fn shown_state_with( why_off: &mut dyn FnMut(&str) -> Option>, ) -> Option<(bool, Option)> { let en = why_off(id).is_none() + && (id != "ui.menuDialog" + || if p.get("command").and_then(Value::as_str) == Some("addon.arrange.artboardGuides") { + why_off("addon.arrange.artboardGuides").is_none() + } else { + app.session.active().is_some_and(|d| !d.selection.is_empty()) + }) && (id != crate::addons::select::link_status::COMMAND || crate::addons::select::link_status::enabled(app, p)) && (!vectorcraft_engine::cmd::plugin::is_command_id(id) || crate::dialogs::plugin::canvas_item_enabled(app, id, p)); if (!en && hidden_when_disabled(id)) || swapped_out(id, why_off) || east_asian_hidden(app, id) { @@ -416,7 +422,7 @@ fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.saveBrushLibrary" => crate::panels::brushes::has_brushes(app), id if id.starts_with(crate::panels::brushes::USER_SLOT) => crate::panels::brushes::user_library(app, id).is_some(), "ui.spotColors" => app.session.active().is_some(), - "ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()), + "ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty() || !d.doc.artboards.is_empty()), "ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app), "ui.smoothAuto" => crate::dialogs::smooth_slider::showing(app), "ui.recolorUndo" => crate::dialogs::recolor::can_step(app, true), diff --git a/docs/mcp.md b/docs/mcp.md index 705f10c92d..a619275594 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17990,6 +17990,11 @@ with strokes and vector effects included and raster effects left out (see its ro | `addon.arrange.artboardGuides` | `offset` pt −1000000…1000000 (0: on the artboard's edges; more than 0 outside them, less than 0 inside); `artboards` [index…] (0-based; the active artboard); `artboard` index (the active artboard, which the app passes; the view's when left out, and the journal then records it for a replay); `all` (false; true: every artboard; not with `artboards`) | Adds a rectangular guide path around each of those artboards, `offset` from its edges, on the topmost top-level layer named Artboard Guides (made above the other layers when there is none; it keeps its lock and visibility). It acts on artboards, not on the selection. The guides have the current paint, which `view.guides.release` gives back with the path. A guide anywhere in that layer with the same rectangle is not added again, and a run that adds none makes no step. An inset that leaves an artboard no width or no height, and a guide edge more than 4,000,000 pt from the origin, are errors. Off without artboards. → `{ids, layer, skipped}` | | `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | +`ui.menuDialog {command: "addon.arrange.artboardGuides"}` is available without a selection. The dialog keeps the +opening artboard's id and resolves its current index for Preview and OK. If that artboard was deleted, Preview and +OK report an error without adding a guide or an undo step. A guide with extra anchors along its sides counts as the +same rectangle. + Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, and fails with nothing selected. Add Artboard Guides… opens a dialog with Offset and Artboards (Active Artboard, or All From df3950f5759d79bc3391690f530a893ab2820126 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:12:47 -0800 Subject: [PATCH 033/106] Import PDF: linked pages keep an explicit Crop Box for a file with editing data With Import PDF Pages as Links on, a file with editing data opened every page on its trim box even when Crop Box was picked: document.open's linkPages path turned a crop-box request into a trim box without asking whether the box was named. A request that names the crop box (cropTo or crop) now keeps the crop boxes; a file that names no box still opens on its trim boxes, as it does when opened as art. Follows #7723. --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/pdfimport.rs | 11 ++-- crates/engine/src/tests/placed_document.rs | 62 ++++++++++++++++++++++ docs/mcp.md | 9 ++-- 4 files changed, 74 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index e902f4185a..7e7340989a 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF or PDF-compatible .ai with its editor's private data uses trim boxes when no box is named; an explicit crop uses crop boxes), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF or PDF-compatible .ai with its editor's private data: its trim box when no box is named; a PDF with only a VectorCraft native attachment: its crop box by default; an explicit crop: its crop box; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 954a345ae0..005cc4a557 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -176,8 +176,8 @@ impl LoadOptions { self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages } - /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible - /// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default, + /// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible + /// `.ai` with Illustrator private data opens on its trim boxes by default, /// with the bleed around them. An explicit crop-box request uses its crop box. fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { @@ -257,7 +257,7 @@ pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page /// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box; -/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the +/// a PDF-compatible `.ai` that names no box gets its trim box, as it opens), in a row from the /// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box, /// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the /// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens @@ -289,8 +289,9 @@ pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &Loa Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?, }; let bounding = o.crop == CropTo::Bounding; - // A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]). - let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop }; + // A PDF-compatible `.ai` that names no box opens on its trim boxes ([`LoadOptions::import_options`]); + // an explicit crop-box request keeps its crop boxes. + let crop = if !o.explicit_crop_box && o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop }; let mut doc = Document::new(1.0, 1.0); let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?; doc.artboards.clear(); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 3dd4959489..5166c820c4 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -731,6 +731,68 @@ fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() { assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins"); } +#[test] +fn linked_pages_of_a_file_with_editing_data_keep_an_explicit_crop_box() { + let dir = Folder::new("open-pdf-link-pages-explicit-crop"); + let src = dir.file("editable.ai"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": src, "format": "ai", "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&src).unwrap(), None)); + let board = |s: &Session| { + let r = s.doc().unwrap().doc.artboards[0].rect; + (r.width(), r.height()) + }; + // No box named: the trim box, as the file opens as art. + s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); + // An explicit crop box is the crop box, which takes in the bleed. + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "crop"})).unwrap(); + let (w, h) = board(&s); + assert!(w > 100.0 && h > 50.0, "{w} x {h}"); + s.execute("document.open", &json!({"path": src, "linkPages": true, "crop": "crop"})).unwrap(); + assert_eq!(board(&s), (w, h)); +} + +#[test] +fn linked_pages_with_only_a_native_attachment_default_to_crop_boxes() { + let dir = Folder::new("open-pdf-link-pages-native-crop"); + let src = dir.file("editable.pdf"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "document.exportPdf", + &json!({"path": src, "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + let bytes = std::fs::read(&src).unwrap(); + assert!(vectorcraft_pdf::editing(&bytes).is_some_and(|e| e.intact)); + assert!(!vectorcraft_pdf::has_illustrator_data(&bytes, None)); + let board = |s: &Session| { + let r = s.doc().unwrap().doc.artboards[0].rect; + (r.width(), r.height()) + }; + s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap(); + let (w, h) = board(&s); + assert!(w > 100.0 && h > 50.0, "{w} x {h}"); + for key in ["cropTo", "crop"] { + let mut params = json!({"path": src, "linkPages": true}); + params[key] = json!("crop"); + s.execute("document.open", ¶ms).unwrap(); + assert_eq!(board(&s), (w, h), "{key}"); + } + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "trim"})).unwrap(); + assert_eq!(board(&s), (100.0, 50.0)); +} + #[test] fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() { use vectorcraft_testkit::pdf::{PdfPage, pdf}; diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..7f0b7c3aa1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1744,8 +1744,8 @@ unknown label is refused. The `warnings` of the result name the first three such Opening a PDF (or `.ai`) imports every page as an artboard and layer; `document.open` takes `pages` ("2-3, 5", 1-based), `cropTo` (`bounding` (the art's bounds), `art`, `crop` (default), `trim`, `bleed`, `media`: the box each artboard gets; -with `trim` the bleed box round it becomes the document's bleed and the artboards are 36 pt apart plus that bleed on both sides, and a PDF-compatible `.ai` or a PDF saved with its editing data opens on its trim boxes for -`crop`, its crop box taking the bleed in) and `password` for an encrypted file. `document.pdfInfo` reads a file without opening it: the page count, each page's +with `trim` the bleed box round it becomes the document's bleed and the artboards are 36 pt apart plus that bleed on both sides; a PDF or PDF-compatible `.ai` with Illustrator private data uses trim boxes when no box is named; +an explicit `crop` uses crop boxes) and `password` for an encrypted file. `document.pdfInfo` reads a file without opening it: the page count, each page's size and boxes, `needsPassword`, and with `thumbnail: n` a PNG of page n. It reads a PostScript file (an EPS, a `.ps` file, a `.ai` in PostScript form) as one page the size of its bounding box (a US Letter page without one), with an empty `boxes`, and `thumbnail: 1` shows what that page prints. A page whose `UserUnit` (PDF 1.6) is above 1 @@ -1755,8 +1755,9 @@ such a page opens from that data at the page's size. `linkPages: true` (File › Open's Import PDF dialog: Import PDF pages as links) opens each page `pages` picks as a placed document linked to that page of the file, as `file.place` with `link` places one, instead of as editable art. Each page gets an artboard of its `cropTo` box (`bounding`: its art's bounds; a blank page gets its crop box), in a row from the left 36 pt apart, and -a layer named after the page (`Page 2`). A PDF-compatible `.ai` with `cropTo: "crop"` gets its trim boxes, as it does -when it opens as art. A page on its trim box shows its bleed box round the artboard, and the pages give the document +a layer named after the page (`Page 2`). A PDF or PDF-compatible `.ai` with Illustrator private data +that names no box gets its trim boxes, as it does when it opens as art. A PDF with only a VectorCraft native attachment (Preserve Editing) defaults to crop boxes for linked pages. +`cropTo: "crop"` (or `crop: "crop"`) gives either file its crop boxes. A page on its trim box shows its bleed box round the artboard, and the pages give the document their bleed; the artboards are then 36 pt apart plus the bleed on both sides. The document opens in CMYK when most of those pages are painted mostly in CMYK, unless `colorMode` names a mode. All the pages' objects share one copy of the file. The Links panel lists each page, and `links.embed` makes a page editable art. The command's `linkPages` defaults to false; the dialog checks the From fa659626b948063af57b3929c94d64d003ed0561 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:58:07 -0800 Subject: [PATCH 034/106] Docs: the deleted-artboard error applies to Active Artboard only With All Artboards, Add Artboard Guides acts on the artboards the document has when Preview or OK runs, so a deleted opening artboard is not an error there. --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index a619275594..ab24cc4fa6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17991,8 +17991,9 @@ with strokes and vector effects included and raster effects left out (see its ro | `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | `ui.menuDialog {command: "addon.arrange.artboardGuides"}` is available without a selection. The dialog keeps the -opening artboard's id and resolves its current index for Preview and OK. If that artboard was deleted, Preview and -OK report an error without adding a guide or an undo step. A guide with extra anchors along its sides counts as the +opening artboard's id and resolves its current index for Preview and OK. With Active Artboard, if that artboard was +deleted, Preview and OK report an error without adding a guide or an undo step; All Artboards acts on the artboards +the document has then. A guide with extra anchors along its sides counts as the same rectangle. Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the From 8930d9d5dc91ca8fe4d7d965479151851df713ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:31:07 -0800 Subject: [PATCH 035/106] Scripts: say the Color Picker's CMYK rule applies in the app An answer to app.showColorPicker taken from script.run's answers keeps the color model it was given; only the app's picker returns an RGB pick as CMYK in a CMYK document. --- docs/mcp.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 8907f40796..fed7676f0a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4011,9 +4011,10 @@ empty object are the same. `app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, `CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a -`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; when the -run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so the -color's `typename` can differ from the picker's model and from the color given. The picker opens on the color as +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in the app, +when the run's active document (a document the script made included) is in CMYK, an RGB pick is returned as CMYK, so +the color's `typename` can differ from the picker's model and from the color given. An answer taken from `answers` +keeps the color model it was given. The picker opens on the color as given, whatever Only Web Colors was left at in another picker. OK with the color unchanged and Cancel return a new object of the color the script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting end the run as they do at the other dialogs, and close the picker. They also end a screen color sample From 627503719246eb95812104a501f28709a8dbadde Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 13:31:26 -0800 Subject: [PATCH 036/106] New Document: Background Contents shows its color chip again The port of New Document to the framework dialog dropped the chip that stood after the Background Contents list, so the list stood alone. A framework paint chip now follows the list in the same row: white for White, and the No Color slash for Transparent. The chip only shows the choice and opens no popover. Screen readers name it "Background Contents swatch" with the paint as its value. The test checks that the chip follows the list in its row inside the dialog and that its value changes from No Color to a color when the background is set to White. --- crates/ui-egui/src/dialogs/new_document.rs | 60 ++++++++++++++++++++-- 1 file changed, 55 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 39337a0439..5a3b01c0c9 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -21,6 +21,8 @@ use vectorcraft_doc::{Background, ColorMode, Unit}; use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, ProfileFile, RASTER_PPI}; use craft::behavior::{ColumnWidth, IconId}; +use craft::color_ui::ui::{Paint, PaintChip, PaintChipSize}; +use craft::theme::Srgba; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Segmented}; use craft::ui::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, clicked}; @@ -342,12 +344,16 @@ impl DocumentSettings for VcNewDocument { let bleed = text(tl!("Bleed")); Field::new(bleed.clone()).layout(FieldLayout::Above).id_salt("bleed").show(ui, |ui, _| bleed_row(ui, s, &mut memory, lengths, compact)); + // The list with a chip after it: white, or No Color's slash for transparent. Field::new(background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| { - let entries: Vec> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect(); - let select = Select::new(background.clone(), Bind::given(s.background), &entries).sizing(Sizing::FillWidth); - if let Some(b) = select.show(ui).events.committed().copied() { - s.background = b; - } + Row::new().show(ui, |ui, _| { + let entries: Vec> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect(); + let select = Select::new(background.clone(), Bind::given(s.background), &entries).sizing(Sizing::FillWidth); + if let Some(b) = select.show(ui).events.committed().copied() { + s.background = b; + } + background_chip(ui, s.background); + }); }); Section::new(text(tl!("Advanced Options"))).initially_open(false).show(ui, |ui, _| advanced(ui, s)); @@ -405,6 +411,17 @@ fn built_in_card(preset: &DocSettings, values: &VcNewDocument, orientation: Opti DocumentCard::new(text(preset_name(&preset.name)), line, value, CardSource::preset(None)) } +/// The chip after Background Contents: the paper white, or No Color for transparent. It shows the choice and opens +/// nothing. +fn background_chip(ui: &mut egui::Ui, background: Background) { + let paint = match background { + Background::White => Paint::Solid(Srgba::WHITE), + Background::Transparent => Paint::None, + }; + let name = crate::i18n::fmt(tl!("{row} swatch"), &[("row", tl!("Background Contents"))]); + PaintChip::new(name, Bind::given(paint), Srgba::WHITE).popover(false).chip_size(PaintChipSize::Swatch).show(ui); +} + /// A label with the text `s`, already translated. fn text(s: &str) -> Label { Label::from(s.to_owned()) @@ -1606,6 +1623,39 @@ mod tests { assert!(sides[3].x1 <= link.x0, "the link button {link:?} ends the Bleed row {sides:?}"); } + /// A chip follows Background Contents in its row: No Color while the list says Transparent, white once it says + /// White. Before, the list stood alone. + #[test] + fn new_document_background_contents_shows_its_chip() { + use egui::accesskit::Role; + let chip_name = "Background Contents swatch"; + let mut app = app(); + open(&mut app); + let look = |app: &mut VectorcraftApp| { + let out = laid_out_in(app, egui::vec2(1280.0, 900.0)); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + let find = |name: &str, role: Role| { + nodes + .iter() + .find(|(_, n)| n.role() == role && n.label() == Some(name)) + .map(|(_, n)| (n.bounds().expect("laid out"), n.value().map(str::to_owned))) + .unwrap_or_else(|| panic!("no {role:?} {name}")) + }; + let (list, _) = find("Background Contents", Role::ComboBox); + let (chip, value) = find(chip_name, Role::ColorWell); + let dialog = nodes.iter().find(|(_, n)| n.role() == Role::Dialog).and_then(|(_, n)| n.bounds()).expect("the dialog"); + assert!(list.x1 <= chip.x0, "the chip {chip:?} follows the list {list:?}"); + assert!(chip.y0 < list.y1 && list.y0 < chip.y1, "the chip {chip:?} shares the list's row {list:?}"); + assert!(chip.x1 <= dialog.x1, "the chip {chip:?} ends inside the dialog {dialog:?}"); + value.expect("the chip names its paint") + }; + let transparent = look(&mut app); + set(&app, "backgroundContents", json!("white")).unwrap(); + let white = look(&mut app); + assert_eq!(transparent, "No Color", "Transparent shows No Color"); + assert_ne!(white, transparent, "White shows a color, not No Color"); + } + /// Turning the Bleed link on sets every side to Top's bleed; unlinking keeps the four values. #[test] fn new_document_bleed_link_turned_on_sets_every_side_to_top() { From c9ef0845a553eecc0a3d87f84638f7f9a6931587 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:04:50 -0800 Subject: [PATCH 037/106] xtask: test-lint census rule follows closure writes, async blocks and nested guards The census rule leaves out a loop that feeds each entry into a computation, so it needs to know which calls and assignments in the loop body run. It misjudged these shapes: - A parameter of an async closure (`async |mut c: Command| { ... }`) or one whose type contains `->` did not shadow the entry. - An async block awaited where it is written (`async { ... }.await`, `(async { ... }).await`) or passed straight to `block_on` counted as never run, for both calls and assignments. An `||` before it still guards it, and an `async move` block still writes only its own copies. - An inner binding assigned the entry stayed hidden by a shadow of an outer binding of the same name. - `ready || accept({ 0 }, wrap(app.run(c)))` lost the `||` guard. - A closure with parameters stored in `Some(...)` counted as called. - A closure call was found past the end of the block that binds the closure. - An assignment in a closure dropped with `let _` or stored in parentheses (`let _saved = (|| { ... });`) ended the entry alias. - An assignment in a closure that is called only conditionally kept the alias. Assignments now use a "may run" mode of the same check that finds calls, so a call that may be skipped still counts and a call that can never run does not. --- xtask/src/test_lint.rs | 475 ++++++++++++++++++++++++++++++++++------- 1 file changed, 403 insertions(+), 72 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e517292e73..1485cfc600 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2163,19 +2163,13 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { if b[at] != b'|' || b.get(at + 1) == Some(&b'|') { continue; } - let head = b[from..at].trim_ascii_end(); - let head = head.strip_suffix(b"move").unwrap_or(head).trim_ascii_end(); + // `move` and `async` may come before the parameters (`async |mut c: Command| …`). + let text = String::from_utf8_lossy(b[from..at].trim_ascii_end()); + let head = strip_closure_keywords(&text).0.as_bytes(); if !head.is_empty() && !matches!(head.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) { continue; } - let Some(end) = (at + 1..to).find(|&i| b[i] == b'|') else { continue }; - // Parameters may carry types (`|c: Command|`, `|p: &[u8]|`). - if !b[at + 1..end] - .iter() - .all(|&c| is_ident(c) || c.is_ascii_whitespace() || matches!(c, b',' | b'&' | b':' | b'<' | b'>' | b'(' | b')' | b'[' | b']' | b'\'')) - { - continue; - } + let Some(end) = closure_params_end(b, at, to) else { continue }; let mut until = skip_ws(b, end + 1); if b.get(until) == Some(&b'{') { until = matching(b, until).unwrap_or(to).min(to); @@ -2268,18 +2262,25 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { .max_by_key(|&(since, _)| since) .map_or(to, |(_, until)| until); // Assignments in move closures leave outer bindings unchanged. Assignments in async - // blocks or uncalled closures do not run; conditional assignments do not make aliases. - if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || in_uncalled_closure(b, from, to, at, &[]) { + // blocks that are not awaited, or in closures that nothing calls, do not run; + // conditional assignments do not make aliases. + if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || !runs_with_assertion_within(b, from, to, at, &[], true) { continue; } if live(value_start(eq, end), end, &derived, &shadows) { if !runs_with_assertion(b, from, to, at) { continue; } - // Assigning the entry again ends what earlier assignments in the same scope stored. - for s in shadows.iter_mut().filter(|s| s.0 == name && s.1 <= at && at < s.2 && s.2 == until) { + // Assigning the entry again ends what earlier assignments in the same scope stored, + // and suspends the shadows of outer bindings of the name until this binding's scope ends. + let mut resumed = vec![]; + for s in shadows.iter_mut().filter(|s| s.0 == name && s.1 <= at && at < s.2 && s.2 >= until) { + if until < s.2 { + resumed.push((s.0.clone(), until, s.2)); + } s.2 = end; } + shadows.extend(resumed); derived.push((name, end, until)); } else if derived.iter().any(|(d, _, _)| *d == name) && !empty_bodies.iter().any(|&(open, close)| open < at && at < close) { shadows.push((name, end, until)); @@ -2523,18 +2524,18 @@ fn call_name_end(b: &[u8], from: usize, open: usize) -> Option { /// that closure ([`closure_calls`]), and a call in a closure that is not bound does not count. A call /// in a nested `for` body counts only when the loop's source yields an item ([`literal_source_yields`]). fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { - runs_with_assertion_within(b, from, to, start, &[]) + runs_with_assertion_within(b, from, to, start, &[], false) } -/// [`runs_with_assertion`], where `active` holds the calls whose check is in progress, so a closure -/// that calls itself does not recurse without end. -fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { +/// Checks whether `start` runs whenever assertions pass, or may run at all when `may_run` is true. +/// `active` holds positions being checked so recursive closure calls terminate. +fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize], may_run: bool) -> bool { if active.contains(&start) { return false; } let mut active = active.to_vec(); active.push(start); - if in_uncalled_closure(b, from, to, start, &active) { + if in_uncalled_closure(b, from, to, start, &active, may_run) { return false; } // Check enclosing blocks independently of the call's statement: an earlier semicolon inside @@ -2555,21 +2556,31 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac _ => {} } } + let prefix_at = skip_ws(b, head).min(open); let prefix = b[head..open].trim_ascii(); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); + // Where the `async` of an async block starts. + let async_kw = [b"async".as_slice(), b"async move"] + .iter() + .find(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident)) + .map(|kw| prefix_at + prefix.len() - kw.len()); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { - if !runs_with_assertion_within(b, from, to, open, &active) { + if !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; } - } else if nested_for && literal_source_yields(prefix) != Some(true) { + } else if nested_for && !literal_source_yields(prefix).unwrap_or(may_run) { // A nested `for` body runs only when its source yields an item. return false; - } else if !prefix.ends_with(b"|") + } else if let Some(kw) = async_kw { + // An async block needs polling where it is written, by await or block_on. + let polled = polled_in_place(b, from, kw, open); + if !polled || !runs_with_assertion_within(b, from, to, kw, &active, may_run) { + return false; + } + } else if !may_run + && !prefix.ends_with(b"|") && !nested_for && (prefix.ends_with(b"=>") - || [b"async".as_slice(), b"async move"] - .iter() - .any(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident)) || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) || (!words(prefix, b"loop", 0, prefix.len()).is_empty() && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) @@ -2583,10 +2594,12 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac // the operand of `||` or `&&`. let mut stmt = from; let mut braces = 0usize; - // The parenthesis or bracket that most closely encloses the call: a block after it is an - // earlier argument or element (`accept({ 0 }, app.run(c))`), not an earlier statement. - let group = (from..start).rev().find(|&i| matches!(b[i], b'(' | b'[' | b'{') && matching(b, i).is_none_or(|close| start < close)); - let group = group.filter(|&i| b[i] != b'{'); + // The outermost parenthesis or bracket that encloses the call inside its innermost block: a block + // after it is an earlier argument or element (`accept({ 0 }, app.run(c))`, also + // `accept({ 0 }, wrap(app.run(c)))`), not an earlier statement. + let encloses = |i: usize| matching(b, i).is_none_or(|close| start < close); + let block = (from..start).rev().find(|&i| b[i] == b'{' && encloses(i)); + let group = (block.map_or(from, |open| open + 1)..start).find(|&i| matches!(b[i], b'(' | b'[') && encloses(i)); for i in (from..start).rev() { match b[i] { b'}' if braces == 0 && group.is_some_and(|g| g < i) => braces += 1, @@ -2621,21 +2634,27 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac // otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`. // Earlier sibling elements cannot skip the call, but guards around their group still can. let mut depth = 0usize; - let params = (stmt..start).find_map(|pipe| { - if b[pipe] != b'|' { - return None; - } - let head = String::from_utf8_lossy(b[stmt..pipe].trim_ascii()); - let head = strip_closure_keywords(&head).0.as_bytes(); - if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) { - return None; - } - (pipe + 1..start).find(|&end| b[end] == b'|').map(|end| (pipe, end)) - }); - let mut closure = params.map(|(pipe, _)| pipe); + // The parameter lists of closures with parameters (`let run = |c: Command| …`, + // `Some(|_: ()| …)`): a `|` where an expression starts, up to the next `|`. + let params: Vec<(usize, usize)> = (stmt..start) + .filter(|&pipe| b[pipe] == b'|' && b.get(pipe + 1) != Some(&b'|') && pipe.checked_sub(1).is_none_or(|p| b[p] != b'|')) + .filter(|&pipe| { + let head = String::from_utf8_lossy(b[stmt..pipe].trim_ascii()); + let head = strip_closure_keywords(&head).0.as_bytes(); + head.is_empty() + || matches!(head.last(), Some(b'(' | b'[' | b'{' | b',')) + || head.ends_with(b"=") && !matches!(head.get(head.len().wrapping_sub(2)), Some(b'=' | b'!' | b'<' | b'>')) + }) + .filter_map(|pipe| closure_params_end(b, pipe, start).map(|end| (pipe, end))) + .collect(); + let mut closure = None; let mut sibling = false; for i in (stmt + 1..start).rev() { - if params.is_some_and(|(pipe, end)| pipe <= i && i <= end) { + if let Some(&(pipe, _)) = params.iter().find(|&&(pipe, end)| pipe <= i && i <= end) { + // A closure that encloses the call at its own level, not a sibling element. + if i == pipe && depth == 0 && !sibling { + closure = Some(pipe); + } continue; } match b[i] { @@ -2656,7 +2675,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>') { break; } - if b[i] == b'&' + if !may_run + && b[i] == b'&' && b[i - 1] == b'&' && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) && !asserted_conjunction(b, from, to, i - 1) @@ -2672,6 +2692,9 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac && !asynchronous && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) { + if may_run { + continue; + } return false; } closure = Some(stmt + prefix.len()); @@ -2683,29 +2706,19 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let head = String::from_utf8_lossy(&b[stmt..end]); let (bare, asynchronous) = strip_closure_keywords(head.trim_end()); // Unwrap parentheses whose outer closing parenthesis ends the initializer. - let unwrapped = (|| { - let mut head = bare; - let mut inner_close = None; - while let Some(prefix) = head.strip_suffix('(') { - let close = matching(b, stmt + prefix.len())?; - if close < start || inner_close.is_some_and(|inner| !b[inner + 1..close].trim_ascii().is_empty()) { - return None; - } - inner_close = Some(close); - head = prefix.trim_end(); - } - inner_close.filter(|&close| b.get(skip_ws(b, close + 1)) == Some(&b';')).map(|_| head) - })(); + let unwrapped = parenthesized_closure_binding_head(b, stmt, start, bare); let binding_head = unwrapped.unwrap_or(bare); let Some(binding) = binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| h.starts_with(char::is_whitespace)) else { + // Other callees may invoke or retain a callback, but an unused constructor only stores it. + let may_call = may_run && !asynchronous && closure_body_end(b, end, to).is_some_and(|close| !stored_closure(b, bare, close, to)); // `(|| app.run(c))()` calls the closure where it is written. let open = stmt + bare.len(); - let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return false }; + let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return may_call }; let call = skip_ws(b, close + 1); if b.get(call) != Some(&b'(') { - return false; + return may_call; } // An async closure's future runs when it is passed straight to `block_on` or awaited. A `|` // before `block_on` may open a closure around it (`let _saved = || block_on(…);`) that @@ -2726,7 +2739,50 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac return b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident); }; let Some(name) = pattern_names(binding).last() else { return false }; - closure_calls(b, &name, skip_ws(b, stmt), end, to, asynchronous).into_iter().any(|at| runs_with_assertion_within(b, from, to, at, &active)) + closure_calls(b, &name, skip_ws(b, stmt), end, to, asynchronous) + .into_iter() + .any(|at| runs_with_assertion_within(b, from, to, at, &active, may_run)) +} + +/// Finds the last non-whitespace byte of the closure body after the parameters opened at `pipe`. +fn closure_body_end(b: &[u8], pipe: usize, to: usize) -> Option { + let body = skip_ws(b, closure_params_end(b, pipe, to)? + 1); + let mut after = body; + while after < to && !matches!(b[after], b',' | b';' | b')' | b']' | b'}') { + let next = skip_turbofish(b, after); + after = if next != after { + next + } else if matches!(b[after], b'(' | b'[' | b'{') { + matching(b, after).unwrap_or(to) + 1 + } else { + after + 1 + }; + } + let close = body + b[body..after.min(to)].trim_ascii_end().len(); + (close > body).then(|| close - 1) +} + +/// The head before parentheses around a closure initializer, when each pair encloses `start` +/// and the outer closing parenthesis ends the statement. +fn parenthesized_closure_binding_head<'a>(b: &[u8], stmt: usize, start: usize, mut head: &'a str) -> Option<&'a str> { + let mut inner_close = None; + while let Some(prefix) = head.strip_suffix('(') { + let close = matching(b, stmt + prefix.len())?; + if close < start || inner_close.is_some_and(|inner| !b[inner + 1..close].trim_ascii().is_empty()) { + return None; + } + inner_close = Some(close); + head = prefix.trim_end(); + } + inner_close.filter(|&close| b.get(skip_ws(b, close + 1)) == Some(&b';')).map(|_| head) +} + +/// The `|` that closes the closure parameter list opened by the `|` at `pipe`, before `to`, when the +/// text between them can be a parameter list. Parameters may carry types (`|c: Command|`, +/// `|p: &[u8; 4]|`, `|f: fn() -> bool|`), but not a block, a string, a method call or an assignment. +fn closure_params_end(b: &[u8], pipe: usize, to: usize) -> Option { + let end = (pipe + 1..to).find(|&i| b[i] == b'|')?; + (!b[pipe + 1..end].iter().any(|c| matches!(c, b'{' | b'}' | b'"' | b'.' | b'='))).then_some(end) } /// The head before a closure's parameters with a trailing `move` and `async` removed, and whether @@ -2744,10 +2800,12 @@ fn strip_closure_keywords(head: &str) -> (&str, bool) { } /// Where `b[after..to]` calls the closure that the `let` at `bound` binds to `name`: `name(…)`, not -/// a method (`other.run()`), and not after a later `let` of the same name that is still in scope. -/// Calling an async closure only makes a future, so its call counts only when the future is -/// awaited (`run().await`) or passed to `block_on`. +/// a method (`other.run()`), not after the end of the block that holds the `let`, and not after a +/// later `let` of the same name that is still in scope. Calling an async closure only makes a +/// future, so its call counts only when the future is awaited (`run().await`) or passed to +/// `block_on`. fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, asynchronous: bool) -> Vec { + let to = to.min(block_close(b, bound)); let rebinds = |l: usize, at: usize| { let eq = (l + 3..at).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')); // The new name is in scope from the end of its statement (`let run = run();` still calls the @@ -2776,6 +2834,15 @@ fn closure_calls(b: &[u8], name: &str, bound: usize, after: usize, to: usize, as .collect() } +/// Whether the expression `b[start..end]` is the only argument of a `block_on` call +/// (`block_on(run())`, also `block_on (run())`, `executor::block_on(run())` or with a trailing +/// comma), not of another function whose name ends in `block_on`. +fn passed_to_block_on(b: &[u8], start: usize, end: usize) -> bool { + let Some(open) = b[..start].trim_ascii_end().len().checked_sub(1).filter(|&o| b[o] == b'(') else { return false }; + b[..open].trim_ascii_end().strip_suffix(b"block_on").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) + && matching(b, open).is_some_and(|close| close >= end && matches!(b[end..close].trim_ascii(), b"" | b",")) +} + /// Whether an `&&` is at the top level of an assertion's first argument. fn asserted_conjunction(b: &[u8], from: usize, to: usize, at: usize) -> bool { macro_calls(b, from, to).iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())).any(|a| { @@ -2813,13 +2880,41 @@ fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: b.get(open) == Some(&b'(') && matching(b, open) == close.checked_sub(1) && required_conjunction(b, open, close, at, depth + 1) } -/// Whether `start` lies in the body of an `async` or `async move` block. +/// Whether `start` lies in the body of an `async move` block, which writes to its own copies of the +/// captures, or of an `async` block that is not polled where it is written ([`polled_in_place`]). fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { - (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { - let head = b[from..open].trim_ascii_end(); - let head = head.strip_suffix(b"move").filter(|h| h.last().is_some_and(u8::is_ascii_whitespace)).unwrap_or(head).trim_ascii_end(); - head.strip_suffix(b"async").is_some_and(|h| !h.last().copied().is_some_and(is_ident)) - }) + (from..start) + .filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) + .any(|open| async_block_keyword(b, from, open).is_some_and(|(kw, moved)| moved || !polled_in_place(b, from, kw, open))) +} + +/// The position of `async` before the block at `open`, and whether it captures by move. +fn async_block_keyword(b: &[u8], from: usize, open: usize) -> Option<(usize, bool)> { + let head = b[from..open].trim_ascii_end(); + let moved = head.strip_suffix(b"move").filter(|h| h.last().is_some_and(u8::is_ascii_whitespace)); + let head = moved.unwrap_or(head).trim_ascii_end(); + head.strip_suffix(b"async").filter(|h| !h.last().copied().is_some_and(is_ident)).map(|h| (from + h.len(), moved.is_some())) +} + +/// Whether the async block whose `async` starts at `kw` and whose body opens at `open` is polled +/// where it is written, by awaiting it or passing it straight to `block_on` (with optional +/// parentheses around the block), so its body has run before the next statement. +fn polled_in_place(b: &[u8], from: usize, kw: usize, open: usize) -> bool { + let Some(mut close) = matching(b, open) else { return false }; + let mut start = kw; + let mut before = from + b[from..kw].trim_ascii_end().len(); + // Unwrap parentheses around the block, but not the parentheses of a call (`wrap(async { … })`). + while before > from + && b[before - 1] == b'(' + && !b[from..before - 1].trim_ascii_end().last().copied().is_some_and(|c| is_ident(c) || matches!(c, b')' | b']' | b'>')) + { + let Some(paren) = matching(b, before - 1).filter(|&c| c > close && b[close + 1..c].trim_ascii().is_empty()) else { break }; + start = before - 1; + close = paren; + before = from + b[from..before - 1].trim_ascii_end().len(); + } + let next = skip_ws(b, close + 1); + (b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident)) || passed_to_block_on(b, start, close + 1) } /// Whether `start` lies in the block or expression body of a move closure that captures `name`: @@ -2854,9 +2949,10 @@ fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) - } /// Whether `start` lies in the block body of a closure bound with `let` in `b[from..to]` -/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds, or of -/// a closure that a `let` stores without a call ([`stored_closure`]). -fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool { +/// (`let run = || { … };`, also `move` or `async`) with no call that [`closure_calls`] finds that +/// runs (or may run, when `may_run` is true), or of a closure that a `let` stores without a call +/// ([`stored_closure`]). +fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize], may_run: bool) -> bool { let mut depth = 0usize; for i in (from..start).rev() { match b[i] { @@ -2868,6 +2964,8 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue }; let text = String::from_utf8_lossy(params[..pipe].trim_ascii_end()); let (head, asynchronous) = strip_closure_keywords(&text); + // Parentheses around the whole initializer (`let _saved = (|| { … });`), not a call's. + let head = parenthesized_closure_binding_head(b, from, start, head).filter(|h| h.ends_with('=')).unwrap_or(head); let close = matching(b, i).unwrap_or(to); let binding = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b); let stored = binding.is_none() && stored_closure(b, head, close, to); @@ -2876,7 +2974,7 @@ fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: & if stored || !closure_calls(b, &name, bound, close, to, asynchronous) .into_iter() - .any(|at| runs_with_assertion_within(b, from, to, at, active)) + .any(|at| runs_with_assertion_within(b, from, to, at, active, may_run)) { return true; } @@ -10487,6 +10585,239 @@ mod tests { assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call"); } + #[test] + fn census_finds_the_closure_a_call_names() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let _saved = Some(|_: ()| app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "a stored closure with parameters is not called" + ); + assert_eq!( + census("let _run = |_: fn() -> bool| app.run(c); assert!(menu(c).is_some());"), + [(2, "census")], + "an uncalled closure whose parameter has a function type" + ); + assert_eq!( + census( + "let run = |f: fn() -> bool, mut c: Command| { c = fallback(); f() }; run(ok, default()); app.run(c); assert!(menu(c).is_some());" + ), + [], + "a parameter after a function type shadows the entry" + ); + assert_eq!( + census("let _ = (|_: ()| app.run(c))(()); assert!(menu(c).is_some());"), + [], + "a closure with parameters called where it is written runs" + ); + assert_eq!( + census("let run = || (); { let run = || { app.run(c); }; } run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a call after the block calls the outer closure" + ); + assert_eq!( + census("let run = || { app.run(c); }; { let run = || (); } run(); assert!(menu(c).is_some());"), + [], + "a call after a nested shadow ends calls the outer closure" + ); + assert_eq!( + census("let _saved = (|| { app.run(c) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a saved parenthesized block closure does not run its call" + ); + } + + #[test] + fn census_follows_writes_in_closures_and_async_blocks() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _pair = (|| (), reset()); app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a call in a sibling tuple element runs the closure it names" + ); + assert_eq!( + census("let mut input = c; let _saved = (|| { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [], + "a saved parenthesized block closure does not run its assignment" + ); + assert_eq!( + census("let mut input = c; let _ = (|| { input = fallback(); })(); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "a parenthesized block closure called in place runs its assignment" + ); + assert_eq!( + census("let run = async |mut c: Command| { c = fallback(); }; run(default()).await; app.run(c); assert!(menu(c).is_some());"), + [], + "an async closure parameter ends with its scope" + ); + assert_eq!( + census("let mut input = c; (async { input = fallback(); }).await; app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an awaited async block has run its assignment" + ); + assert_eq!( + census("let mut input = c; async { input = fallback(); }.await; app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an async block awaited without parentheses has run its assignment" + ); + assert_eq!( + census("let mut input = c; let _ = block_on(async { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an async block passed to block_on has run its assignment" + ); + assert_eq!( + census("let mut input = c; let _ = discard_block_on(async { input = fallback(); }); app.run(input); assert!(menu(c).is_some());"), + [], + "an async block passed to another function does not run its assignment" + ); + assert_eq!( + census("let mut input = c; (async move { input = fallback(); }).await; app.run(input); assert!(menu(c).is_some());"), + [], + "an awaited async move block assigns its own copy" + ); + assert_eq!( + census("let mut input = c; let _f = wrap(async { input = fallback(); }).await; app.run(input); assert!(menu(c).is_some());"), + [], + "an async block passed to a call is not awaited where it is written" + ); + assert_eq!(census("assert!((async { app.run(c) }).await.is_ok());"), [], "an awaited async block runs its call"); + assert_eq!(census("assert!(block_on(async { app.run(c) }).is_ok());"), [], "an async block passed to block_on runs its call"); + assert_eq!( + census("let _ = ready || async { app.run(c); true }.await; assert!(menu(c).is_some());"), + [(2, "census")], + "an || before an awaited async block can skip it" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _saved = || reset(); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a call in a closure that nothing calls does not run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _ = Some(|| reset()); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a call in a closure stored in a constructor does not run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _ = ready || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a call after || may run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; match ready { true => reset(), false => () } app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a call in a match arm may run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _saved = (|| reset()); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a saved parenthesized closure does not run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _ = (|| reset())(); app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a parenthesized closure called in place runs the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; let _future = async { reset(); }; app.run(input); assert!(menu(c).is_some());" + ), + [], + "an unpolled future does not run the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; async { reset(); }.await; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "an async block awaited in place runs the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; (async { reset(); }).await; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a parenthesized async block awaited in place runs the closure it names" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; async move { reset(); }.await; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "an async move block awaited in place runs the capturing closure" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; (async move { reset(); }).await; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a parenthesized async move block awaited in place runs the capturing closure" + ); + assert_eq!( + census("let input = c; let input = fallback(); { let mut input = fallback(); input = c; app.run(input); } assert!(menu(c).is_some());"), + [], + "an inner binding assigned the entry holds it inside its block" + ); + assert_eq!( + census("let input = c; let input = fallback(); { let mut input = fallback(); input = c; } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "the outer binding holds its own value after the block" + ); + assert_eq!( + census("let mut input = c; let _ = || { input = fallback(); }; app.run(input); assert!(menu(c).is_some());"), + [], + "an assignment in a closure dropped with let _ does not end an alias" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; if ready { reset(); } app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "an assignment in a closure that may be called ends an alias" + ); + assert_eq!( + census("let mut input = fallback(); let mut set = || { input = c; }; if ready { set(); } app.run(input); assert!(menu(c).is_some());"), + [(2, "census")], + "an assignment in a closure that may be skipped does not make an alias" + ); + } + + #[test] + fn census_keeps_guards_around_nested_arguments() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let _ = ready || accept({ 0 }, wrap(app.run(c))); assert!(menu(c).is_some());"), + [(2, "census")], + "a block in an earlier argument keeps the enclosing || around a nested call" + ); + assert_eq!( + census("let _ = accept({ 0 }, wrap(app.run(c))); assert!(menu(c).is_some());"), + [], + "a block in an earlier argument does not skip a nested call" + ); + assert_eq!( + census("{ { 0 }; prepare(); } let _ = ready || wrap(app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an earlier statement's block does not hide the ||" + ); + } + #[test] fn census_keeps_diagnostics_for_fixed_range_arguments() { for range in ["1..4", "1..=4", "-4..-1", "1..(2 + 2)"] { From f01fa3c11f00c084198ea27296d8727ba01444f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:10:18 -0800 Subject: [PATCH 038/106] Tests: check the find dialog fields without a per-entry loop CI's test-lint step failed on the merge of main because the census rule, which main added, flags params_texts_match_what_ui_inspect_lists for looping over every field and checking only presence. The test now collects the missing fields and asserts the list is empty, so it checks the same seven fields and reports all missing ones at once. --- crates/ui-egui/src/dialogs/find_replace/tests.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs index 49d784e09f..89a21834cb 100644 --- a/crates/ui-egui/src/dialogs/find_replace/tests.rs +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -448,7 +448,7 @@ fn edit_find_next_starts_at_the_first_restored_match_with_that_frame_selected() /// and the fields the params text names, as both params texts say. #[test] fn params_texts_match_what_ui_inspect_lists() { - const FIELDS: [&str; 7] = ["find", "replace", "matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers"]; + let expected = ["find", "replace", "matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers"]; let doc = |command: &str| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == command).expect("registered").3; for (command, params) in [("ui.findAndReplace", json!({})), ("ui.paramDialog", json!({"command": super::COMMAND, "params": {}}))] { let mut app = crate::testing::windowed(app_with(&["alpha"]).0); @@ -458,13 +458,11 @@ fn params_texts_match_what_ui_inspect_lists() { let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog"); assert!(entry["key"].is_null(), "{command}: {entry}"); assert!(doc(command).contains("with key null"), "{command} opens a dialog with key null, which its params text does not say"); - for field in FIELDS { - assert!(entry["fields"].get(field).is_some(), "{command}: ui.inspect does not list `{field}`"); - } + let missing: Vec<&str> = expected.iter().copied().filter(|f| entry["fields"].get(*f).is_none()).collect(); + assert!(missing.is_empty(), "{command}: ui.inspect does not list {missing:?}"); } let named = doc("ui.paramDialog"); - for field in FIELDS { - assert!(named.contains(field), "the params text of ui.paramDialog does not name `{field}`"); - } + let unnamed: Vec<&str> = expected.iter().copied().filter(|f| !named.contains(*f)).collect(); + assert!(unnamed.is_empty(), "the params text of ui.paramDialog does not name {unnamed:?}"); assert!(!named.contains("and action"), "the params text of ui.paramDialog names an `action` field that ui.inspect does not list"); } From e12e9074f1f3b7f06e5fc1f2370df5dcf1619f5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:10:55 -0800 Subject: [PATCH 039/106] Tests: check the point count before checking every point moved MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's test-lint step failed the gate's sixth test shard: the all-unguarded rule flagged reading_and_moving_points_counts_the_subpaths_a_few_times, whose assert!(…all(…)) would also pass on a path with no anchors. The test now asserts the path still has 1000 anchors first. --- crates/engine/src/tests/script_dom_paths.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index f2f148408c..ac8ecc128e 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1669,7 +1669,9 @@ fn reading_and_moving_points_counts_the_subpaths_a_few_times() { let built = crate::script::LAYOUTS_BUILT.with(std::cell::Cell::get); assert!(built < 10, "{built} layouts for 1000 points"); let n = node(&s, id); - assert!(n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).all(|an| an.p.y == 9.0 || an.p.y == 19.0), "every point moved up"); + let ys: Vec = n.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).map(|an| an.p.y).collect(); + assert_eq!(ys.len(), 1000); + assert!(ys.iter().all(|&y| y == 9.0 || y == 19.0), "every point moved up"); } /// `selectedPathPoints` lists the direct-selected anchors of a path with several subpaths in the From ae9ad685b274f11a6577798c5bdc5e419b26ba76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:23:08 -0800 Subject: [PATCH 040/106] JavaScript: block functions look up top-level function names in a set Deciding whether a block function gets an Annex B variable compared its name with every top-level function declaration, so a script with N top-level functions and M block functions made N x M comparisons (1,000,000 for 1,000 of each). The names are now gathered into a set once, the first time a block function needs them, and each block function makes one lookup. Hoisting results are unchanged. The scan came in with #9131. --- crates/js/src/compiler.rs | 21 ++++++++++++++++++++- crates/js/src/es2015_tests.rs | 13 +++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index f13677ca52..488823940a 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -33,6 +33,13 @@ use pattern::Mode; /// enough for a 1 MiB stack. pub(crate) const MAX_DEPTH: u32 = 600; +#[cfg(test)] +thread_local! { + /// Tests: the top-level function names that deciding the variables of block functions has + /// gathered or looked up. + pub(crate) static FUN_DECL_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Why code could not be compiled. #[derive(Debug)] pub(crate) enum CompileFail { @@ -409,6 +416,7 @@ impl<'a> FnCompiler<'a> { | Stmt::DefaultXmlNamespace(_) => {} } } + let mut top_names: Option> = None; for (k, scope, id) in annex { let mut cur = Some(scope); let mut clash = params.contains(&k) || *k == *key_of("arguments"); @@ -422,7 +430,18 @@ impl<'a> FnCompiler<'a> { } if !clash { self.annex.insert(id); - if !seen.contains(&k) && !out.fun_decls.iter().any(|(name, _)| *name == k) && annex_seen.insert(k.clone()) { + if seen.contains(&k) { + continue; + } + // The top-level function names, gathered the first time a block function needs them. + let top = top_names.get_or_insert_with(|| { + #[cfg(test)] + FUN_DECL_CHECKS.with(|c| c.set(c.get() + out.fun_decls.len() as u64)); + out.fun_decls.iter().map(|(name, _)| name).collect::>() + }); + #[cfg(test)] + FUN_DECL_CHECKS.with(|c| c.set(c.get() + 1)); + if !top.contains(&k) && annex_seen.insert(k.clone()) { out.annex_vars.push(k); } } diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 1a076c43c1..2071b2063f 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -203,6 +203,19 @@ fn a_block_function_whose_variable_cannot_be_declared_stays_in_its_block() { assert_eq!(realm.run("(0, eval)('{ function m() { return 7; } out = m(); }'); out + typeof m"), Ok(JsValue::String("7undefined".into()))); } +#[test] +fn block_function_variables_look_up_each_top_level_function_name_once() { + // 1,000 top-level functions and 1,000 block functions: each block function's variable is + // decided with one lookup in the names gathered once, not by comparing it with every + // top-level function. + let top = (0..1_000).map(|i| format!("function t{i}() {{ return {i}; }}")).collect::(); + let blocks = (0..1_000).map(|i| format!("{{ function b{i}() {{ return {i}; }} }}")).collect::(); + crate::compiler::FUN_DECL_CHECKS.with(|c| c.set(0)); + assert_eq!(run(&format!("{top}{blocks}t999() + b999()")), JsValue::Number(1_998.0)); + let checks = crate::compiler::FUN_DECL_CHECKS.with(std::cell::Cell::get); + assert_eq!(checks, 2_000, "top-level function names gathered and looked up for 1,000 block functions"); +} + #[test] fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() { truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0"); From 2db01b7dd940dca21dcf5edf23f50036fc703308 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 14:39:53 -0800 Subject: [PATCH 041/106] Scripts: remove() refuses a tracing's shown source image A script could show a tracing's source image with `hidden = false` and then remove it, which left the Image Trace object without its source and made every handle to it stale. `remove()` now refuses the source image with the error `move` already gives it, "a tracing's source image cannot leave its tracing", and leaves the document unchanged. The source-image rule for `move` came in with #9077. --- crates/engine/src/script/dom.rs | 11 ++++++++-- crates/engine/src/tests/script_dom_tracing.rs | 22 +++++++++++++++++++ docs/mcp.md | 6 +++-- docs/target-app-parity.md | 2 +- 4 files changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4e50da3b48..d5de5b26a9 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -133,6 +133,8 @@ pub const STALE_ITEM: &str = "Stale page item"; const TRACING_NAME: &str = "The name of a tracing cannot be changed"; /// The error for the tracing's name given to a group that holds an image first. const NOT_A_TRACING: &str = "Only Image Trace can make a tracing"; +/// The error of `move` and `remove()` for a tracing's source image. +const SOURCE_STAYS: &str = "a tracing's source image cannot leave its tracing"; /// The error for a document that was closed, or that came from an earlier run. pub const STALE_DOCUMENT: &str = "Stale document"; /// The error of `index` and `getByName` when nothing matches. @@ -2731,7 +2733,8 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { /// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or /// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] -/// refuses it. A compound path whose last path this is stays, empty. +/// refuses it. A tracing's source image is refused when it is shown as well. A compound path whose +/// last path this is stays, empty. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (whole, on_locked) = with_doc(h, item.doc, |_, st| { @@ -2743,6 +2746,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } + // A tracing keeps its source image when a script has shown it, as `move` keeps it there. + if with_doc(h, item.doc, |_, st| crate::cmd::is_trace_source(&st.doc, item.id)) { + return Err(HostError::Error(SOURCE_STAYS.into())); + } // An image left first in an ordinary group named as a tracing would make that group one. if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) { return Err(HostError::Error(NOT_A_TRACING.into())); @@ -2908,7 +2915,7 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul if d.parent_of(id) == Some(to.parent) { return Ok(0); } - return Err(HostError::Error("a tracing's source image cannot leave its tracing".into())); + return Err(HostError::Error(SOURCE_STAYS.into())); } let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0; let at = match (to.how, to.beside) { diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..a9c3f8b51d 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1074,6 +1074,28 @@ fn the_source_image_cannot_leave_its_tracing() { let _ = std::fs::remove_dir_all(base); } +/// A tracing's shown source image cannot be removed, which would leave the tracing without it, and +/// the refused remove leaves the document as it was. +#[test] +fn a_shown_source_image_cannot_be_removed() { + let base = folder("source-removed"); + let (mut s, _) = session(&base, false); + log(&mut s, &base, "app.activeDocument.rasterItems[0].trace().tracing.sourceArt.hidden = false;"); + let saved = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.pageItems[0], m = 'none';\ + try { p.tracing.sourceArt.remove(); } catch (e) { m = e.message; }\ + vc.log(m); vc.log(p.isTracing);", + ); + assert_eq!(out, [json!("a tracing's source image cannot leave its tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), saved); + assert_eq!(undo_steps(&s), steps); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn trace_source_art_is_not_listed_with_the_images() { let base = folder("lists"); diff --git a/docs/mcp.md b/docs/mcp.md index e716a1a08e..1062566e75 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3205,8 +3205,10 @@ through `$`: is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` - and delete nothing. Setting `width` or `height` scales the object along - the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw + and delete nothing. If these checks pass, `remove()` on a tracing's shown, unlocked source image that is not on a + locked artboard throws `a tracing's source image cannot leave its tracing` and deletes nothing. Setting `width` or + `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. + `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`. Any other value, `undefined` included (such as an index past the end diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144759bf00..f14fec843b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1115,7 +1115,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.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. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. `remove()` also refuses a shown source image. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, 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`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops 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. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. From df634f8a0b0d3877470caf5cb4aef2eae037109e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:26:28 -0800 Subject: [PATCH 042/106] Panels: the Color and Gradient pop-outs run one pass a frame With the Color or Gradient panel open as a pop-out, every second frame at rest ran the whole window twice: egui discarded the first pass because a content column in the panel body measured differently from the transcript its flyout kept. storytold/craft-libs#4932 fixes the layout memory, and this moves the craft-libs pin to its head c2a47dfe, which is craft-libs main 092a2c6b with the fix. The egui and winit revisions are unchanged. The bump also brings in craft-libs #4584, #4804, #2415, #4531, #4676, #3061 and #4050. Test: with either pop-out open, each of 10 frames at rest runs one pass. --- Cargo.lock | 172 +++++++++++------------ Cargo.toml | 76 +++++----- apps/vectorcraft-web/Cargo.toml | 2 +- crates/ui-egui/src/panels/color/tests.rs | 30 ++++ xtask/src/pdf_deps.rs | 2 +- 5 files changed, 156 insertions(+), 126 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0216e2962..80e136673a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "flate2", "serde", @@ -1850,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2082,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,7 +2165,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2182,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "accesskit", "craft-behavior", @@ -2220,7 +2220,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2231,7 +2231,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-host", @@ -2249,7 +2249,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-host", @@ -2270,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-host", @@ -2291,7 +2291,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-behavior", "craft-host", @@ -2310,7 +2310,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "base64 0.22.1", "chrono", @@ -2342,7 +2342,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "flate2", "serde", @@ -2353,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2363,7 +2363,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "js-sys", "serde_json", @@ -2374,7 +2374,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "winsafe", ] @@ -2382,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "craft-appkit", "craft-atomic", @@ -2414,7 +2414,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3773,7 +3773,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3782,7 +3782,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3800,7 +3800,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3818,12 +3818,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "flate2", "hayro-ccitt", @@ -4806,7 +4806,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4963,7 +4963,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=c2a47dfea38b215245f739c675da3662c89f1e09#c2a47dfea38b215245f739c675da3662c89f1e09" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 843f9cbb53..d14fd9004f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 70aae32f73..e439dc8be6 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "c2a47dfea38b215245f739c675da3662c89f1e09", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index d354702ef2..a36c95f13a 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -429,3 +429,33 @@ fn the_wells_show_a_gradient_and_none_as_the_tools_proxy_does() { assert!(color.shows_value(well), "the Color panel shows a well that reads as {well:?}"); } } + +/// With the Color or the Gradient panel open as a pop-out, each frame at rest runs one pass of the window: no frame +/// runs a second pass that egui discards. +#[test] +fn an_open_color_or_gradient_pop_out_runs_one_pass_a_frame() { + for panel in ["color", "gradient"] { + let mut app = app(); + app.run("window.panel", json!({"panel": panel})).unwrap(); + let ctx = crate::testing::ui_context(); + let mut time = 0.0; + let mut passes = |app: &mut VectorcraftApp| { + time += 1.0 / 60.0; + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + focused: true, + ..Default::default() + }; + let before = ctx.cumulative_pass_nr(); + let _ = crate::testing::app_frame(app, &ctx, raw); + ctx.cumulative_pass_nr() - before + }; + for _ in 0..4 { + passes(&mut app); + } + assert_eq!(app.ui.open_panel.as_deref(), Some(panel), "the {panel} pop-out is open"); + let counted: Vec = (0..10).map(|_| passes(&mut app)).collect(); + assert_eq!(counted, vec![1; 10], "the {panel} pop-out: one pass in each of 10 frames at rest"); + } +} diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 542a3e8c41..1abbfba86a 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6"; +const REV: &str = "c2a47dfea38b215245f739c675da3662c89f1e09"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From f52ff9b4ec62d44542665c921d7aeb12d4f6a39e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:08:07 -0800 Subject: [PATCH 043/106] Docs: gaps.md no longer lists script tracing as missing The Scripts entry said tracing images from scripts was still missing and listed placed and raster images twice. Scripts trace images with `trace()` since #9062 (`crates/engine/src/script/dom/tracing.rs`), as the same entry says a few lines later, so the earlier sentence drops the duplicate and the stale claim. Rasterizing and capturing images stay listed as missing. --- docs/gaps.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index fdf8eb1dcc..f1b74be261 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -861,9 +861,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection, its page items, layers, groups, compound paths and artboards, its text frames with their text ranges and character and paragraph attributes, their links to each other and the stories they form, its character and - paragraph styles, the installed fonts, each document's variables, data sets and variable libraries, and its - linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, - rasterizing and capturing images are still missing. + paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries. `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms. Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a document's `fullName`, `path` and `saved`, and close it with `Document.close`. From dc11714200d5d3c795f22f4af3adf6c53663aec6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:25:37 -0800 Subject: [PATCH 044/106] Scripts: removeAll cannot leave an image first in a group named Image Trace groupItems.removeAll() and compoundPathItems.removeAll() could delete the bottom object of an ordinary group named "Image Trace" and leave an image first in it, which made that group read as a tracing. They now throw "Only Image Trace can make a tracing" before anything is deleted, as move, remove() and zOrder do. The check came in with #9048's collection removeAll. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/layers.rs | 15 +++++-- crates/engine/src/tests/script_dom_tracing.rs | 39 +++++++++++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 4328c1bad2..1e2c7a6123 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -789,10 +789,11 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { /// `removeAll()`: deletes every object the collection lists (those inside another listed one go /// with it) in one command. A hidden or locked one, one in a hidden or locked layer or group, or /// one on a locked artboard stops it before anything is deleted, as the document's -/// `pageItems.removeAll()` is stopped. +/// `pageItems.removeAll()` is stopped, and so does an image the deletion would leave first in an +/// ordinary group named as a tracing. fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| { let all = art_list(h, st, kind, c)?; let d = &st.doc; let listed: std::collections::HashSet = all.iter().copied().collect(); @@ -817,7 +818,12 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { .map(|i| i.0) .take(20) .collect(); - Ok::<_, HostError>((ids, refused, on_locked, masks)) + // An image left first in an ordinary group named as a tracing would make that group one. + let parents: std::collections::HashSet = ids.iter().filter_map(|i| d.parent_of(*i)).filter(|p| !going.contains(p)).collect(); + let tracing = parents.into_iter().filter(|p| super::named_as_tracing(d, *p)).any(|p| { + d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) + }); + Ok::<_, HostError>((ids, refused, on_locked, masks, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -833,6 +839,9 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { "cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}" ))); } + 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::>(), "keepEmpty": true})))?; } diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..ccd9229f72 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -135,6 +135,45 @@ fn added_group_named_as_seam_fills_is_counted() { let _ = std::fs::remove_dir_all(base); } +/// `groupItems.removeAll()` of a group and the document's `compoundPathItems.removeAll()` refuse +/// to leave an image at the bottom of an ordinary group named as a tracing, before the document +/// changes. +#[test] +fn group_and_compound_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let compound = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20), d.pathItems.rectangle(40, 40, 5, 5)];\ + vc.run('object.compoundPath.make'); return d.pageItems[0]; })()"; + let group = "(function () { d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); return d.pageItems[0]; })()"; + for (name, bottom, list) in + [("group-remove-all-groups", group, "groupItems[0].groupItems"), ("remove-all-compounds", compound, "compoundPathItems")] + { + let base = folder(name); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + &format!( + "var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);" + ), + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, m = ''; try {{ d.{list}.removeAll(); }} catch (e) {{ m = e.message; }}\ + vc.log(m); vc.log(d.pageItems[0].typename);" + ), + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem")], "{list}"); + assert!(traces(&s).is_empty(), "{list}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{list}"); + assert_eq!(undo_steps(&s), steps, "{list}"); + let _ = std::fs::remove_dir_all(base); + } +} + #[test] fn trace_image_resolution_is_one_number_or_none() { let base = folder("resolution"); diff --git a/docs/mcp.md b/docs/mcp.md index b3c7372984..5b4d7d914c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3144,7 +3144,8 @@ through `$`: its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before the document changes, as renaming such a group does. `move`, `remove()` and `zOrder` throw the same error, with - nothing changed, when they would leave an image at the bottom of such a group. An object of + nothing changed, when they would leave an image at the bottom of such a group, and so do `groupItems.removeAll()` + and `compoundPathItems.removeAll()`. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2b5bad4ebc..2bf3353d84 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1118,7 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, 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`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. 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. `crates/engine/src/tests/script_dom_paths.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. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`. - - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`. + - Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error, and so does a `groupItems.removeAll()` or `compoundPathItems.removeAll()` that would leave an image at the bottom of such a group. `crates/engine/src/tests/script_dom_tracing.rs`. - Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`. - Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. From e438b270aa693c3a575416400e2a02ed4a0787c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:42:46 -0800 Subject: [PATCH 045/106] Tests: require ui.inspect to list the dialog key as null The print params-text check indexed `entry["key"]`, which also returns null when `ui.inspect` leaves `key` out. It now requires the member to be present with a null value. --- crates/ui-egui/src/dialogs/tests_print.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index db3e8cb0bb..f5fa7ba7bd 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -1583,7 +1583,7 @@ fn assert_params_text_matches_ui_inspect(command: &str, fields: &[&str]) { pump(&mut app); let ui = crate::control::inspect(&app, &ctx(&app)); let entry = ui["dialogs"].as_array().and_then(|d| d.last()).cloned().expect("a dialog"); - assert!(entry["key"].is_null(), "{command}: {entry}"); + assert_eq!(entry.get("key"), Some(&Value::Null), "{command}: {entry}"); assert!(doc.contains("with key null"), "{command} opens a dialog with key null, which its params text does not say"); for field in fields { assert!(entry["fields"].get(field).is_some(), "{command}: ui.inspect does not list `{field}`"); From ebf7ebd06316d419b720271f7576409740124b10 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:58:47 -0800 Subject: [PATCH 046/106] Docs: opening a path deselects its closing segment and the ends it alone held docs/mcp.md said that setting `closed` keeps the direct selection. Setting it to false removes the closing segment, so the selection drops that segment and each of its end anchors that no other selected segment uses. The tests opening_a_path_* in crates/engine/src/tests/script_dom_paths.rs cover these cases. --- docs/mcp.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 3673b9dfe7..0626bfcd67 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3680,7 +3680,9 @@ through `$`: 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. Changes that - only move points or handles, change a point's type or set `closed` keep them selected. + only move points or handles, change a point's type or set `closed` keep the remaining anchors and segments + selected. Setting `closed` to false deselects a selected closing segment and each of its two end anchors that no + other selected segment uses, even when that anchor was also selected on its own; when nothing else on the path stays selected, the path is deselected. `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`, From dc8460b909463883e7d8940934b71db7f49d8b49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:44:59 -0800 Subject: [PATCH 047/106] Artboard Guides: a guide with straight handled sides is not added again An existing guide rectangle whose anchors carry handles along its sides (an extra anchor on a side with handles on that side, or a handle past a corner on a segment that still runs one way) traced the rectangle but was rejected, so the command added a duplicate guide. A segment now counts as straight when its handles lie on the side's line and the curve never turns back along it, and the rectangle is taken from the anchors instead of the curve bounds. Handles off the side still do not match. --- .../src/cmd/addons/arrange/artboard_guides.rs | 31 +++++++++++++-- .../addons/arrange/artboard_guides/tests.rs | 38 +++++++++++++++++++ 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs index 98c6598d87..d849047fb9 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides.rs @@ -9,7 +9,7 @@ use std::collections::HashSet; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; -use vectorcraft_geom::{PathData, Point, Rect, shapes}; +use vectorcraft_geom::{Anchor, PathData, Point, Rect, shapes}; use super::super::super::panelcmds::{artboard_at, listed_artboards}; use super::super::super::{CommandSpec, bad, cmd, has_doc, switch_or}; @@ -70,9 +70,12 @@ fn guide_rectangles(d: &Document, layer: Option) -> HashSet<[u64; 4]> { n.walk(&mut |c| { #[cfg(test)] GUIDE_NODES_VISITED.with(|count| count.set(count.get() + 1)); + // The anchors' bounds: `traces` only accepts segments that stay between their anchors. if let NodeKind::Path { path, guide: true, .. } = &c.kind - && let Some(r) = path.bounds() + && let [sp] = &path.subpaths[..] + && let Some(first) = sp.anchors.first() { + let r = sp.anchors.iter().fold(Rect::from_points(first.p, first.p), |r, a| r.union_pt(a.p)); let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; if traces(path, &corners) { rects.insert(rect_key(r)); @@ -83,13 +86,35 @@ fn guide_rectangles(d: &Document, layer: Option) -> HashSet<[u64; 4]> { rects } +/// Does the segment from `a` to `b` run straight along a horizontal or vertical line, from `a` to `b` +/// without turning back? Its handles lie on that line, and the curve's position along it never reverses. +fn straight(a: &Anchor, b: &Anchor) -> bool { + let along = |f: fn(Point) -> f64, g: fn(Point) -> f64| { + if [a.h_out, b.h_in].iter().any(|h| g(*h) != g(a.p)) || g(a.p) != g(b.p) { + return false; + } + let s = (f(b.p) - f(a.p)).signum(); + let [p0, p1, p2, p3] = [a.p, a.h_out, b.h_in, b.p].map(|p| f(p) * s); + // The derivative along the line, as a quadratic Bernstein form: never negative on [0, 1]. + let (u, v, w) = (p1 - p0, p2 - p1, p3 - p2); + let curve = u - 2.0 * v + w; + let vertex = if curve > 0.0 && (0.0..=1.0).contains(&((u - v) / curve)) { u - (u - v) * (u - v) / curve } else { 0.0 }; + u >= 0.0 && w >= 0.0 && vertex >= 0.0 + }; + if a.p == b.p { + return a.h_out == a.p && b.h_in == a.p; + } + along(|p| p.x, |p| p.y) || along(|p| p.y, |p| p.x) +} + /// Is `path` one closed run of straight segments through `corners`, from any corner, either way round? fn traces(path: &PathData, corners: &[Point; 4]) -> bool { let [sp] = &path.subpaths[..] else { return false }; if !sp.closed || sp.anchors.len() < 4 { return false; } - if sp.anchors.iter().any(|a| a.h_in != a.p || a.h_out != a.p) { + let n = sp.anchors.len(); + if (0..n).any(|i| !straight(&sp.anchors[i], &sp.anchors[(i + 1) % n])) { return false; } let points: Vec = sp diff --git a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs index 3013130f3f..5152dcffe9 100644 --- a/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/artboard_guides/tests.rs @@ -198,6 +198,44 @@ fn collinear_midpoints_do_not_add_another_guide_or_history_step() { } } +#[test] +fn handles_along_a_side_still_match_and_handles_off_it_do_not() { + let mut s = session(); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let [id] = ids(&r)[..] else { panic!("one guide: {r}") }; + let b = board(&s, 0); + let mid = Point::new(b.center().x, b.y0); + let points = [mid, Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1), Point::new(b.x0, b.y0)]; + let corner = points[1]; + let set = |s: &mut Session, h_in: Point, h_out: Point, corner_in: Point| { + let mut sp = SubPath::polyline(&points, true); + sp.anchors[0].h_in = h_in; + sp.anchors[0].h_out = h_out; + sp.anchors[1].h_in = corner_in; + let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, .. } = &mut d.node_mut(id).unwrap().kind else { panic!("guide path") }; + *path = PathData::single(sp); + }; + // The extra anchor's handles lie along the top side: the guide still matches. + // Then a handle past the corner on a segment that still runs one way (along x: 0, 9, 6, 8 eighths). + let eighth = (corner.x - mid.x) / 8.0; + for (h_out, corner_in) in + [(Point::new(mid.x + 20.0, b.y0), corner), (Point::new(mid.x + 9.0 * eighth, b.y0), Point::new(mid.x + 6.0 * eighth, b.y0))] + { + set(&mut s, Point::new(mid.x - 20.0, b.y0), h_out, corner_in); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let again = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(again, json!({"ids": [], "layer": r["layer"], "skipped": 1}), "{h_out:?} {corner_in:?}"); + assert_eq!(steps(&s), n); + assert_eq!(s.doc().unwrap().doc, before); + } + // A handle off the side bends it: the path is not that guide, so one is added. + set(&mut s, Point::new(mid.x - 20.0, b.y0), Point::new(mid.x + 20.0, b.y0 + 10.0), corner); + let other = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(other["skipped"], json!(0)); + assert_eq!(ids(&other).len(), 1); +} + #[test] fn every_artboard_shares_one_walk_of_existing_guides() { let mut s = session(); From b81ede353247e7526906610cf826d058502f1fc5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:54:39 -0800 Subject: [PATCH 048/106] Scripts: pathItems.removeAll keeps clipping paths; empty paths refuse stroke-only scaling - pathItems.removeAll() now throws and deletes nothing when it would delete the clipping path of a group or layer that keeps other objects, as pageItems.removeAll() does. The check is shared with the art collections, and the document's collection counts compound paths that edit.clear empties and deletes. - rotate, resize and transform check changeLineWidths at the transformation's own scale with changePositions false before the early return for a path with no points, so an empty path is refused as one with bounds is instead of having its stroke weight set. - docs/mcp.md describes both. --- crates/engine/src/script/dom/layers.rs | 53 +++++++++++++-------- crates/engine/src/script/dom/paths.rs | 25 +++++++++- crates/engine/src/script/dom/transform.rs | 8 ++-- crates/engine/src/tests/script_dom_paths.rs | 52 ++++++++++++++++++++ docs/mcp.md | 7 ++- 5 files changed, 117 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index ff90c4f2f5..f213cf97d4 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -790,21 +790,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. - let going: std::collections::HashSet = ids.iter().copied().collect(); - let masks: Vec = ids - .iter() - .filter(|i| { - d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| { - let kids = p.children().map_or(&[][..], Vec::as_slice); - p.clips() - && kids.first().is_some_and(|f| f.id == **i) - && kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) - }) - }) - .map(|i| i.0) - .take(20) - .collect(); + let masks = kept_clipping_paths(d, &ids); Ok::<_, HostError>((ids, refused, on_locked, masks)) })?; if !refused.is_empty() { @@ -815,18 +801,43 @@ 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)?; if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": true})))?; } Ok(Data::Undefined) } +/// The 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. +pub(super) fn kept_clipping_paths(d: &Document, ids: &[NodeId]) -> Vec { + let going: std::collections::HashSet = ids.iter().copied().collect(); + ids.iter() + .filter(|i| { + d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| { + let kids = p.children().map_or(&[][..], Vec::as_slice); + p.clips() + && kids.first().is_some_and(|f| f.id == **i) + && kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. })) + }) + }) + .map(|i| i.0) + .take(20) + .collect() +} + +/// 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 { diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 7ed6a07290..9342813849 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -581,14 +581,34 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { /// 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. +/// Like `PageItems.removeAll()`, it throws and deletes nothing when it would delete the clipping +/// path of a group or layer that keeps other objects. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let (doc, c) = items_scope(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| { let ids = path_items(h, st, c)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); let locks = st.doc.locked_artboards(); let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused, on_locked)) + // Without `keepEmpty`, `edit.clear` also deletes a compound path it empties. + let mut going: Vec = ids.to_vec(); + if c.is_none() { + let listed: std::collections::HashSet = ids.iter().copied().collect(); + let mut seen = std::collections::HashSet::new(); + for p in ids.iter().filter_map(|i| st.doc.parent_of(*i)) { + if !seen.insert(p) { + continue; + } + let emptied = st.doc.node(p).is_some_and(|n| { + matches!(n.kind, NodeKind::Compound { .. }) && n.children().is_some_and(|k| k.iter().all(|k| listed.contains(&k.id))) + }); + if emptied { + going.push(p); + } + } + } + let masks = super::layers::kept_clipping_paths(&st.doc, &going); + Ok::<_, HostError>((ids, refused, on_locked, masks)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -598,6 +618,7 @@ 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}"))); } + super::layers::refuse_kept_clipping_paths(&masks)?; if !ids.is_empty() { 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))?; diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index f8dbeba57f..dcc9d05fd0 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -215,6 +215,11 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } + // Checked before an empty path's early return, so that a path without anchors is refused as + // one with bounds is. + if opts.strokes && !opts.objects { + return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into())); + } // The identity acts the same about every point, so an object without bounds (an empty path) // takes it too. let o = match (about, bounds) { @@ -232,9 +237,6 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, (None, _) => Point::ORIGIN, }; let xf = on_page(m, o); - if opts.strokes && !opts.objects { - return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into())); - } if opts.objects && xf != Affine::IDENTITY { // The transformed corners of the bounds hold the transformed object. When one of them is // past the canvas, or the object holds a clipping group (whose bounds leave out the art diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index e9ff7536ea..f85bd10edd 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -156,6 +156,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(); @@ -768,6 +805,21 @@ fn turning_or_scaling_an_empty_path_changes_nothing() { 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); diff --git a/docs/mcp.md b/docs/mcp.md index 0626bfcd67..5dc9783326 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3162,7 +3162,8 @@ through `$`: 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`). The compound path's - `pathItems.removeAll()` also leaves it, empty. An object with nothing in it, such + `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 @@ -3199,7 +3200,9 @@ through `$`: matrix whose determinant is 0 and a transformation that would take the object past the canvas also throw an error. In each of these cases the document does not change. A call that changes nothing runs no command. `rotate`, `resize` and `transform` on a path with no points leave its geometry as it is and set only the stroke weight the - call asks for. + call asks for. As on a path with points, `changeLineWidths` at the transformation's own scale, other than 100, with + `changePositions` false throws an error that says it is not available yet; `resize` with another percent still + sets the stroke weight. `pageItems` lists the art topmost first, as the example on [CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`, and a document's `selection` lists the selected objects in the same order, whatever order they were selected or From 0313f86491f41e2939e289414c81e7036c25f2a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 23:53:38 -0800 Subject: [PATCH 049/106] Docs: name layer and group pathItems in the roadmap --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index d28848169e..b19a09d9d5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -209,7 +209,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 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; the rest of the script document model (layers, artboards, 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 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, and the `pathItems` of layers, groups and compound paths make paths inside them; the rest of the script document model (layers, artboards, 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 | From 63183693911b8d9123a6093663d7490afe1ad7b5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 01:34:27 -0800 Subject: [PATCH 050/106] Scripts: a pattern on a path with no points is not left untransformed rotate, resize and transform on a path with no points returned success after setting only the stroke weight, even when the call asked to transform a fill or stroke pattern the path uses. The pattern stayed as it was. Such a call now throws "the object has no bounds", as it did before empty paths were accepted, and leaves the document unchanged. docs/mcp.md states the exception. --- crates/engine/src/script/dom/transform.rs | 5 +++-- crates/engine/src/tests/script_dom_paths.rs | 23 +++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index baae8b1d0a..9bbc8c1cd2 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -233,8 +233,9 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, _ if m == IDENTITY => Point::ORIGIN, (Some(name), Some(r)) => anchor(h, item, r, name)?, // A path with no anchors has no bounds to turn or scale about, and turning or scaling it - // changes nothing; only a stroke weight the call sets is applied. - (Some(_), None) if paths::is_path(h, item) => { + // changes nothing; only a stroke weight the call sets is applied. A pattern it uses has no + // point to turn or scale about either, so a call that asks to transform it is refused. + (Some(_), None) if paths::is_path(h, item) && !(opts.patterns && uses_pattern) => { if let Some(w) = weight { paths::set_stroke_weight(h, item, w)?; } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 81a28f5354..db02ff3742 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1783,6 +1783,29 @@ fn filled_and_stroked_true_give_the_new_art_paint() { } } +/// Turning or scaling the pattern of a path with no anchors is refused, since the path has no +/// point to transform it about; with Transform Patterns off the call succeeds. +#[test] +fn transforming_the_pattern_of_an_empty_path_is_refused() { + 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)); + let e = failure(&mut s, source); + assert!(e.contains("the object has no bounds"), "{source}: {e}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{source}: nothing changes"); + // With Transform Patterns off the call succeeds and changes nothing. + log(&mut s, "app.activeDocument.pathItems[0].resize(50, 50, true, false, true, false); app.activeDocument.pathItems[0].rotate(90);"); + assert_eq!((art(&s), undo_steps(&s)), (before, steps), "{source}"); + } +} + #[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/docs/mcp.md b/docs/mcp.md index f9be26ba5c..c3d1775763 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3200,7 +3200,8 @@ through `$`: matrix whose determinant is 0 and a transformation that would take the object past the canvas also throw an error. In each of these cases the document does not change. A call that changes nothing runs no command. `rotate`, `resize` and `transform` on a path with no points leave its geometry as it is and set only the stroke weight the - call asks for. As on a path with points, `changeLineWidths` at the transformation's own scale, other than 100, with + call asks for. When the path uses a pattern and the call transforms patterns, it throws an error that the object has + no bounds, since no point on the path can serve to turn or scale the pattern about. As on a path with points, `changeLineWidths` at the transformation's own scale, other than 100, with `changePositions` false throws an error that says it is not available yet; `resize` with another percent still sets the stroke weight. `pageItems` lists the art topmost first, as the example on From 4bb9f7dc92d8ee0859302dd8d9a7b2b21b7627e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 03:08:31 -0800 Subject: [PATCH 051/106] xtask: test-lint census rule skips writes that cannot run - An async block whose `async` and `move` are separated by a comment or extra spaces is found with `async_block_keyword`. - A write inside an `async move` block to a local the block declares counts as a write; only writes to captures are skipped. - A literal `false` left of `&&` or `true` left of `||` keeps the right side from running, also when the lint asks whether a write may run. `a && true || ...` is not a literal left operand. - A closure passed to `drop` (or `mem::drop`, `std::mem::drop`, `core::mem::drop`) is not called. --- xtask/src/test_lint.rs | 136 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 120 insertions(+), 16 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 1485cfc600..7927f48eaa 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2264,7 +2264,10 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { // Assignments in move closures leave outer bindings unchanged. Assignments in async // blocks that are not awaited, or in closures that nothing calls, do not run; // conditional assignments do not make aliases. - if in_move_closure(b, from, to, at, &name) || in_async_block(b, from, at) || !runs_with_assertion_within(b, from, to, at, &[], true) { + if in_move_closure(b, from, to, at, &name) + || in_async_block(b, from, at, &name) + || !runs_with_assertion_within(b, from, to, at, &[], true) + { continue; } if live(value_start(eq, end), end, &derived, &shadows) { @@ -2559,11 +2562,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let prefix_at = skip_ws(b, head).min(open); let prefix = b[head..open].trim_ascii(); let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); - // Where the `async` of an async block starts. - let async_kw = [b"async".as_slice(), b"async move"] - .iter() - .find(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident)) - .map(|kw| prefix_at + prefix.len() - kw.len()); + // Where the `async` of an async block starts, with any whitespace before `move`. + let async_kw = async_block_keyword(b, prefix_at, open).map(|(kw, _)| kw); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; @@ -2675,11 +2675,12 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac if b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>') { break; } - if !may_run - && b[i] == b'&' + if b[i] == b'&' && b[i - 1] == b'&' - && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) - && !asserted_conjunction(b, from, to, i - 1) + && ((!may_run + && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) + && !asserted_conjunction(b, from, to, i - 1)) + || (may_run && literal_operand(b, stmt, i - 1, b"false"))) { return false; } @@ -2692,7 +2693,8 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac && !asynchronous && prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) { - if may_run { + // A literal `true` always skips the right side; any other operand may let it run. + if may_run && !literal_operand(b, stmt, i - 1, b"true") { continue; } return false; @@ -2712,7 +2714,10 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac binding_head.trim_start().strip_suffix('=').and_then(|h| h.strip_prefix("let")).filter(|h| h.starts_with(char::is_whitespace)) else { // Other callees may invoke or retain a callback, but an unused constructor only stores it. - let may_call = may_run && !asynchronous && closure_body_end(b, end, to).is_some_and(|close| !stored_closure(b, bare, close, to)); + let may_call = may_run + && !asynchronous + && !discarding_call(bare) + && closure_body_end(b, end, to).is_some_and(|close| !stored_closure(b, bare, close, to)); // `(|| app.run(c))()` calls the closure where it is written. let open = stmt + bare.len(); let Some(close) = open.checked_sub(1).filter(|&o| b[o] == b'(').and_then(|o| matching(b, o)) else { return may_call }; @@ -2882,10 +2887,51 @@ fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: /// Whether `start` lies in the body of an `async move` block, which writes to its own copies of the /// captures, or of an `async` block that is not polled where it is written ([`polled_in_place`]). -fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { - (from..start) - .filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) - .any(|open| async_block_keyword(b, from, open).is_some_and(|(kw, moved)| moved || !polled_in_place(b, from, kw, open))) +/// A write to `name` that a `let` in the block before `start` declares is a write to the block's own +/// local, not to a capture. +fn in_async_block(b: &[u8], from: usize, start: usize, name: &str) -> bool { + (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { + async_block_keyword(b, from, open) + .is_some_and(|(kw, moved)| (moved && !declared_in(b, open + 1, start, name)) || !polled_in_place(b, from, kw, open)) + }) +} + +/// Whether a `let` in `b[body..start]` whose scope reaches `start` binds `name`. +fn declared_in(b: &[u8], body: usize, start: usize, name: &str) -> bool { + words(b, b"let", body, start).into_iter().any(|l| { + block_close(b, l) > start + && (l + 3..start) + .find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) + .is_some_and(|eq| pattern_names(&String::from_utf8_lossy(&b[l + 3..eq])).any(|n| n == name)) + }) +} + +/// Whether the left operand of the `&&` or `||` at `op` in the statement starting at `stmt` is the +/// literal `lit` (`false && …`, `true || …`), which decides the operator without its right side. +fn literal_operand(b: &[u8], stmt: usize, op: usize, lit: &[u8]) -> bool { + let left = b[stmt..op].trim_ascii_end(); + let Some(rest) = left.strip_suffix(lit) else { return false }; + if rest.last().copied().is_some_and(is_ident) { + return false; + } + let rest = rest.trim_ascii_end(); + match rest.last() { + None | Some(b'(' | b'{' | b',' | b';') => true, + Some(b'=') => !matches!(rest.get(rest.len().wrapping_sub(2)), Some(b'=' | b'!' | b'<' | b'>')), + // `a && true || …` has `a && true` as its left operand, while `a && false && …` is still false. + Some(b'&') => lit == b"false" && rest.ends_with(b"&&"), + Some(b'|') => rest.ends_with(b"||"), + _ => false, + } +} + +/// Whether `head`, the text before a closure's parameters, ends with a call to `drop`, which +/// discards the closure without calling it. A bare `drop` is the prelude's, as in [`value_kept`]. +fn discarding_call(head: &str) -> bool { + head.strip_suffix('(').map(str::trim_end).is_some_and(|callee| { + let path_len = callee.bytes().rev().take_while(|&c| is_ident(c) || c == b':').count(); + matches!(&callee[callee.len() - path_len..], "drop" | "mem::drop" | "std::mem::drop" | "core::mem::drop") + }) } /// The position of `async` before the block at `open`, and whether it captures by move. @@ -10797,6 +10843,64 @@ mod tests { ); } + #[test] + fn census_skips_writes_that_cannot_run_and_async_block_locals() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("let _future = async /* deferred */ move { app.run(c); }; assert!(menu(c).is_some());"), + [(2, "census")], + "a comment between async and move still marks an unpolled async block" + ); + assert_eq!( + census("block_on(async move { let mut input = fallback(); input = c; app.run(input); }); assert!(menu(c).is_some());"), + [], + "a write to a local declared inside an async move block makes an alias" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; false && { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [], + "a literal false left of && never runs the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; true || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [], + "a literal true left of || never runs the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; ready && { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "an unknown left operand of && may run the reset" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; std::mem::drop(|| reset()); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a closure passed to drop is never called" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; on_change(|| reset()); app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a closure passed to another callee may be called" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; ready && true || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a literal true after && is not the whole left operand of ||" + ); + } + #[test] fn census_keeps_guards_around_nested_arguments() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); From 9d7d310e839690f7fddb2fd5515ef9f95caf922b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 03:31:08 -0800 Subject: [PATCH 052/106] Save: a checked save opens an existing file without creating one When the rename is refused, a checked save on Unix copied the new content into the existing file, opened with `O_CREAT` after a separate check that the file was there. A file removed between the check and the open was created again before the final check of the folder, so a folder moved out of the write root could be left holding an empty file. The existing file is now opened without `O_CREAT`; a missing one is created only after the final check, as before. The open is non-blocking and only a regular file is written, so a FIFO at the name fails at once. The rule that Linux's `fs.protected_regular` applied to the `O_CREAT` open is kept: in a sticky folder that the group or others can write to, a file owned by neither this user nor the folder's owner is refused. --- crates/format/Cargo.toml | 2 +- crates/format/src/atomic.rs | 121 ++++++++++++++++++++++++++++++++++-- 2 files changed, 116 insertions(+), 7 deletions(-) diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index e020dda9c3..f48032c020 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -22,7 +22,7 @@ flate2 = { workspace = true } # file's access ACL on Linux (`keep_permissions`). Already in Cargo.lock (tempfile), so this adds # no new crate. [target.'cfg(unix)'.dependencies] -rustix = { workspace = true, features = ["std", "fs"] } +rustix = { workspace = true, features = ["std", "fs", "process"] } [dev-dependencies] vectorcraft-testkit = { workspace = true } diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index dd0cd4cc6c..39e14aa08c 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -153,13 +153,19 @@ pub fn write_atomic_checked( flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) }; let open_target = |write: bool| -> io::Result { - // A missing target is created by `create_target`, after the last check. An existing one is - // opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it. - if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) { - return Err(io::ErrorKind::NotFound.into()); + // Opened without `O_CREAT`: a missing target, one removed meanwhile included, is created + // only by `create_target`, after the last check. + #[cfg(test)] + if write && let Some(hook) = BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()) { + hook(); } - let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; - Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) + // `O_NONBLOCK`: a FIFO at the name fails the regular-file check instead of waiting for a reader. + let flags = if write { OFlags::WRONLY | OFlags::NONBLOCK } else { OFlags::RDONLY }; + let file = File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?); + if write { + protected_regular(&dir, &file)?; + } + Ok(file) }; let create_target = || -> io::Result { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, mode)?)) }; match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { @@ -265,6 +271,31 @@ pub fn write_atomic_checked( } } +/// The target [`write_atomic_checked`] opened without `O_CREAT`, checked as Linux's strictest +/// `fs.protected_regular` checks an `O_CREAT` open of an existing file: anything but a regular +/// file is refused, and so is a file in a sticky folder that others or the group can write to +/// when neither this process nor the folder's owner owns it. +#[cfg(unix)] +fn protected_regular(dir: &std::os::fd::OwnedFd, file: &File) -> io::Result<()> { + let (folder, opened) = (rustix::fs::fstat(dir)?, rustix::fs::fstat(file)?); + if rustix::fs::FileType::from_raw_mode(opened.st_mode) != rustix::fs::FileType::RegularFile { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")); + } + if refused_in_sticky_folder(rustix::fs::Mode::from_raw_mode(folder.st_mode), folder.st_uid, opened.st_uid, rustix::process::geteuid().as_raw()) { + return Err(io::ErrorKind::PermissionDenied.into()); + } + Ok(()) +} + +/// Whether a file owned by `owner` in a folder with mode `folder_mode` owned by `folder_owner` is +/// refused to the user `me`: the folder is sticky, others or the group can write to it, and +/// neither `me` nor `folder_owner` owns the file. +#[cfg(unix)] +fn refused_in_sticky_folder(folder_mode: rustix::fs::Mode, folder_owner: u32, owner: u32, me: u32) -> bool { + use rustix::fs::Mode; + folder_mode.contains(Mode::SVTX) && folder_mode.intersects(Mode::WGRP | Mode::WOTH) && owner != me && owner != folder_owner +} + /// See the Unix version. #[cfg(not(unix))] pub fn write_atomic_checked( @@ -767,6 +798,9 @@ thread_local! { /// Tests: [`write_atomic_checked`]'s folder refuses the rename. #[cfg(unix)] static RENAME_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: run once right before [`write_atomic_checked`] opens its target for writing. + #[cfg(unix)] + static BEFORE_TARGET_OPEN: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; } /// A symbolic link keeps pointing at its file: write the file it names. @@ -1246,6 +1280,81 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// A target removed after the write starts is not created again before the last check: when its + /// folder has moved outside by then, nothing is left there. + #[cfg(unix)] + #[test] + fn a_checked_write_creates_no_target_removed_while_it_is_opened() { + let (d, root, outside) = checked_folders("checked-removed-target"); + let path = root.join("inside/doc.txt"); + std::fs::write(&path, b"old").unwrap(); + let (inside, moved) = (root.join("inside"), outside.join("inside")); + let (from, to) = (inside.clone(), moved.clone()); + BEFORE_TARGET_OPEN.with(|h| { + *h.borrow_mut() = Some(Box::new(move || { + std::fs::remove_file(from.join("doc.txt")).unwrap(); + std::fs::rename(&from, &to).unwrap(); + })) + }); + RENAME_REFUSED.with(|c| c.set(true)); + let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + BEFORE_TARGET_OPEN.with(|h| h.borrow_mut().take()); + assert!(r.is_err(), "{r:?}"); + assert!(!moved.join("doc.txt").exists(), "the removed target was created again"); + assert!(!inside.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// An existing regular file this process owns passes the check. + #[cfg(unix)] + #[test] + fn protected_regular_allows_a_file_this_process_owns() { + let d = std::fs::canonicalize(dir("protected-regular")).unwrap(); + std::fs::write(d.join("doc.txt"), b"old").unwrap(); + let folder: std::os::fd::OwnedFd = File::open(&d).unwrap().into(); + let file = OpenOptions::new().write(true).open(d.join("doc.txt")).unwrap(); + protected_regular(&folder, &file).unwrap(); + let _ = std::fs::remove_dir_all(d); + } + + /// A FIFO at the name is not written into when the rename is refused: without a reader the + /// write fails at once instead of waiting for one (without `O_NONBLOCK` this test does not + /// return), and with a reader nothing reaches it. + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_does_not_write_into_a_fifo_at_its_name() { + use rustix::fs::{Mode, OFlags}; + use std::io::Read as _; + let (d, root, _) = checked_folders("checked-fifo"); + let path = root.join("inside/doc.txt"); + rustix::fs::mknodat(rustix::fs::CWD, &path, rustix::fs::FileType::Fifo, Mode::RUSR | Mode::WUSR, 0).unwrap(); + RENAME_REFUSED.with(|c| c.set(true)); + let alone = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + let reader = File::from(rustix::fs::open(&path, OFlags::RDONLY | OFlags::NONBLOCK, Mode::empty()).unwrap()); + let read = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)); + RENAME_REFUSED.with(|c| c.set(false)); + assert!(alone.is_err() && read.is_err(), "{alone:?} {read:?}"); + let mut got = [0u8; 8]; + assert!((&reader).read(&mut got).map_or(true, |n| n == 0), "nothing is written into the FIFO"); + let _ = std::fs::remove_dir_all(d); + } + + /// A file in a sticky folder that others or the group can write to is refused when neither this + /// user nor the folder's owner owns it. + #[cfg(unix)] + #[test] + fn a_file_owned_by_someone_else_in_a_shared_sticky_folder_is_refused() { + let (me, folder_owner, other) = (1000, 0, 2000); + let mode = rustix::fs::Mode::from_raw_mode; + assert!(refused_in_sticky_folder(mode(0o1777), folder_owner, other, me)); + assert!(refused_in_sticky_folder(mode(0o1770), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o1755), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o0777), folder_owner, other, me)); + assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, me, me)); + assert!(!refused_in_sticky_folder(mode(0o1777), folder_owner, folder_owner, me)); + } + /// A file created by another writer at the final check is preserved whether that check succeeds or fails. #[cfg(unix)] #[test] From cfebc3e61b65fbb15826d75afea1322597062b91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 04:08:03 -0800 Subject: [PATCH 053/106] xtask: test-lint census rule follows early exits and captured writes A polled async block, a called closure or a nested for body can be left before the call: a return or ? leaves a closure or async block, and a break or continue leaves a nested for body. The census exemption no longer counts a call after such an exit. Exits inside a nested closure, async block or inner loop leave only that one, and a closure with a return type is recognized as nested. A write to a capture inside an async move block or a move closure now changes the block's own copy until the block ends, instead of being skipped. A later call in the block that receives the replaced value no longer counts as feeding the entry, while the outer binding keeps it. --- xtask/src/test_lint.rs | 184 +++++++++++++++++++++++++++++++++-------- 1 file changed, 148 insertions(+), 36 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 7927f48eaa..50c4187406 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2261,15 +2261,15 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { ) .max_by_key(|&(since, _)| since) .map_or(to, |(_, until)| until); - // Assignments in move closures leave outer bindings unchanged. Assignments in async - // blocks that are not awaited, or in closures that nothing calls, do not run; - // conditional assignments do not make aliases. - if in_move_closure(b, from, to, at, &name) - || in_async_block(b, from, at, &name) - || !runs_with_assertion_within(b, from, to, at, &[], true) - { + // Assignments in async blocks that are not awaited, or in closures that nothing calls, + // do not run; conditional assignments do not make aliases. + if in_async_block(b, from, at) || !runs_with_assertion_within(b, from, to, at, &[], true) { continue; } + // Assignments to a capture in a move closure or an `async move` block change the + // block's own copy, so they end at the block and leave the outer binding unchanged. + let until = + move_closure_copy_end(b, from, to, at, &name).into_iter().chain(async_move_copy_end(b, from, at, &name)).fold(until, usize::min); if live(value_start(eq, end), end, &derived, &shadows) { if !runs_with_assertion(b, from, to, at) { continue; @@ -2564,26 +2564,30 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let nested_for = prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace); // Where the `async` of an async block starts, with any whitespace before `move`. let async_kw = async_block_keyword(b, prefix_at, open).map(|(kw, _)| kw); + // A closure body, an async block or a nested `for` body can be left before the call + // (`block_on(async { if skip { return; } app.run(c); })`) while the loop's assertions still run. + let left_early = !may_run && (async_kw.is_some() || nested_for || closure_params_head(prefix)) && exits_before(b, open, start, nested_for); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { - if !runs_with_assertion_within(b, from, to, open, &active, may_run) { + if left_early || !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; } - } else if nested_for && !literal_source_yields(prefix).unwrap_or(may_run) { + } else if nested_for && (left_early || !literal_source_yields(prefix).unwrap_or(may_run)) { // A nested `for` body runs only when its source yields an item. return false; } else if let Some(kw) = async_kw { // An async block needs polling where it is written, by await or block_on. let polled = polled_in_place(b, from, kw, open); - if !polled || !runs_with_assertion_within(b, from, to, kw, &active, may_run) { + if !polled || left_early || !runs_with_assertion_within(b, from, to, kw, &active, may_run) { return false; } - } else if !may_run - && !prefix.ends_with(b"|") - && !nested_for - && (prefix.ends_with(b"=>") - || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) - || (!words(prefix, b"loop", 0, prefix.len()).is_empty() - && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty()))) + } else if left_early + || (!may_run + && !prefix.ends_with(b"|") + && !nested_for + && (prefix.ends_with(b"=>") + || [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty()) + || (!words(prefix, b"loop", 0, prefix.len()).is_empty() + && matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty())))) { // A nested `for` body whose source yields an item runs, like the loop body itself; // [`feeds_entry`] keeps its own bindings apart. @@ -2885,15 +2889,65 @@ fn required_conjunction(b: &[u8], mut f: usize, mut t: usize, at: usize, depth: b.get(open) == Some(&b'(') && matching(b, open) == close.checked_sub(1) && required_conjunction(b, open, close, at, depth + 1) } -/// Whether `start` lies in the body of an `async move` block, which writes to its own copies of the -/// captures, or of an `async` block that is not polled where it is written ([`polled_in_place`]). -/// A write to `name` that a `let` in the block before `start` declares is a write to the block's own -/// local, not to a capture. -fn in_async_block(b: &[u8], from: usize, start: usize, name: &str) -> bool { - (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)).any(|open| { - async_block_keyword(b, from, open) - .is_some_and(|(kw, moved)| (moved && !declared_in(b, open + 1, start, name)) || !polled_in_place(b, from, kw, open)) - }) +/// Whether `start` lies in the body of an `async` block that is not polled where it is written +/// ([`polled_in_place`]). +fn in_async_block(b: &[u8], from: usize, start: usize) -> bool { + (from..start) + .filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) + .any(|open| async_block_keyword(b, from, open).is_some_and(|(kw, _)| !polled_in_place(b, from, kw, open))) +} + +/// The close of the innermost `async move` block around `start` that captures `name`: a write to +/// `name` there changes the block's own copy, which ends with the block. A write to `name` that a +/// `let` in the block before `start` declares is a write to the block's own local, not to a capture. +fn async_move_copy_end(b: &[u8], from: usize, start: usize, name: &str) -> Option { + (from..start) + .rev() + .filter(|&i| b[i] == b'{') + .filter_map(|open| matching(b, open).filter(|&close| start < close).map(|close| (open, close))) + .find(|&(open, _)| async_block_keyword(b, from, open).is_some_and(|(_, moved)| moved && !declared_in(b, open + 1, start, name))) + .map(|(_, close)| close) +} + +/// Whether `head`, the text of a statement before a `{`, ends with a closure's parameter list +/// (`let run = ||`, `move |c: Command|`), not with a logical OR (`ready ||`). +fn closure_params_head(head: &[u8]) -> bool { + // A return type follows the parameters (`|| -> bool`, `|c: Command| -> Result<(), E>`). + let head = match head.iter().rposition(|&c| c == b'|') { + Some(p) if head[p + 1..].trim_ascii_start().starts_with(b"->") => &head[..=p], + _ => head, + }; + let Some(rest) = head.strip_suffix(b"||") else { + return head.ends_with(b"|"); + }; + let rest = rest.trim_ascii_end(); + rest.is_empty() + || matches!(rest.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) + || [b"move".as_slice(), b"async"].iter().any(|kw| rest.strip_suffix(*kw).is_some_and(|h| !h.last().copied().is_some_and(is_ident))) +} + +/// Whether the block opening at `open` can be left before `start`: a closure body or async block by +/// a `return` or a `?`, and a loop body (`loop_body`) by a `break` or a `continue` (a `return` or `?` +/// there leaves the test, and the assertions with it). An exit inside a nested closure or async +/// block leaves only that one, and a `break` or `continue` inside a nested loop leaves only that loop. +fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool) -> bool { + let nested = |at: usize, loops: bool| { + (open + 1..at).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).any(|inner| { + let stmt = (open + 1..inner).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); + let head = b[stmt..inner].trim_ascii(); + closure_params_head(head) + || async_block_keyword(b, stmt, inner).is_some() + || (loops + && [b"for".as_slice(), b"while", b"loop"] + .iter() + .any(|kw| head.starts_with(kw) && !head.get(kw.len()).copied().is_some_and(is_ident))) + }) + }; + let returns = words(b, b"return", open + 1, start).into_iter().any(|at| !nested(at, false)); + let tries = (open + 2..start).any(|i| b[i] == b'?' && (is_ident(b[i - 1]) || matches!(b[i - 1], b')' | b']')) && !nested(i, false)); + let loops = + loop_body && [b"break".as_slice(), b"continue"].iter().any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true))); + if loop_body { loops } else { returns || tries } } /// Whether a `let` in `b[body..start]` whose scope reaches `start` binds `name`. @@ -2963,15 +3017,13 @@ fn polled_in_place(b: &[u8], from: usize, kw: usize, open: usize) -> bool { (b[next..].starts_with(b".await") && !b.get(next + 6).copied().is_some_and(is_ident)) || passed_to_block_on(b, start, close + 1) } -/// Whether `start` lies in the block or expression body of a move closure that captures `name`: -/// neither the closure's parameters nor a `let` in its body before `start` binds `name`. -fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) -> bool { - words(b, b"move", from, start).into_iter().any(|at| { - let pipe = skip_ws(b, at + 4); - if b.get(pipe) != Some(&b'|') { - return false; - } - let Some(end) = (pipe + 1..to).find(|&i| b[i] == b'|') else { return false }; +/// Where the body of the innermost move closure around `start` that captures `name` ends: neither +/// the closure's parameters nor a `let` in its body before `start` binds `name`. A write to `name` +/// there changes the closure's own copy, which ends with the body. +fn move_closure_copy_end(b: &[u8], from: usize, to: usize, start: usize, name: &str) -> Option { + words(b, b"move", from, start).into_iter().rev().find_map(|at| { + let pipe = Some(skip_ws(b, at + 4)).filter(|&pipe| b.get(pipe) == Some(&b'|'))?; + let end = (pipe + 1..to).find(|&i| b[i] == b'|')?; let body = skip_ws(b, end + 1); let mut until = body; if b.get(body) == Some(&b'{') { @@ -2990,7 +3042,7 @@ fn in_move_closure(b: &[u8], from: usize, to: usize, start: usize, name: &str) - .find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>')) .is_some_and(|eq| binds(&b[l + 3..eq])) }); - inside && !binds(&b[pipe + 1..end]) && !local + (inside && !binds(&b[pipe + 1..end]) && !local).then_some(until) }) } @@ -10857,6 +10909,66 @@ mod tests { [], "a write to a local declared inside an async move block makes an alias" ); + assert_eq!( + census("block_on(async { if skip { return; } app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return before the call leaves a polled async block without running it" + ); + assert_eq!( + census("block_on(async { prepare()?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? before the call can leave a polled async block" + ); + assert_eq!( + census("block_on(async { let _f = || { return; }; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a nested closure does not leave the polled async block" + ); + assert_eq!( + census("let run = || { if skip { return; } app.run(c); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a return before the call leaves a called closure without running it" + ); + assert_eq!( + census("for _ in [1] { if skip { continue; } app.run(c); } assert!(menu(c).is_some());"), + [(2, "census")], + "a continue before the call skips it in a nested for body" + ); + assert_eq!( + census("for _ in [1] { for _ in [2] { break; } app.run(c); } assert!(menu(c).is_some());"), + [], + "a break in an inner loop does not leave the nested for body" + ); + assert_eq!( + census("for _ in [1] { prepare()?; app.run(c); } assert!(menu(c).is_some());"), + [], + "a ? in a nested for body fails the test instead of skipping the call" + ); + assert_eq!( + census("block_on(async { let _ready = || -> bool { return true; }; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a nested closure with a return type does not leave the async block" + ); + assert_eq!( + census("let mut input = c; block_on(async move { input = fallback(); render(input, offset); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a write to a capture in an async move block replaces the entry inside the block" + ); + assert_eq!( + census("let mut input = c; let run = move || { input = fallback(); render(input, offset); }; run(); assert!(menu(c).is_some());"), + [(2, "census")], + "a write to a capture in a move closure replaces the entry inside the closure" + ); + assert_eq!( + census("let input = c; block_on(async move { render(input, offset); }); assert!(menu(c).is_some());"), + [], + "an async move block that renders the captured entry feeds it" + ); + assert_eq!( + census("let mut input = c; block_on(async move { input = fallback(); }); render(input, offset); assert!(menu(c).is_some());"), + [], + "the outer binding keeps the entry after an async move block writes its copy" + ); assert_eq!( census( "let mut input = c; let mut reset = || { input = fallback(); }; false && { reset(); true }; app.run(input); assert!(menu(c).is_some());" From 34a8ecdcbab64719654fc86508f859e04f77fb49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 04:18:49 -0800 Subject: [PATCH 054/106] New Document: the Background Contents chip keeps its full color The chip took no click or focus because it was disabled, and a disabled chip draws faded, so White showed as gray on a dark theme. It now uses PaintChip::display_only() from storytold/craft-libs#4953, which takes no click or focus and draws as an enabled chip. The craft-libs rev and the pdf-deps REV move to that pull request's head. --- Cargo.lock | 172 ++++++++++----------- Cargo.toml | 76 ++++----- apps/vectorcraft-web/Cargo.toml | 2 +- crates/ui-egui/src/dialogs/new_document.rs | 10 +- xtask/src/pdf_deps.rs | 2 +- 5 files changed, 133 insertions(+), 129 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0216e2962..9b2c05266f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "flate2", "serde", @@ -1850,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2082,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,7 +2165,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2182,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "accesskit", "craft-behavior", @@ -2220,7 +2220,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2231,7 +2231,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-host", @@ -2249,7 +2249,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-host", @@ -2270,7 +2270,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-host", @@ -2291,7 +2291,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-behavior", "craft-host", @@ -2310,7 +2310,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "base64 0.22.1", "chrono", @@ -2342,7 +2342,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "flate2", "serde", @@ -2353,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2363,7 +2363,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "js-sys", "serde_json", @@ -2374,7 +2374,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "winsafe", ] @@ -2382,7 +2382,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "craft-appkit", "craft-atomic", @@ -2414,7 +2414,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3773,7 +3773,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3782,7 +3782,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3800,7 +3800,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3818,12 +3818,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "flate2", "hayro-ccitt", @@ -4806,7 +4806,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4963,7 +4963,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" +source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 843f9cbb53..085881302b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } emath = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } epaint = { git = "https://github.com/storytold/egui.git", rev = "861d60a65c50850e995bbb3dcee7c1f3b06815f6" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 70aae32f73..ebf926348a 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 5a3b01c0c9..17da38f679 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -412,14 +412,14 @@ fn built_in_card(preset: &DocSettings, values: &VcNewDocument, orientation: Opti } /// The chip after Background Contents: the paper white, or No Color for transparent. It shows the choice and opens -/// nothing. +/// nothing. It is display-only: it is not a Tab stop, offers no click and draws in full color. fn background_chip(ui: &mut egui::Ui, background: Background) { let paint = match background { Background::White => Paint::Solid(Srgba::WHITE), Background::Transparent => Paint::None, }; let name = crate::i18n::fmt(tl!("{row} swatch"), &[("row", tl!("Background Contents"))]); - PaintChip::new(name, Bind::given(paint), Srgba::WHITE).popover(false).chip_size(PaintChipSize::Swatch).show(ui); + PaintChip::new(name, Bind::given(paint), Srgba::WHITE).chip_size(PaintChipSize::Swatch).display_only().show(ui); } /// A label with the text `s`, already translated. @@ -1627,7 +1627,7 @@ mod tests { /// White. Before, the list stood alone. #[test] fn new_document_background_contents_shows_its_chip() { - use egui::accesskit::Role; + use egui::accesskit::{Action, Role}; let chip_name = "Background Contents swatch"; let mut app = app(); open(&mut app); @@ -1643,6 +1643,10 @@ mod tests { }; let (list, _) = find("Background Contents", Role::ComboBox); let (chip, value) = find(chip_name, Role::ColorWell); + let node = nodes.iter().find(|(_, n)| n.role() == Role::ColorWell && n.label() == Some(chip_name)).map(|(_, n)| n).expect("the chip"); + assert!(!node.supports_action(Action::Click), "the chip opens nothing, so it offers no click"); + assert!(!node.supports_action(Action::Focus), "the chip is not a Tab stop"); + assert!(!node.is_disabled(), "the chip is not disabled, so it draws in full color"); let dialog = nodes.iter().find(|(_, n)| n.role() == Role::Dialog).and_then(|(_, n)| n.bounds()).expect("the dialog"); assert!(list.x1 <= chip.x0, "the chip {chip:?} follows the list {list:?}"); assert!(chip.y0 < list.y1 && list.y0 < chip.y1, "the chip {chip:?} shares the list's row {list:?}"); diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 542a3e8c41..ff7e67707a 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6"; +const REV: &str = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 06fc6592993e009c12ca8db5bf2f749ef9cf778e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 04:19:34 -0800 Subject: [PATCH 055/106] Scripts: empty paths scale their strokes and refuse a compound's pattern resize and transform with changeLineWidths equal to the scale now scale the strokes, dashes and effects of a path with no anchors, as they do for a path with anchors. A member with no anchors of a compound path or compound shape that shows a pattern is refused when the call transforms patterns, as a path with a pattern of its own is. node.move's description and docs/mcp.md now say that a compound path on a locked artboard takes a path while it is new art there and still selected. --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/script/dom/paths.rs | 2 +- crates/engine/src/script/dom/transform.rs | 27 +++++++++++++++------ crates/engine/src/tests/panelcmds.rs | 24 ++++++++++++++++++ crates/engine/src/tests/script_dom_paths.rs | 27 +++++++++++++++++++++ docs/mcp.md | 4 +-- 6 files changed, 74 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 15b4c96670..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 whose layer and groups are shown and unlocked and that is not on a locked artboard, 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 ), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index eaff2ab678..43b2982ce0 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -400,7 +400,7 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { /// The object whose paint the path `n` with id `id` shows: its compound path or compound shape /// when it is a member of one, since the paint commands paint that owner in its place. -fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node { +pub(super) fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node { d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) } diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 9bbc8c1cd2..f2f558fcd0 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -194,13 +194,15 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, if matrix::singular(m) { return Err(HostError::Error("the transformation is singular and would flatten the object".into())); } - let (locked, hidden, on_locked, bounds, uses_pattern, clipped) = with_doc(h, item.doc, |_, st| { + let (locked, hidden, on_locked, bounds, uses_pattern, shows_pattern, clipped) = with_doc(h, item.doc, |_, st| { let d = &st.doc; let line = d.ancestry(item.id); let mut locked = line.as_ref().is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked))); let hidden = line.as_ref().is_none_or(|a| a.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(|n| !n.visible))); - let (mut uses, mut clipped) = (false, false); + let (mut uses, mut shows, mut clipped) = (false, false, false); if let Some(n) = d.node(item.id) { + // A member of a compound path or compound shape shows its compound's paint. + shows = vectorcraft_doc::pattern::uses_pattern(paths::paint_owner(d, item.id, n), None); n.walk(&mut |c| { locked |= c.locked; uses |= vectorcraft_doc::pattern::uses_pattern(c, None); @@ -208,7 +210,7 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, matches!(c.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. } | vectorcraft_doc::NodeKind::Layer { clip: true, .. }); }); } - (locked, hidden, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses, clipped) + (locked, hidden, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses, shows || uses, clipped) }); if locked { return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0))); @@ -235,11 +237,20 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, // A path with no anchors has no bounds to turn or scale about, and turning or scaling it // changes nothing; only a stroke weight the call sets is applied. A pattern it uses has no // point to turn or scale about either, so a call that asks to transform it is refused. - (Some(_), None) if paths::is_path(h, item) && !(opts.patterns && uses_pattern) => { - if let Some(w) = weight { - paths::set_stroke_weight(h, item, w)?; - } - return Ok(Data::Undefined); + (Some(_), None) if paths::is_path(h, item) && !(opts.patterns && shows_pattern) => { + // A call that scales strokes and effects with the object still scales the path's own + // strokes and effects, as for a path with anchors. + return atomically(h, |h| { + if opts.strokes { + let c = on_page(m, Point::ORIGIN).as_coeffs(); + let p = json!({"ids": [item.id.0], "matrix": c, "objects": true, "patterns": false, "strokes": true}); + edit_item(h, item, "object.transform", &p)?; + } + if let Some(w) = weight { + paths::set_stroke_weight(h, item, w)?; + } + Ok(Data::Undefined) + }); } (Some(_), None) => return Err(HostError::Error("the object has no bounds".into())), (None, _) => Point::ORIGIN, 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_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index db02ff3742..155f99c1bc 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1806,6 +1806,33 @@ fn transforming_the_pattern_of_an_empty_path_is_refused() { } } +/// A member with no anchors of a compound path that shows a pattern is refused as a path with a +/// pattern of its own is, since the pattern it shows is its compound's. +#[test] +fn transforming_the_compound_pattern_of_an_empty_member_is_refused() { + let (mut s, _) = doc_with_paints(); + s.execute("paint.setFill", &json!({"swatch": "Dots"})).unwrap(); + log(&mut s, "var d = app.activeDocument, n = d.pathItems.add(), c = d.compoundPathItems.add(); n.move(c, ElementPlacement.PLACEATBEGINNING);"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.compoundPathItems[0].pathItems.length);"), vec![json!(1)]); + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems[0].rotate(90, true, true, true, true, Transformation.TOPLEFT);"); + assert!(e.contains("the object has no bounds"), "{e}"); + assert_eq!((art(&s), undo_steps(&s)), (before, steps)); +} + +/// 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/docs/mcp.md b/docs/mcp.md index aa3d561e59..b493faaae9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3369,7 +3369,7 @@ through `$`: 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 (its layer and - groups shown and unlocked too, and not on a locked artboard), where the path + 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 @@ -8332,7 +8332,7 @@ and `layerRows`, the rows highlighted in the panel. 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 whose layer and groups are also shown and unlocked and that is not on - a locked artboard (see `object.newGroup` for the paint the path keeps or takes). A row that + 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, From 45388081a86c1adc60bb084167631e7c6aaede30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 04:40:25 -0800 Subject: [PATCH 056/106] xtask: test-lint census exits ignore closure bodies and return operands When the census rule asks whether a write can run at all, a return statement directly before it in the closure or async block now rules it out, while a return inside a condition still leaves it possibly executed. A return or ? in an expression-bodied closure (`let _f = || return;`) leaves only that closure, not the enclosing async block. The operand of a return (`return app.run(c);`) runs before the return, and a call after a bare return in a tuple element does not. A ? after whitespace or a comment (`prepare() ?;`) is still an exit. --- xtask/src/test_lint.rs | 121 +++++++++++++++++++++++++++++++++++------ 1 file changed, 105 insertions(+), 16 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 50c4187406..1cc0760571 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2566,7 +2566,9 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac let async_kw = async_block_keyword(b, prefix_at, open).map(|(kw, _)| kw); // A closure body, an async block or a nested `for` body can be left before the call // (`block_on(async { if skip { return; } app.run(c); })`) while the loop's assertions still run. - let left_early = !may_run && (async_kw.is_some() || nested_for || closure_params_head(prefix)) && exits_before(b, open, start, nested_for); + // When `may_run` asks whether the call can run at all, only an exit that always runs first + // (`|| { return; input = fallback(); }`) rules it out. + let left_early = (async_kw.is_some() || nested_for || closure_params_head(prefix)) && exits_before(b, open, start, nested_for, may_run); if prefix.ends_with(b"||") || prefix.ends_with(b"&&") { if left_early || !runs_with_assertion_within(b, from, to, open, &active, may_run) { return false; @@ -2930,23 +2932,63 @@ fn closure_params_head(head: &[u8]) -> bool { /// a `return` or a `?`, and a loop body (`loop_body`) by a `break` or a `continue` (a `return` or `?` /// there leaves the test, and the assertions with it). An exit inside a nested closure or async /// block leaves only that one, and a `break` or `continue` inside a nested loop leaves only that loop. -fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool) -> bool { - let nested = |at: usize, loops: bool| { - (open + 1..at).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).any(|inner| { - let stmt = (open + 1..inner).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); - let head = b[stmt..inner].trim_ascii(); - closure_params_head(head) - || async_block_keyword(b, stmt, inner).is_some() - || (loops - && [b"for".as_slice(), b"while", b"loop"] - .iter() - .any(|kw| head.starts_with(kw) && !head.get(kw.len()).copied().is_some_and(is_ident))) +/// A `return` whose operand holds `start` (`return app.run(c);`) runs the call first. With `definite`, +/// only an exit that always runs counts: a `return`, `break` or `continue` statement directly in the +/// block, not one in a nested block and not a `?`. +fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: bool) -> bool { + // The innermost block in `b[open..]` that encloses `at`. + let innermost = |at: usize| (open..at).rev().find(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).unwrap_or(open); + // Whether `b[from..to]` stays inside one expression: no `;` or `,` and no unmatched closing + // bracket outside nested brackets. + let one_expression = |from: usize, to: usize| { + let mut depth = 0usize; + b[from..to].iter().all(|&c| match c { + b'(' | b'[' | b'{' => { + depth += 1; + true + } + b')' | b']' | b'}' => depth.checked_sub(1).map(|d| depth = d).is_some(), + b';' | b',' => depth > 0, + _ => true, }) }; - let returns = words(b, b"return", open + 1, start).into_iter().any(|at| !nested(at, false)); - let tries = (open + 2..start).any(|i| b[i] == b'?' && (is_ident(b[i - 1]) || matches!(b[i - 1], b')' | b']')) && !nested(i, false)); - let loops = - loop_body && [b"break".as_slice(), b"continue"].iter().any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true))); + // An expression-bodied closure (`|| return`, `|x| x?`) whose body holds `at`. The pipe at `p` + // ends the parameter list, so the `||` of `skip || return` is read as a whole. + let in_expression_closure = |at: usize| { + let stmt = (open + 1..at).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); + (stmt..at).any(|p| b[p] == b'|' && b[p + 1] != b'|' && closure_params_head(b[stmt..=p].trim_ascii()) && one_expression(p + 1, at)) + }; + let nested = |at: usize, loops: bool| { + (!loops && in_expression_closure(at)) + || (open + 1..at).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| at < close)).any(|inner| { + let stmt = (open + 1..inner).rev().find(|&i| matches!(b[i], b';' | b'{' | b'}')).map_or(open + 1, |i| i + 1); + let head = b[stmt..inner].trim_ascii(); + closure_params_head(head) + || async_block_keyword(b, stmt, inner).is_some() + || (loops + && [b"for".as_slice(), b"while", b"loop"] + .iter() + .any(|kw| head.starts_with(kw) && !head.get(kw.len()).copied().is_some_and(is_ident))) + }) + }; + // A statement that starts at `at` directly in the block, and ends before `start`. + let always = |at: usize| { + innermost(at) == open + && b[open + 1..at].trim_ascii_end().last().is_none_or(|c| matches!(c, b';' | b'{' | b'}')) + && matching(b, open).is_some_and(|close| statement_end(&b[..close], at) < start) + }; + let returns = + words(b, b"return", open + 1, start).into_iter().any(|at| !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); + let tries = !definite + && (open + 2..start).any(|i| { + b[i] == b'?' + && (open + 1..i).rev().find(|&p| !b[p].is_ascii_whitespace()).is_some_and(|p| is_ident(b[p]) || matches!(b[p], b')' | b']')) + && !nested(i, false) + }); + let loops = loop_body + && [b"break".as_slice(), b"continue"] + .iter() + .any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true) && (!definite || always(at)))); if loop_body { loops } else { returns || tries } } @@ -10949,6 +10991,53 @@ mod tests { [], "a return in a nested closure with a return type does not leave the async block" ); + assert_eq!( + census("let mut input = c; let mut reset = || { return; input = fallback(); }; reset(); app.run(input); assert!(menu(c).is_some());"), + [], + "a write after a return statement in a called closure never runs" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { if skip { return; } input = fallback(); }; reset(); app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a write after a conditional return in a called closure may run" + ); + assert_eq!( + census("block_on(async { let _f = || return; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a nested expression-bodied closure does not leave the async block" + ); + assert_eq!( + census("block_on(async { return app.run(c); }); assert!(menu(c).is_some());"), + [], + "the operand of a return runs before the return" + ); + assert_eq!( + census("block_on(async { let _ = (return, app.run(c)); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a call after a bare return in a tuple is not its operand" + ); + assert_eq!( + census("block_on(async { let _ = skip || return; app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return after a logical or is not in a closure" + ); + assert_eq!( + census("block_on(async { let _ = (|| 1, return); app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return after a closure in an earlier tuple element is not in that closure" + ); + assert_eq!( + census("block_on(async { prepare() /* why */ ?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? after a comment can leave a polled async block" + ); + assert_eq!( + census("block_on(async { prepare() ?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? after whitespace can leave a polled async block" + ); assert_eq!( census("let mut input = c; block_on(async move { input = fallback(); render(input, offset); }); assert!(menu(c).is_some());"), [(2, "census")], From 0613c48c50874c71b6b1b86d4cd214689703d0b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 05:07:36 -0800 Subject: [PATCH 057/106] xtask: test-lint census exits read match alternatives and skip stringify! A single pipe now ends a closure's parameter list only when an opening pipe stands in a closure position, so the `|` of a match arm such as `0 | 1 => return` no longer hides that return from the census rule. A closure that a match arm yields (`_ => |_: ()| return`) still keeps its return to itself. A `?` inside the arguments of `stringify!` is not evaluated and no longer counts as an exit from the enclosing async block. --- xtask/src/test_lint.rs | 48 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 7 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 1cc0760571..c372e4c971 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2919,13 +2919,16 @@ fn closure_params_head(head: &[u8]) -> bool { Some(p) if head[p + 1..].trim_ascii_start().starts_with(b"->") => &head[..=p], _ => head, }; - let Some(rest) = head.strip_suffix(b"||") else { - return head.ends_with(b"|"); - }; - let rest = rest.trim_ascii_end(); - rest.is_empty() - || matches!(rest.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) - || [b"move".as_slice(), b"async"].iter().any(|kw| rest.strip_suffix(*kw).is_some_and(|h| !h.last().copied().is_some_and(is_ident))) + // A single closing pipe needs its opening pipe in a closure position: `0 | 1` in a match arm and + // `a | b` are not parameter lists. + let rest = + head.strip_suffix(b"||").or_else(|| head.strip_suffix(b"|").and_then(|params| params.iter().rposition(|&c| c == b'|').map(|o| ¶ms[..o]))); + rest.map(<[u8]>::trim_ascii_end).is_some_and(|rest| { + rest.is_empty() + || matches!(rest.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) + || rest.ends_with(b"=>") + || [b"move".as_slice(), b"async"].iter().any(|kw| rest.strip_suffix(*kw).is_some_and(|h| !h.last().copied().is_some_and(is_ident))) + }) } /// Whether the block opening at `open` can be left before `start`: a closure body or async block by @@ -2979,9 +2982,19 @@ fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: }; let returns = words(b, b"return", open + 1, start).into_iter().any(|at| !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); + // The arguments of `stringify!` are not evaluated. + let unevaluated: Vec<(usize, usize)> = calls_at(b, open + 1, start) + .iter() + .filter(|(_, name, _)| name == "stringify!") + .filter_map(|(p, name, _)| { + let o = skip_ws(b, p + name.len()); + matching(b, o).map(|c| (o, c)) + }) + .collect(); let tries = !definite && (open + 2..start).any(|i| { b[i] == b'?' + && !unevaluated.iter().any(|&(o, c)| o < i && i < c) && (open + 1..i).rev().find(|&p| !b[p].is_ascii_whitespace()).is_some_and(|p| is_ident(b[p]) || matches!(b[p], b')' | b']')) && !nested(i, false) }); @@ -11102,6 +11115,27 @@ mod tests { ); } + #[test] + fn census_exits_count_match_alternatives_and_skip_stringify() { + let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); + let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::>(); + assert_eq!( + census("block_on(async { match mode { 0 | 1 => return, _ => {} } app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return in a match arm with alternatives can leave a polled async block" + ); + assert_eq!( + census("block_on(async { let _f = match mode { _ => |_: ()| return }; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return in a closure that a match arm yields leaves only that closure" + ); + assert_eq!( + census("block_on(async { let _ = stringify!(prepare() ?); app.run(c); }); assert!(menu(c).is_some());"), + [], + "a ? inside stringify! is not evaluated" + ); + } + #[test] fn census_keeps_guards_around_nested_arguments() { let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n"); From 6ec484819a0ed892ef051e2937a784072ca4dd53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 06:08:23 -0800 Subject: [PATCH 058/106] xtask: test-lint census guards apply only to the operand they control - An `&&` left of an `||` alternative belongs to the `||`'s left operand, so `false && ready || { reset(); true }` now counts the reset. A group that holds the alternative (`false && (a || b)`) is still guarded by the outer `&&`. - A `?` after a block expression (`{ prepare() }?`) can leave a polled async block. A block that is the body of an expression closure (`|| { ... }?`) leaves only that closure. - `return`, `break` and `continue` inside `stringify!` are not evaluated, and a call inside `stringify!` does not feed the entry. --- xtask/src/test_lint.rs | 93 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 86 insertions(+), 7 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index c372e4c971..e4c8ecde36 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2353,13 +2353,27 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { let numeric = numeric && operands > 0; s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None") }; + // The arguments of `stringify!` are not evaluated, so a call there does not run. + let unevaluated: Vec<(usize, usize)> = calls_at(b, from, to) + .iter() + .filter(|(_, name, _)| name == "stringify!") + .filter_map(|(p, name, _)| { + let o = skip_ws(b, p + name.len()); + matching(b, o).map(|c| (o, c)) + }) + .collect(); (from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| { let mut start = name_end; while start > from && is_ident(b[start - 1]) { start -= 1; } let name = String::from_utf8_lossy(&b[start..name_end]); - if start == name_end || LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() || !runs_with_assertion(b, from, to, start) { + if start == name_end + || LOOKUPS.contains(&name.as_ref()) + || b[start].is_ascii_digit() + || unevaluated.iter().any(|&(o, c)| o < start && start < c) + || !runs_with_assertion(b, from, to, start) + { return false; } let Some(close) = matching(b, open).filter(|&c| c < to) else { return false }; @@ -2655,6 +2669,9 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac .collect(); let mut closure = None; let mut sibling = false; + // Set after an `||` that may run the call: every `&&` further left belongs to its left operand + // (`false && ready || reset()`), so it does not guard the call, until an enclosing group opens. + let mut alternative = false; for i in (stmt + 1..start).rev() { if let Some(&(pipe, _)) = params.iter().find(|&&(pipe, end)| pipe <= i && i <= end) { // A closure that encloses the call at its own level, not a sibling element. @@ -2665,7 +2682,10 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } match b[i] { b')' | b']' | b'}' => depth += 1, - b'(' | b'[' | b'{' if depth == 0 => sibling = false, + b'(' | b'[' | b'{' if depth == 0 => { + sibling = false; + alternative = false; + } b'(' | b'[' | b'{' => depth -= 1, _ => {} } @@ -2683,6 +2703,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } if b[i] == b'&' && b[i - 1] == b'&' + && !alternative && ((!may_run && b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}')) && !asserted_conjunction(b, from, to, i - 1)) @@ -2701,6 +2722,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac { // A literal `true` always skips the right side; any other operand may let it run. if may_run && !literal_operand(b, stmt, i - 1, b"true") { + alternative = true; continue; } return false; @@ -2980,8 +3002,6 @@ fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: && b[open + 1..at].trim_ascii_end().last().is_none_or(|c| matches!(c, b';' | b'{' | b'}')) && matching(b, open).is_some_and(|close| statement_end(&b[..close], at) < start) }; - let returns = - words(b, b"return", open + 1, start).into_iter().any(|at| !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); // The arguments of `stringify!` are not evaluated. let unevaluated: Vec<(usize, usize)> = calls_at(b, open + 1, start) .iter() @@ -2991,17 +3011,32 @@ fn exits_before(b: &[u8], open: usize, start: usize, loop_body: bool, definite: matching(b, o).map(|c| (o, c)) }) .collect(); + let evaluated = |at: usize| !unevaluated.iter().any(|&(o, c)| o < at && at < c); + let returns = words(b, b"return", open + 1, start) + .into_iter() + .any(|at| evaluated(at) && !one_expression(at, start) && !nested(at, false) && (!definite || always(at))); + // A `?` follows an operand: a name, a call or index, or a block expression (`{ prepare() }?`). let tries = !definite && (open + 2..start).any(|i| { b[i] == b'?' - && !unevaluated.iter().any(|&(o, c)| o < i && i < c) - && (open + 1..i).rev().find(|&p| !b[p].is_ascii_whitespace()).is_some_and(|p| is_ident(b[p]) || matches!(b[p], b')' | b']')) + && evaluated(i) + && (open + 1..i).rev().find(|&p| !b[p].is_ascii_whitespace()).is_some_and(|p| { + is_ident(b[p]) + || matches!(b[p], b')' | b']') + // A block operand that is the body of an expression closure + // (`|| { … }?`) leaves only that closure. + || (b[p] == b'}' + && (open + 1..p) + .rev() + .find(|&o| b[o] == b'{' && matching(b, o) == Some(p)) + .is_some_and(|o| !in_expression_closure(o))) + }) && !nested(i, false) }); let loops = loop_body && [b"break".as_slice(), b"continue"] .iter() - .any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| !nested(at, true) && (!definite || always(at)))); + .any(|kw| words(b, kw, open + 1, start).into_iter().any(|at| evaluated(at) && !nested(at, true) && (!definite || always(at)))); if loop_body { loops } else { returns || tries } } @@ -11134,6 +11169,50 @@ mod tests { [], "a ? inside stringify! is not evaluated" ); + assert_eq!( + census("block_on(async { let _ = stringify!(return); app.run(c); }); assert!(menu(c).is_some());"), + [], + "a return inside stringify! is not evaluated" + ); + assert_eq!( + census("for _ in [1] { let _ = stringify!(continue); app.run(c); } assert!(menu(c).is_some());"), + [], + "a continue inside stringify! does not skip the call in a nested for body" + ); + assert_eq!( + census("block_on(async { return; let _ = stringify!(x); app.run(c); }); assert!(menu(c).is_some());"), + [(2, "census")], + "a return outside stringify! still leaves the block" + ); + assert_eq!( + census("block_on(async { { prepare() }?; app.run(c); Ok(()) }); assert!(menu(c).is_some());"), + [(2, "census")], + "a ? after a block expression can leave a polled async block" + ); + assert_eq!( + census("block_on(async { let _f = || { Some(Some(())) }?; app.run(c); }); assert!(menu(c).is_some());"), + [], + "a ? after the block body of an expression closure leaves only that closure" + ); + assert_eq!( + census("let _ = stringify!(app.run(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "a call inside stringify! does not run, so it does not feed the entry" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; false && ready || { reset(); true }; app.run(input); assert!(menu(c).is_some());" + ), + [(2, "census")], + "a literal false left of && guards only its own operand, not the || alternative" + ); + assert_eq!( + census( + "let mut input = c; let mut reset = || { input = fallback(); }; false && (ready || { reset(); true }); app.run(input); assert!(menu(c).is_some());" + ), + [], + "a literal false left of && still guards a group that holds the || alternative" + ); } #[test] From cb837fa47a56db82dc93fd834fce399e1ef0b66e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 07:08:20 -0800 Subject: [PATCH 059/106] xtask: test-lint census skips stringified helpers and reads struct closure params An asserting helper inside `stringify!` is not evaluated, so it no longer counts as a check that runs for each entry. Closure parameter lists may now hold struct patterns (`|Row { c }|`), so a parameter that shadows the entry is seen. A path segment in a pattern (`entry::Row { .. }`) does not bind a name. --- xtask/src/test_lint.rs | 108 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 99 insertions(+), 9 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index e4c8ecde36..3b12d7c30e 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -2052,10 +2052,16 @@ fn census(v: &View, helpers: &HashSet) -> Vec { // Failure messages run only after an assertion has failed, so a check there does not count. let unmessaged = v.body_without_messages(); let helpers_in = |from: usize, to: usize| -> Vec { - calls(&unmessaged, from - v.t.open, to - v.t.open) + let (f, t) = (from - v.t.open, to - v.t.open); + let unevaluated = stringify_args(&unmessaged, f, t); + calls_at(&unmessaged, f, t) .into_iter() - .filter(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)) - .map(|(n, _)| n) + .filter(|(at, n, method)| { + !(n.ends_with('!') && is_assert_macro(n)) + && is_helper_call(n, *method, helpers) + && !unevaluated.iter().any(|&(o, c)| o < *at && *at < c) + }) + .map(|(_, n, _)| n) .collect() }; let weak_in = |from: usize, to: usize, var: &str| { @@ -2129,7 +2135,9 @@ fn pattern_names(pattern: &str) -> impl Iterator + '_ { // Inside braces, `name:` labels a field; outside them it starts a type (`let x: u32`). let in_braces = b[..at].iter().filter(|&&c| c == b'{').count() > b[..at].iter().filter(|&&c| c == b'}').count(); let next = end + b[end..].iter().take_while(|c| c.is_ascii_whitespace()).count(); - !in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':') + // A path segment (`entry::Row { .. }`, `Kind::empty`) names a module or an item. + let path = b[next..].starts_with(b"::") || pattern[..at].trim_end().ends_with("::"); + !path && (!in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':')) }) .map(move |(at, end)| &pattern[at..end]) .filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_')) @@ -2180,7 +2188,7 @@ fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool { } // Each parameter binds the names before its type. let params = String::from_utf8_lossy(&b[at + 1..end]).into_owned(); - let names: Vec = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::>()).collect(); + let names: Vec = closure_param_patterns(¶ms).into_iter().flat_map(|p| pattern_names(p).collect::>()).collect(); shadows.extend(names.into_iter().map(|n| (n, at + 1, until))); } // The scopes of nested loop patterns and closure parameters, where an assignment to the name @@ -2544,6 +2552,23 @@ fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool { runs_with_assertion_within(b, from, to, start, &[], false) } +/// Whether `at` lies in the arguments of a `stringify!` in `b[from..to]`, which are not evaluated. +fn in_stringify(b: &[u8], from: usize, to: usize, at: usize) -> bool { + stringify_args(b, from, to).iter().any(|&(open, close)| open < at && at < close) +} + +/// The brackets around the arguments of each `stringify!` in `b[from..to]`. +fn stringify_args(b: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { + calls_at(b, from, to) + .into_iter() + .filter(|(_, name, _)| name == "stringify!") + .filter_map(|(p, name, _)| { + let open = skip_ws(b, p + name.len()); + matching(b, open).map(|close| (open, close)) + }) + .collect() +} + /// Checks whether `start` runs whenever assertions pass, or may run at all when `may_run` is true. /// `active` holds positions being checked so recursive closure calls terminate. fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize], may_run: bool) -> bool { @@ -2552,7 +2577,7 @@ fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, ac } let mut active = active.to_vec(); active.push(start); - if in_uncalled_closure(b, from, to, start, &active, may_run) { + if in_stringify(b, from, to, start) || in_uncalled_closure(b, from, to, start, &active, may_run) { return false; } // Check enclosing blocks independently of the call's statement: an earlier semicolon inside @@ -2812,10 +2837,54 @@ fn parenthesized_closure_binding_head<'a>(b: &[u8], stmt: usize, start: usize, m /// The `|` that closes the closure parameter list opened by the `|` at `pipe`, before `to`, when the /// text between them can be a parameter list. Parameters may carry types (`|c: Command|`, -/// `|p: &[u8; 4]|`, `|f: fn() -> bool|`), but not a block, a string, a method call or an assignment. +/// `|p: &[u8; 4]|`, `|f: fn() -> bool|`) and struct patterns (`|Row { c, .. }|`), but not a block, +/// a string, a method call or an assignment. fn closure_params_end(b: &[u8], pipe: usize, to: usize) -> Option { - let end = (pipe + 1..to).find(|&i| b[i] == b'|')?; - (!b[pipe + 1..end].iter().any(|c| matches!(c, b'{' | b'}' | b'"' | b'.' | b'='))).then_some(end) + let mut i = pipe + 1; + loop { + match b[..to].get(i)? { + b'|' => break Some(i), + b'"' | b'.' | b'=' | b'}' => break None, + b'{' => { + // A struct pattern follows its path (`Row {`); its braces hold names, labels and `..`. + let named = b[pipe + 1..i].trim_ascii_end().last().copied().is_some_and(is_ident); + let close = matching(b, i).filter(|&c| c < to && named)?; + if b[i + 1..close].iter().any(|c| matches!(c, b'"' | b'=' | b';' | b'{' | b'}')) { + break None; + } + i = close + 1; + } + _ => i += 1, + } + } +} + +/// The patterns of a closure parameter list `params` without their types: the text of each +/// top-level parameter before its `:` (`c` in `c: Command`, `Row { c: other }` in `Row { c: other }: Row`). +fn closure_param_patterns(params: &str) -> Vec<&str> { + let b = params.as_bytes(); + let (mut out, mut depth, mut start, mut typed) = (vec![], 0usize, 0, false); + for (i, &c) in b.iter().enumerate() { + match c { + b'(' | b'[' | b'{' | b'<' => depth += 1, + b')' | b']' | b'}' | b'>' => depth = depth.saturating_sub(1), + b':' if depth == 0 && !typed && b.get(i + 1) != Some(&b':') && (i == 0 || b[i - 1] != b':') => { + out.push(¶ms[start..i]); + typed = true; + } + b',' if depth == 0 => { + if !typed { + out.push(¶ms[start..i]); + } + (start, typed) = (i + 1, false); + } + _ => {} + } + } + if !typed { + out.push(¶ms[start..]); + } + out } /// The head before a closure's parameters with a trailing `move` and `async` removed, and whether @@ -11199,6 +11268,27 @@ mod tests { [(2, "census")], "a call inside stringify! does not run, so it does not feed the entry" ); + assert_eq!( + census("let _ = stringify!(verify_entry(c)); assert!(menu(c).is_some());"), + [(2, "census")], + "an asserting helper inside stringify! does not run" + ); + assert_eq!(census("verify_entry(c); assert!(menu(c).is_some());"), [], "an asserting helper that runs checks each entry"); + assert_eq!( + census("let run = |Row { c }| { render(c, offset); }; run(fallback()); assert!(menu(c).is_some());"), + [(2, "census")], + "a struct pattern in closure parameters shadows the entry" + ); + assert_eq!( + census("let run = |Row { c: other }| { render(c, other); }; run(fallback()); assert!(menu(c).is_some());"), + [], + "a field label in a closure's struct pattern binds the name after it, not the entry" + ); + assert_eq!( + census("let run = |c::Row { offset }| { render(c, offset); }; run(fallback()); assert!(menu(c).is_some());"), + [], + "a path segment in a closure's struct pattern does not bind the name" + ); assert_eq!( census( "let mut input = c; let mut reset = || { input = fallback(); }; false && ready || { reset(); true }; app.run(input); assert!(menu(c).is_some());" From 44c96976be7058d496c6e519c77fbd03029cc8a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 3 Dec 2026 09:39:08 -0800 Subject: [PATCH 060/106] New Document: draw the Background Contents chip without PaintChip::display_only craft-libs on the rev main pins has no display-only PaintChip yet (storytold/craft-libs#4953 is open), so the craft-libs revs and xtask/src/pdf_deps.rs REV go back to main's pin, and the dialog draws the swatch-size chip with its own small component until #4953 merges. The chip is a color well named "Background Contents swatch", valued with the hex or "No Color", read-only, with no click, no focus and the arrow cursor, and it draws at full color. The test also checks it is read-only. --- Cargo.lock | 172 ++++++++++----------- apps/vectorcraft-web/Cargo.toml | 2 +- crates/ui-egui/src/dialogs/new_document.rs | 135 ++++++++++++++-- xtask/src/pdf_deps.rs | 2 +- 4 files changed, 213 insertions(+), 98 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 257f1690b7..75c87011b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -1848,7 +1848,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "serde", @@ -1859,7 +1859,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1871,7 +1871,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "async-channel", "async-io", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1913,7 +1913,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -1937,7 +1937,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1948,7 +1948,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-eps", "flate2", @@ -1962,7 +1962,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "encoding_rs", "flate2", @@ -1973,7 +1973,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "dispatch2", "egui", @@ -1986,7 +1986,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -2005,7 +2005,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-atomic", "craft-host", @@ -2022,7 +2022,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fax", "hayro-ccitt", @@ -2033,7 +2033,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2054,7 +2054,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2066,7 +2066,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2099,7 +2099,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2114,7 +2114,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-atomic", "craft-behavior", @@ -2129,7 +2129,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2139,7 +2139,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2148,7 +2148,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2163,12 +2163,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2182,7 +2182,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -2199,7 +2199,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "accesskit", "craft-behavior", @@ -2237,7 +2237,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2248,7 +2248,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2266,7 +2266,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2287,7 +2287,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2308,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-behavior", "craft-host", @@ -2327,7 +2327,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.22.1", "chrono", @@ -2359,7 +2359,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "serde", @@ -2370,7 +2370,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2380,7 +2380,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "js-sys", "serde_json", @@ -2391,7 +2391,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "winsafe", ] @@ -2399,7 +2399,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "craft-appkit", "craft-atomic", @@ -2431,7 +2431,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3790,7 +3790,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3799,7 +3799,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3817,7 +3817,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3835,12 +3835,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "flate2", "hayro-ccitt", @@ -4823,7 +4823,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4980,7 +4980,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb#8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb" +source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index ebf926348a..70aae32f73 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8bdbc9e2f9db47bfb739b6cdec958a93b3ab0beb", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 700644bd6a..3b371ffad9 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -20,12 +20,14 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::{Background, ColorMode, Unit}; use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, ProfileFile, RASTER_PPI}; -use craft::behavior::{ColumnWidth, IconId}; -use craft::color_ui::ui::{Paint, PaintChip, PaintChipSize}; +use craft::behavior::{ColumnWidth, CursorIcon, IconId, Input, Metrics, PartKey, Sense}; use craft::theme::Srgba; use craft::ui::buttons::Button; -use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, clicked}; +use craft::ui::choice::{Checkbox, Segmented, SwatchMetrics}; +use craft::ui::contract::{ + Access, Bind, Common, Component, Cx, Entry, FieldLayout, Gap, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _, ShowContainer as _, + SideLabel, Sizing, clicked, +}; use craft::ui::display::{Shade, Text}; use craft::ui::form::Field; use craft::ui::layout::CellAlign; @@ -36,10 +38,12 @@ use craft::ui::patterns::form_dialogs::{ use craft::ui::patterns::presets::{GroupPath, NamedPresetEvent, PresetLibrary}; use craft::ui::pickers::Select; use craft::ui::popover::Popover; +use craft::ui::primitives::{PaintShape, StrokeWidth}; use craft::ui::runtime::env::{Env, Label, LengthUnits, UnitKind}; use craft::ui::sections::Section; -use craft::ui::style::TypeRole; +use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx, TypeRole}; use craft::ui::text::{LinkMode, LinkedWords, NumberField, follow_equal, link_toggle}; +use egui::{Color32, Rect, Response, Vec2}; use super::host::open_held; use crate::VectorcraftApp; @@ -414,12 +418,122 @@ fn built_in_card(preset: &DocSettings, values: &VcNewDocument, orientation: Opti /// The chip after Background Contents: the paper white, or No Color for transparent. It shows the choice and opens /// nothing. It is display-only: it is not a Tab stop, offers no click and draws in full color. fn background_chip(ui: &mut egui::Ui, background: Background) { - let paint = match background { - Background::White => Paint::Solid(Srgba::WHITE), - Background::Transparent => Paint::None, - }; let name = crate::i18n::fmt(tl!("{row} swatch"), &[("row", tl!("Background Contents"))]); - PaintChip::new(name, Bind::given(paint), Srgba::WHITE).chip_size(PaintChipSize::Swatch).display_only().show(ui); + BackgroundChip::new(name, background).show(ui); +} + +// TEMPORARY: craft-libs on the pinned rev has no display-only PaintChip, so this chip draws the swatch-size well +// itself. Replace it with `PaintChip::chip_size(PaintChipSize::Swatch).display_only()` once storytold/craft-libs#4953 +// merges and the pin moves past it. + +/// The No Color diagonal stops this many well heights short of the chip's edges, as PaintChip's does. +const NO_COLOR_INSET: f32 = 0.15; +/// A one-column rail's cell holds this many swatch chips to a row, as PaintChip's swatch size does. +const SWATCHES_PER_RAIL_BUTTON: f32 = 3.0; +/// The chip's well, which keeps the arrow cursor: the chip opens nothing. +const BACKGROUND_WELL: PartKey = PartKey::new("well"); + +/// The style of a [`BackgroundChip`]. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +pub(crate) struct BackgroundChipStyle { + #[style(metrics)] + metrics: Metrics, + /// The well's side. + side: f32, + /// The well's corners. + radius: egui::CornerRadius, + /// The ring on the well's outline. + edge: StyleColor, + /// The fill of No Color. + none_fill: StyleColor, + /// The No Color diagonal. + none_mark: StyleColor, +} + +/// A swatch-size color well that shows the Background Contents choice: white, or No Color for transparent. +/// +/// - Pointer and keys: none; it is not a Tab stop and draws as an enabled chip. +/// - AccessKit: a color well named by the label, its value the hex or "No Color". +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(sample = background_chip_sample)] +pub(crate) struct BackgroundChip { + #[common] + common: Common, + background: Background, +} + +impl BackgroundChip { + /// A chip named `label` that shows `background`. + fn new(label: impl Into