From 2356ffe7475d85f079b6edfcb3f55f64da3386de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:55:12 -0800 Subject: [PATCH 01/28] Scripts: layers and groups give their own text frames Layer.textFrames and GroupItem.textFrames threw "not available yet". They now give a TextFrames collection with the members of the document's: length, [i], index, getByName, add, pointText, areaText, pathText and removeAll. It lists the type directly in the layer or group, topmost first, as the layer's other collections do, and new type goes on top of the layer's or group's contents whatever the current layer. A hidden or locked layer or group throws and changes nothing. text.create takes a parent: a shown, unlocked layer or group that the new type goes on top of, whatever the drawing mode. Area type and type on a path are moved there with node.move in the same step. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/create.rs | 41 +++++++- crates/engine/src/script/dom/layers.rs | 29 +++++- crates/engine/src/script/dom/text.rs | 96 ++++++++++++++----- crates/engine/src/tests/script_text.rs | 87 +++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 4 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 7 files changed, 229 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..feb2505258 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -155,7 +155,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -885,7 +885,38 @@ fn path_create(s: &mut Session, p: &Value) -> Result { add_look(s, "Pen", path_kind(path, None), look, None) } +/// The shown, unlocked layer or group `text.create`'s `parent` names, if it names one. +fn text_parent(s: &Session, p: &Value) -> Result> { + const C: &str = "text.create"; + let Some(parent) = object_param(p, "parent", C)? else { return Ok(None) }; + let d = &s.doc()?.doc; + let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) }; + if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() { + return Err(bad(C, format!("{} is not a layer or group", parent.0))); + } + if !d.is_editable(parent) { + return Err(bad(C, "the layer or group is hidden or locked")); + } + Ok(Some(parent)) +} + +/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected. +fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result { + let id = s.edit("Type", |d, sel| { + let id = d.alloc_id(); + let mut n = Node::new(id, kind); + NewArt::plain(Appearance::default()).apply(d, &mut n); + super::object::align_new_object(d, &mut n); + n.bbox_angle = bbox_angle; + d.insert(Some(parent), usize::MAX, n)?; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + fn text_create(s: &mut Session, p: &Value) -> Result { + let parent = text_parent(s, p)?; let x = f64_req(p, "x", "text.create")?; let y = f64_req(p, "y", "text.create")?; super::paint::check_keep_model(p, "text.create")?; @@ -922,8 +953,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result { // Lays the text out (and sizes an Auto Size frame). super::typecmd::refresh_bounds(&mut t); } - let made = - insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?; + let made = match parent { + Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?, + None => { + insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)? + } + }; let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3fafaf684b..b315aab2e0 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 `textFrames`, and a compound path's +//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` //! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. @@ -65,6 +65,8 @@ enum Kind { Group, /// Compound paths (`CompoundPathItem`). Compound, + /// Type (`TextFrame`), whose collection's other members are in `text.rs`. + Text, } impl Kind { @@ -73,6 +75,7 @@ impl Kind { Kind::Any => "PageItems", Kind::Group => "GroupItems", Kind::Compound => "CompoundPathItems", + Kind::Text => "TextFrames", } } @@ -81,6 +84,7 @@ impl Kind { Kind::Any => typename(n).is_some(), Kind::Group => typename(n) == Some("GroupItem"), Kind::Compound => typename(n) == Some("CompoundPathItem"), + Kind::Text => typename(n) == Some("TextFrame"), } } } @@ -845,6 +849,20 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +fn held_text(h: &Host, a: &[Data]) -> Answer { + held(h, a, Kind::Text) +} + +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +pub(super) fn text_scope(h: &Host, d: &Data) -> Result<(Doc, Option)> { + art_scope(h, d, Kind::Text.class()) +} + +/// The type objects directly in `container`, topmost first. +pub(super) fn text_list(h: &Host, st: &DocState, container: NodeId) -> Result>> { + art_list(h, st, Kind::Text, Some(container)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -897,8 +915,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)), + ("textFrames", get(l, held_text)), ]); - m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), @@ -1320,6 +1339,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("textFrames", get(l, held_text)), ("zOrderPosition", get(l, layer_z_position)), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)), ("isIsolated", get(l, layer_is_isolated)), @@ -1328,8 +1348,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)), + ["pathItems", "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/text.rs b/crates/engine/src/script/dom/text.rs index 233ba56621..556b0a113c 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1,4 +1,4 @@ -//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! Type in the script object model: the `textFrames` of a document, a layer and a group, each `TextFrame`, the `TextRange` of its //! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and //! `paragraphAttributes`, and `app.textFonts`, as the help pages //! , @@ -7,6 +7,9 @@ //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: +//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`, +//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden +//! or locked layer or group throws. //! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so //! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves //! out to the whole character. One item of `characters` is one code point. @@ -1231,32 +1234,46 @@ fn frame_ids(h: &Host, st: &DocState) -> Rc> { ids } +/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists. +fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + super::layers::text_scope(h, arg(a, 0)) +} + fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "TextFrames") + Ok(frames_scope(h, a)?.0) +} + +/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those +/// directly in a layer or group, topmost first. +fn listed(h: &Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { + match container { + None => Ok(frame_ids(h, st)), + Some(c) => super::layers::text_list(h, st, c), + } } fn frames_length(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) + let (doc, c) = frames_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64))) } fn frames_parent(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; - Ok(doc_ref(h, doc.uid)) + let (doc, c) = frames_scope(h, a)?; + Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c)))) } fn frames_at(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) } fn frames_by_name(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_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 = frame_ids(h, st); + let ids = listed(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| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -1284,29 +1301,40 @@ fn vertical_of(d: &Data) -> std::result::Result { } } -/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. -fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on +/// top of the contents of `container` when there is one. +fn point_text(h: &Host, (doc, container): (Doc, Option), anchor: Option<[f64; 2]>, vertical: bool) -> Answer { let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; - let (_, r) = - on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical}); + if let Some(c) = container { + check_open(h, doc, c)?; + if let Some(o) = params.as_object_mut() { + o.insert("parent".into(), json!(c.0)); + } + } + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", ¶ms))?; new_ref(h, doc, result_id(&r)) } +/// The error for a layer or group that takes no new type. +const SHUT_CONTAINER: &str = "the layer or group is hidden or locked"; + /// `add()`: empty point type at the origin. fn frames_add(h: &Host, a: &[Data]) -> Answer { - point_text(h, frames_doc(h, a)?, None, false) + point_text(h, frames_scope(h, a)?, None, false) } /// `pointText(anchor, orientation?)`. fn frames_point_text(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let scope = frames_scope(h, a)?; let anchor = point(arg(a, 1), "anchor")?; - point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) + point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?) } -/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves +/// it on top of the contents of the collection's layer or group when there is one. fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, container) = frames_scope(h, a)?; if handle_of(arg(a, 1), "PathItem").is_none() { return Err(HostError::Type("textPath must be a PathItem".into())); } @@ -1321,8 +1349,23 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { let vertical = vertical_of(arg(a, orientation))?; let mode = if on_path { "onPath" } else { "area" }; let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); - let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; - new_ref(h, doc, result_id(&r)) + let Some(c) = container else { + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + return new_ref(h, doc, result_id(&r)); + }; + check_open(h, doc, c)?; + let id = super::atomically(h, |h| { + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; + let id = result_id(&r).ok_or_else(|| HostError::Error("the command made no object".into()))?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?; + new_ref(h, doc, Some(id)) +} + +/// Refuses a hidden or locked layer or group as the place for new type. +fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> { + if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) } } /// `areaText(textPath, orientation?, baseFrame?, postFix?)`. @@ -1335,15 +1378,16 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3, 5, 6]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or +/// locked one stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { - let doc = frames_doc(h, a)?; + let (doc, c) = frames_scope(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { - let ids = frame_ids(h, st); + let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(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 type: {list}"))); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..a164ca396b 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -582,6 +582,93 @@ fn type_made_with_a_large_id_is_the_new_type() { assert_eq!(plain(&s, NodeId(big)), ""); } +/// A script that builds a layer `base` holding type `back`, a group `g` (type `g-text` and a +/// group `gg` holding type `gg-text`) and type `front`, a sublayer `sub` of it holding type +/// `sub-text`, and a layer `other` holding type `other-text`, which it leaves current. +const NESTED_TYPE: &str = "var d = app.activeDocument, L0 = d.layers[0]; L0.name = 'base';\ + function put(c, name, y) { var t = c.textFrames.pointText([20, y]); t.contents = name; t.name = name; return t; }\ + put(L0, 'back', 20); var g = L0.groupItems.add(); g.name = 'g'; put(g, 'g-text', 40);\ + var gg = g.groupItems.add(); gg.name = 'gg'; put(gg, 'gg-text', 60); put(L0, 'front', 80);\ + var sub = L0.layers.add(); sub.name = 'sub'; put(sub, 'sub-text', 100);\ + var L1 = d.layers.add(); L1.name = 'other'; put(L1, 'other-text', 120); d.activeLayer = L1;\ + function names(c) { var a = []; for (var i = 0; i < c.length; i++) a.push(c[i].name); return a.join(','); }"; + +#[test] +fn a_layers_and_a_groups_text_frames_list_only_their_own_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + &format!( + "{NESTED_TYPE} vc.log([names(L0.textFrames), names(g.textFrames), names(sub.textFrames), names(L1.textFrames)]);\ + vc.log([L0.textFrames.typename, L0.textFrames.parent.name, g.textFrames.parent.typename, g.textFrames.parent.name]);\ + vc.log([L0.textFrames.getByName('front').name, L0.textFrames.index(1).name, L0.textFrames[2] === undefined]);\ + vc.log(d.textFrames.length);" + ), + ); + assert_eq!(out[0], json!(["front,back", "g-text", "sub-text", "other-text"])); + assert_eq!(out[1], json!(["TextFrames", "base", "GroupItem", "g"])); + assert_eq!(out[2], json!(["front", "back", true])); + assert_eq!(out[3], json!(6)); + // Type inside the layer's group or sublayer is not the layer's own. + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.textFrames.getByName('gg-text');")); + assert!(e.contains("Not found"), "{e}"); +} + +#[test] +fn text_frames_of_a_layer_or_group_put_new_type_in_it() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 50})).unwrap(); + let before = undo_steps(&s); + // The rectangle is in the first layer, which becomes `base`; `other` is current while the + // collections of `base` and `g` add type. + let out = log( + &mut s, + &format!( + "var rect = app.activeDocument.pageItems[0]; {NESTED_TYPE}\ + var t = L0.textFrames.add(); t.name = 'added';\ + vc.log([t.layer.name, L0.pageItems[0].name, t.kind, d.activeLayer.name]);\ + var gt = g.textFrames.add(); gt.name = 'g-added'; vc.log([gt.parent.name, g.pageItems[0].name]);\ + var at = g.textFrames.areaText(rect); at.name = 'area'; vc.log([at.parent.name, g.pageItems[0].name, at.kind]);\ + g.textFrames.removeAll(); vc.log([names(g.pageItems), names(L0.textFrames)]);" + ), + ); + assert_eq!(out[0], json!(["base", "added", "TextType.POINTTEXT", "other"])); + assert_eq!(out[1], json!(["g", "g-added"])); + assert_eq!(out[2], json!(["g", "area", "TextType.AREATEXT"])); + // removeAll takes the group's own type and leaves the type inside its group. + assert_eq!(out[3], json!(["gg", "added,front,back"])); + assert_eq!(undo_steps(&s), before + 1); + // A locked layer and a hidden group take no new type, and the run changes nothing. + let before = undo_steps(&s); + let e = failure(&mut s, &format!("{NESTED_TYPE} L0.locked = true; L0.textFrames.add();")); + assert!(e.contains("hidden or locked"), "{e}"); + let e = failure(&mut s, &format!("{NESTED_TYPE} g.hidden = true; g.textFrames.pointText([5, 5]);")); + assert!(e.contains("hidden or locked"), "{e}"); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn text_create_puts_type_in_the_layer_or_group_it_names() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let group = s.execute("object.newGroup", &json!({})).unwrap()["id"].as_u64().unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + // A new layer is current, and a locked one takes no type. + let locked = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().map(NodeId).unwrap(); + s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap(); + let before = undo_steps(&s); + for bad in [json!("1"), json!(rect), json!(9999), json!(locked.0)] { + assert!(s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": bad})).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), before); + let id = s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": group})).unwrap()["id"].as_u64().unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(group))); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f08c8eb324..cc23a9d5c3 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -109,7 +109,7 @@ const INSIDE: &[(&str, &str)] = &[ dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ - textFrames= typename visible visible= zOrder zOrderPosition", + typename visible visible= zOrder zOrderPosition", ), ("Layers.", "prototype"), ("Layers.prototype.", "add constructor getByName index length parent removeAll typename"), @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "GroupItem.prototype.", "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ - rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", + rasterItems rasterItems= symbolItems symbolItems= textFrames", ), ("GroupItems.", "prototype"), ("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll typename"), diff --git a/docs/mcp.md b/docs/mcp.md index 2de50317ee..63f947b35b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -620,7 +620,7 @@ change nothing; an omitted or null `id` keeps the default. Commands that need an `path` keys of `appearance.transfer`, `appearance.copyFrom`, `layer.move`, the `livePaint.*` commands and `text.createInPath`) refuse a value that is not a non-negative integer with "`id` must be a whole number", naming the key, and report a key left out or null as missing. The optional `group` of `livePaint.fill` and `parent` of -`node.move` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when +`node.move` and `text.create` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when `group` is left out or null, and reports a missing group only when both are left out. A command that needs a number (`x` of `shape.rectangle`, `pos` of `guide.add`, `index`, `x` and `y` of the `object.mesh.*` and `object.envelope.setMeshPoint` point commands, and the others like them) refuses a value that is not a number with @@ -2772,7 +2772,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not - available yet. A `TextFrame` + available yet. A `Layer` and a `GroupItem` have `textFrames` with the same members. VectorCraft's own rules for + them: they list the type objects directly in the layer or group, topmost first, and their `add()`, `pointText`, + `areaText` and `pathText` put the new type on top of the layer's or group's contents, whatever the current layer. + Point type goes there with `text.create`'s `parent`, which takes a shown, unlocked layer or group and ignores the + drawing mode, and area type and type on a path go there with `node.move`, in the same undo step. A hidden or + locked layer or group throws an error and changes nothing. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 05bd1ba664..76797eea1f 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`). Paths and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `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.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. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames`, and the `textFrames` of a layer or group, which list the type directly in it and put new type on top of its contents (VectorCraft's own rule), make 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/, with https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ for the layer's and group's `textFrames`, describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.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 4ff24a0d6d4cec5cb8affec063b631e18b0a9d2d Mon Sep 17 00:00:00 2001 From: Taha-Mahmoodi <85902429+Taha-Mahmoodi@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:29:49 +0430 Subject: [PATCH 02/28] PDF: honor embedded-font preferences in synchronous opens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Compose the canonical font choice before Text As, retaining explicit overrides and avoiding an extra parameter clone. - Port the real eight-case synchronous/background font-binding regression to the current Craft runtime. - Build on the contributors’ PDF handling merged in #4569; preserve worker/profile/clipboard and glyph round-trip behavior. Fixes #9286 --- crates/ui-egui/src/dialogs/import_pdf.rs | 8 ++- .../ui-egui/src/dialogs/tests_import_pdf.rs | 2 +- crates/ui-egui/src/io/open.rs | 7 +- crates/ui-egui/src/opening/tests.rs | 69 +++++++++++++++++++ docs/development.md | 4 ++ 5 files changed, 83 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index e28bdbb021..17f1ea744f 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -618,14 +618,16 @@ pub(crate) fn preferred_text_as(app: &VectorcraftApp) -> TextAs { /// or `.ait` file opens as it says: Outlines would open it from its PDF content, without its /// editing data. So does an open with `linkPages`, which refuses Outlines: a linked page shows the /// file's own text. -pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], p: &Value) -> Value { +pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], mut p: Value) -> Value { let given = p.get("textAs").is_some_and(|v| !v.is_null()); let linked = p.get("linkPages").and_then(Value::as_bool) == Some(true); let options = p.is_object() || p.is_null(); if given || linked || !options || preferred_text_as(app) == TextAs::Text || fileio::detect(name, bytes).map(|f| f.id) != Some("pdf") { - return p.clone(); + return p; + } + if !p.is_object() { + p = json!({}); } - let mut p = if p.is_object() { p.clone() } else { json!({}) }; p["textAs"] = json!(TextAs::Outlines.id()); p } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 30a1aa9d65..49b5ec44b7 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -430,7 +430,7 @@ fn a_pdf_opened_without_the_dialog_takes_the_pdf_text_preference() { io::open_document(&mut app, "one.pdf", &one, None, &json!({"textAs": "text"})).unwrap(); opened(&mut app); assert_eq!(type_objects(&app), 1, "an open that gives textAs keeps it"); - let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, &serde_json::Value::Null); + let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, serde_json::Value::Null); assert!(p.is_null(), "a .ai file opens as it says: {p}"); // In the dialog too, a .ai file starts from Editable, and its choice is not kept for PDFs. assert!(import_pdf::offer(&mut app, "two.ai", &two_pages(false, None), None, None)); diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 639f33ac21..5ab17f9a69 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -143,9 +143,10 @@ pub fn opens_as(name: &str) -> Option { /// Open a document through the engine loader with the `document.open` options in `p` → /// `document.open`'s result, or `{dialog}` when Edit › Color Settings asks about its profile first /// ([`dialogs::profile_mismatch::open_or_ask`]): the document then opens, and goes on the recent -/// files, once the question is answered. A PDF opens with the `pdfTextAs` preference unless `p` -/// gives `textAs` ([`dialogs::import_pdf::with_preferred_text_as`]). +/// files, once the question is answered. PDF font and Text As preferences supply missing options; +/// explicit `embeddedFonts` and `textAs` choices keep their precedence. pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { + let p = app.session.prefs.with_pdf_font_choice(p); let p = &dialogs::import_pdf::with_preferred_text_as(app, name, bytes, p); let update_links = app.session.prefs.update_links == "automatically"; let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps; @@ -609,7 +610,7 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } - let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, &Value::Null); + let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, Value::Null); return Ok(crate::opening::start_with(app, path, bytes, params)); } let r = open_bytes_with(app, path, &bytes, Some(path.to_string()), p)?; diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index 2466381a3d..551cac14e8 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -4,6 +4,75 @@ use super::*; use crate::Services; use crate::tests::picks::{cancel_dialog, close_shown, draw_dialogs, open_dialogs, show_question}; +/// #9286: both real open consumers apply the same preference/explicit-option precedence and bind +/// the carried program to rendered text, rather than merely storing the requested option. +#[test] +fn synchronous_and_background_pdf_open_honor_embedded_font_preferences_and_overrides() { + use std::fmt::Write as _; + use vectorcraft_doc::{FILE_FONT_MIME, NodeKind}; + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; + use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font}; + + let mut glyph = FileGlyph { ch: 'x', outline: Default::default(), advance: 600.0 }; + glyph.outline.move_to((0.0, 0.0)); + glyph.outline.line_to((500.0, 0.0)); + glyph.outline.line_to((500.0, 700.0)); + glyph.outline.line_to((0.0, 700.0)); + glyph.outline.close_path(); + let info = FileFontInfo { family: "VectorCraftUIOpenPreference".into(), style: "Regular".into(), ..Default::default() }; + let font_bytes = build_file_font(&info, &[glyph]).unwrap(); + let mut hex = String::with_capacity(font_bytes.len() * 2); + for b in font_bytes { + write!(hex, "{b:02x}").unwrap(); + } + let n = first_extra(1); + let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(100.0, 100.0, "BT /F1 24 Tf 10 40 Td (x) Tj ET") }; + let font = format!( + "<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+VectorCraftUIOpenPreference /FirstChar 120 /LastChar 120 /Widths [600] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>", + n + 1 + ); + let descriptor = format!( + "<< /Type /FontDescriptor /FontName /ABCDEF+VectorCraftUIOpenPreference /Flags 34 /FontBBox [0 -200 500 900] /ItalicAngle 0 /Ascent 900 /Descent -200 /CapHeight 700 /StemV 80 /FontFile2 {} 0 R >>", + n + 2 + ); + let program = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1); + let bytes = pdf_with(&[page], &[&font, &descriptor, &program], None); + for background in [false, true] { + for (preference, explicit, expected) in [(false, None, false), (true, None, true), (false, Some(true), true), (true, Some(false), false)] { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default())); + app.session.prefs.pdf_import_embedded_fonts = preference; + let mut params = json!({"textAs": "text"}); + if let Some(value) = explicit { + params["embeddedFonts"] = json!(value); + } + if background { + start_with(&mut app, "embedded-preference.pdf", bytes.clone(), params); + open_ready(&mut app); + } else { + crate::io::open_document(&mut app, "embedded-preference.pdf", &bytes, None, ¶ms).unwrap(); + } + let doc = &app.session.doc().unwrap().doc; + let db = vectorcraft_text::FontDb::global(); + let mut text_count = 0; + let mut carries_font = false; + doc.walk(|node| { + if let NodeKind::Text(text) = &node.kind { + assert_eq!(text.plain_text(), "x", "imported text content"); + text_count += 1; + carries_font |= vectorcraft_text::layout(db, text).glyphs.iter().any(|glyph| db.is_file_font(glyph.font_id)); + } + }); + assert_eq!(text_count, 1, "text survives: background={background}, preference={preference}, explicit={explicit:?}"); + assert_eq!(carries_font, expected, "rendered font: background={background}, preference={preference}, explicit={explicit:?}"); + assert_eq!( + doc.images.values().any(|blob| blob.mime == FILE_FONT_MIME), + expected, + "owned font program: background={background}, preference={preference}, explicit={explicit:?}" + ); + } + } +} + #[test] fn long_operation_busy_while_a_file_opens_or_a_background_save_runs() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); diff --git a/docs/development.md b/docs/development.md index 404dc10f33..8ec8db5fab 100644 --- a/docs/development.md +++ b/docs/development.md @@ -352,6 +352,10 @@ The app decides which cursors exist; whoever draws them works from the list. For doesn't run. `cargo xtask ci` runs the same two as its `test` and `doctests` steps. - The test build leaves out the examples (`--lib --bins --tests`); clippy (`--all-targets`) still checks them. +- PDF open consumers compose the embedded-font preference before Text As without cloning the + composed options again; explicit options win in both synchronous and background opens. + `opening::tests::synchronous_and_background_pdf_open_honor_embedded_font_preferences_and_overrides` + exercises both paths with a generated embedded font and checks rendered font ownership (#9286). - Each crate has one integration-test binary: its test files are modules of `tests/it/main.rs`. Run one file's tests with `cargo nextest run -p vectorcraft-svg --test it roundtrip::` (or `cargo test` with the same arguments). A new test file gets a `mod` line in `main.rs`. From c70eb7fc986a581b49d34ccf046f3434115eb9af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:53:40 -0800 Subject: [PATCH 03/28] Scripts: character attributes set the fill and stroke of text A text range and its characterAttributes now have fillColor, strokeColor and strokeWeight. The colors take and give the same color objects as a path's fill and stroke; a NoColor takes the paint away, and a color out of range or of a kind that cannot be assigned yet throws with nothing changed. strokeWeight is 0 to 1000 points and reads in document points on scaled type. Setting the value a range already has records no undo step. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/text.rs | 43 +++++++++-- crates/engine/src/tests/script_text.rs | 72 +++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 12 ++-- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 5 files changed, 122 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 233ba56621..6595cfb926 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -3,7 +3,8 @@ //! `paragraphAttributes`, and `app.textFonts`, as the help pages //! , //! , -//! and +//! , +//! and //! describe them. //! //! VectorCraft's own rules, which the help pages do not state: @@ -33,6 +34,8 @@ //! value; set on an empty range it changes nothing. A paragraph attribute reads the first //! paragraph the range touches and sets every one of them. A text range has the members of //! both its `characterAttributes` and its `paragraphAttributes`. +//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes +//! the paint away. `strokeWeight` is 0 to 1000 points. use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; @@ -40,13 +43,14 @@ use std::rc::Rc; use std::sync::{Arc, Weak}; use serde_json::{Value, json}; +use vectorcraft_color::Paint; use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; use super::{ - Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, editable, float, - frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, typename_of, - whole, with_doc, + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, edit_item, editable, + float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, + typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -789,9 +793,12 @@ enum Attr { Underline, StrikeThrough, TextFont, + FillColor, + StrokeColor, + StrokeWeight, } -const ATTRS: [(&str, Attr); 11] = [ +const ATTRS: [(&str, Attr); 14] = [ ("size", Attr::Size), ("leading", Attr::Leading), ("autoLeading", Attr::AutoLeading), @@ -803,6 +810,9 @@ const ATTRS: [(&str, Attr); 11] = [ ("underline", Attr::Underline), ("strikeThrough", Attr::StrikeThrough), ("textFont", Attr::TextFont), + ("fillColor", Attr::FillColor), + ("strokeColor", Attr::StrokeColor), + ("strokeWeight", Attr::StrokeWeight), ]; /// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with @@ -905,9 +915,18 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) Attr::Underline => Data::Bool(s.underline), Attr::StrikeThrough => Data::Bool(s.strikethrough), Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + Attr::FillColor => colors::of_paint(&s.fill), + Attr::StrokeColor => colors::of_paint(&s.stroke), + Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)), } } +/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a +/// `strokeWidth` it is given. +fn stroke_scale(t: &TextObject) -> f64 { + vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0) +} + /// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { let finite = || number(v, name); @@ -976,6 +995,20 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, & let (family, style) = font_of(h, v)?; (json!({"font": family, "style": style}), font_ref(h, &family, &style)) } + Attr::FillColor | Attr::StrokeColor => { + let color = colors::assigned(v, name)?; + let paint = color.map_or(Paint::None, Paint::solid); + let given = color.map_or_else(|| json!("none"), |c| colors::param(&c)); + let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" }; + (json!({ key: given }), colors::of_paint(&paint)) + } + Attr::StrokeWeight => { + let n = finite()?; + if !(0.0..=1000.0).contains(&n) { + return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into())); + } + (json!({"strokeWidth": n}), num(n)) + } }) } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..7d70741e69 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -225,6 +225,78 @@ fn setting_the_value_a_range_has_records_no_undo_step() { assert_eq!(undo_steps(&s), before); } +fn paints(s: &Session, id: NodeId) -> Vec<(String, Paint, Paint, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn character_attributes_paint_only_their_own_characters() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, b = r.characters[1].characterAttributes;\ + var red = new RGBColor(); red.red = 255; b.fillColor = red;\ + var k = new CMYKColor(); k.black = 100; b.strokeColor = k; b.strokeWeight = 2;\ + vc.log([b.fillColor.typename, b.fillColor.red, b.strokeColor.typename, b.strokeColor.black, b.strokeWeight]);\ + vc.log([r.characters[0].fillColor.red, r.characters[0].strokeColor.typename]);", + ); + let n = |v: &Value| v.as_f64().unwrap_or(f64::NAN); + assert_eq!((out[0][0].as_str(), out[0][2].as_str()), (Some("RGBColor"), Some("CMYKColor")), "{out:?}"); + assert_eq!((n(&out[0][1]), n(&out[0][3]), n(&out[0][4])), (255.0, 100.0, 2.0), "the paint reads back as given"); + assert_ne!(n(&out[1][0]), 255.0, "the first character keeps its fill"); + assert_eq!(out[1][1], json!("NoColor"), "the first character keeps no stroke"); + let runs = paints(&s, id); + let b = runs.iter().find(|r| r.0 == "b").expect("b is a run of its own"); + assert_eq!(b.1, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(b.2, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!(b.3 > 1.0); + assert!(runs.iter().filter(|r| r.0 != "b").all(|r| r.1 != b.1 && r.2 == Paint::None), "{runs:?}"); + assert!(undo_steps(&s) > before); + + let steps = undo_steps(&s); + log(&mut s, "var b = app.activeDocument.textFrames[0].textRange.characters[1]; b.fillColor = b.fillColor; b.strokeWeight = b.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "setting the paint a range has records no undo step"); + log(&mut s, "app.activeDocument.textFrames[0].textRange.characters[1].strokeColor = new NoColor();"); + assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away"); +} + +#[test] +fn stroke_weight_reads_back_in_document_points_on_scaled_type() { + let (mut s, id) = doc_with("abc"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap(); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = 2; vc.log(r.strokeWeight);"); + assert!((out[0].as_f64().unwrap_or(f64::NAN) - 2.0).abs() < 1e-9, "{out:?}"); + let stored = paints(&s, id)[0].3; + assert!(stored < 2.0, "the type's own scale draws the stored width wider: {stored}"); + let steps = undo_steps(&s); + log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = r.strokeWeight;"); + assert_eq!(undo_steps(&s), steps, "the weight read back is the weight it has"); +} + +#[test] +fn bad_text_paint_is_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let runs = paints(&s, id); + for (src, want) in [ + ("r.fillColor = 'red';", "fillColor must be a color object"), + ("var c = new RGBColor(); c.red = 300; r.strokeColor = c;", "RGBColor.red"), + ("r.fillColor = new GradientColor();", "not available yet"), + ("r.strokeWeight = -1;", "strokeWeight must be from 0 to 1000"), + ("r.characterAttributes.strokeWeight = 'thick';", "strokeWeight must be a finite number"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(paints(&s, id), runs); +} + #[test] fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a1893c17cf..016b0acd37 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -177,12 +177,14 @@ const INSIDE: &[(&str, &str)] = &[ "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ - duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + duplicate duplicate= end end= fillColor fillColor= firstLineIndent firstLineIndent= getLocalCharOverridesJSON \ + getLocalCharOverridesJSON= \ getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ - spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \ + spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= strokeColor strokeColor= \ + strokeWeight strokeWeight= textFont textFont= textRanges \ textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ verticalScale= words", ), @@ -195,9 +197,9 @@ const INSIDE: &[(&str, &str)] = &[ ("CharacterAttributes.", "prototype"), ( "CharacterAttributes.prototype.", - "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ - rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ - underline= verticalScale verticalScale=", + "autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \ + leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \ + strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=", ), ("ParagraphAttributes.", "prototype"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 08f1c2fc98..afa5506833 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2719,8 +2719,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to 5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and - `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`, - set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`, + `fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and + `strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with + `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 50d76e869f..57c3304e95 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,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: 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 and the other classes are not there yet. `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. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.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, fill and stroke colors, stroke weight) 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/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles and tab stops are not there yet. `crates/engine/src/tests/script_text.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: 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 f0c2c946b9277dbf95d1e2c495236d9534f11be4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:58:43 -0800 Subject: [PATCH 04/28] Scripts: keep clipping paths at the bottom and take handles into controlBounds - node.move refuses to move the clipping path of a clip group or clipping layer until the mask is released, and a row moved to index 0 of a clip group goes directly above the clipping path. PageItem.move refuses a place behind a clipping path. - controlBounds takes in the anchors and direction handles of the shown paths in the item; hidden paths, guides and clipped art are left out. - Setting opacity to a value that differs from the current one only past the reported precision now sets it. - Text added after a range that ends inside a character goes after the whole character. - textFrames.removeAll() throws and deletes nothing when a type object is on a locked artboard. - Layer lists are kept while the document is unchanged and are charged by the rows they look at; getByName is charged by the items it scans. - The offset tables of text frame indexes are kept within 64 MiB per run; tables past it are made again when the frame is next read. - The handles of host class objects count toward the script heap limit. - Tests: the file-open test quotes the path as a JS string, the font lookup test clears the message between its two checks, and the collection test pins its host-call count. A new test covers a path node.move puts into a pixel-aligned compound path. - Docs: docs/mcp.md, the M13 roadmap row and the scripts entries in docs/target-app-parity.md describe what scripts have now. --- crates/engine/src/cmd/layer.rs | 11 ++- crates/engine/src/script/dom.rs | 39 ++++++++++- crates/engine/src/script/dom/layers.rs | 65 ++++++++++++------ crates/engine/src/script/dom/text.rs | 93 ++++++++++++++++++++++---- crates/engine/src/tests/layers.rs | 25 +++++++ crates/engine/src/tests/pixelalign.rs | 19 ++++++ crates/engine/src/tests/script_dom.rs | 77 ++++++++++++++++++++- crates/engine/src/tests/script_text.rs | 32 ++++++++- crates/js/src/heap.rs | 4 ++ crates/js/src/host_classes.rs | 4 +- crates/js/src/host_tests.rs | 19 ++++++ docs/mcp.md | 10 ++- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 14 files changed, 354 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 9fe8d9e678..a7b4073827 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; 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 also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -930,6 +930,14 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } else if !accepts(d, parent, n) { return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups")); } + // The clipping path stays at the bottom of its clip group or clipping layer. + let from = d.parent_of(id); + let clips = |p: Option| p.and_then(|p| d.node(p)).filter(|p| p.clips()); + let is_mask = clips(from).and_then(Node::children).and_then(|c| c.first()).is_some_and(|c| c.id == id); + if is_mask && (parent != from || index != 0) { + return Err(bad(C, "the clipping path stays at the bottom of its clip group; release the clipping mask first")); + } + let index = if !is_mask && clips(parent).and_then(Node::children).is_some_and(|c| c.iter().any(|c| c.id != id)) { index.max(1) } else { index }; // An empty compound path takes the paint of the first path that goes into it: the path's own, // or the paint of the compound path it leaves, which is what painted it. let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })); @@ -945,7 +953,6 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } let live_paint = LivePaintMove::plan(d, &[id], parent, false)?; let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" }; - let from = d.parent_of(id); let left = super::intertwine::groups_of(d, &[id]); s.edit(label, |d, sel| { d.move_node(id, parent, index)?; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7bafaafca1..bde785060d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1540,7 +1540,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { // replaces the one the graph keeps for its series or kind. let item = this_item(h, a)?; let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); - let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); + let v = now.filter(|now| (now * 1e4).round() / 1e4 == v).unwrap_or(v); set_props(h, a, |_| false, json!({"opacity": v})) } @@ -1586,6 +1586,33 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds, taking in the anchors and direction handles of the paths +/// in the item. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, true)?; + let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r))); + Ok(f.bounds(h.dom.coords.get(), r)) +} + +/// `r` with the anchors and direction handles of the shown paths in `n`. Hidden objects, the +/// objects in them and guides are left out, as the visible bounds leave them out, and a clip group +/// or clipping layer gives only its clipping path's. +fn take_in_handles(n: &crate::doc::Node, mut r: Rect) -> Rect { + if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { + return r; + } + for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) { + r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out); + } + let children = n.children().map_or(&[][..], Vec::as_slice); + let children = if n.clips() { &children[..children.len().min(1)] } else { children }; + for c in children { + r = take_in_handles(c, r); + } + r +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1823,7 +1850,13 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul { i -= 1; } - if how == Placement::Above { i + 1 } else { i } + let at = if how == Placement::Above { i + 1 } else { i }; + // A place behind a clipping path is refused; an object put into the clip group + // itself goes directly above the clipping path. + if clips && at == 0 { + return Err(HostError::Error("an object cannot go behind a clipping path".into())); + } + at } (_, None) => count, }; @@ -2078,7 +2111,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 b315aab2e0..684a6c84fb 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -486,7 +486,8 @@ 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))) + let n = with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))?; + Ok(num(float(n as u64))) } fn layers_parent(h: &Host, a: &[Data]) -> Answer { @@ -503,14 +504,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())) @@ -583,8 +584,8 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option)> { } } -/// A document's uid, the document as it was, the [`Kind`] and the container of an art collection, -/// and the ids it listed then. +/// A document's uid, the document as it was, the [`Kind`] (or [`LAYER_LIST`]) and the container of +/// an art or layer collection, and the ids it listed then. pub(super) type ArtList = (u64, Arc, u8, Option, Rc>); /// How many lists of art [`super::State`] keeps at once. @@ -595,9 +596,44 @@ pub(super) const ART_LISTS: usize = 4; /// their documents are unchanged, so a loop over groups that reads each group's `pageItems` builds /// each list once. Each new list is charged by the objects it looks at. fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> Result>> { + kept_list(h, st, kind as u8, container, || { + Ok(match container { + None => { + let all = page_items(h, st); + h.charge_call(all.len() as u64)?; + all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() + } + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect() + } + }) + }) +} + +/// The tag of a list of layers among the kept lists of art. +const LAYER_LIST: u8 = u8::MAX; + +/// The layers of `parent` (`None`: the top level), top first, kept as [`art_list`] keeps its +/// lists. Each new list is charged by the rows it looks at. +fn layer_ids(h: &Host, st: &DocState, parent: Option) -> Result>> { + kept_list(h, st, LAYER_LIST, parent, || { + let rows = match parent { + None => Some(&st.doc.layers), + Some(p) => st.doc.children(Some(p)), + }; + h.charge_call(rows.map_or(0, Vec::len) as u64)?; + Ok(layer_list(&st.doc, parent)) + }) +} + +/// The list kept for `tag` and `container` while the document is unchanged, else the one `build` +/// makes, which is kept in place of the least recently used one. +fn kept_list(h: &Host, st: &DocState, tag: u8, container: Option, build: impl FnOnce() -> Result>) -> Result>> { { let mut lists = h.dom.art.borrow_mut(); - let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container); + let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == tag && *c == container); if let Some(at) = at { let list = lists.remove(at); let ids = list.4.clone(); @@ -605,25 +641,13 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option) -> R return Ok(ids); } } - let ids: Vec = match container { - None => { - let all = page_items(h, st); - h.charge_call(all.len() as u64)?; - all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect() - } - Some(c) => { - let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); - h.charge_call(children.len() as u64)?; - children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect() - } - }; - let ids = Rc::new(ids); + let ids = Rc::new(build()?); let mut lists = h.dom.art.borrow_mut(); lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); if lists.len() >= ART_LISTS { lists.remove(0); } - lists.push((st.uid, st.doc.clone(), kind as u8, container, ids.clone())); + lists.push((st.uid, st.doc.clone(), tag, container, ids.clone())); Ok(ids) } @@ -663,6 +687,7 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { let ids = art_list(h, st, kind, c)?; + 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())) }) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 556b0a113c..df600f6c6b 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -59,6 +59,10 @@ pub const STALE_RANGE: &str = "Stale text range"; /// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit /// is stale. const MAX_EDITS: usize = 100_000; +/// The most bytes the offset tables of the frames' indexes hold in a run. Past it the tables of +/// the other frames are given up; their text, generations and edits stay, and each frame's tables +/// are made again when it is next read. +const INDEX_BUDGET: usize = 64 << 20; /// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. pub(super) struct Index { @@ -102,6 +106,22 @@ impl Index { Self { text, chars, bytes, words, paras } } + /// The text alone, without its offset tables, for a frame whose tables were given up under + /// [`INDEX_BUDGET`]; [`observe`] makes them again before the index is read. + fn bare(text: String) -> Self { + Self { text, chars: Vec::new(), bytes: Vec::new(), words: Vec::new(), paras: Vec::new() } + } + + fn is_bare(&self) -> bool { + self.chars.is_empty() + } + + /// The bytes the offset tables hold. + fn table_bytes(&self) -> usize { + let pairs = self.words.capacity() + self.paras.capacity(); + (self.chars.capacity() + self.bytes.capacity()) * size_of::() + pairs * size_of::<(usize, usize)>() + } + fn len(&self) -> usize { self.chars.last().copied().unwrap_or(0) } @@ -127,6 +147,13 @@ impl Index { fn char_span(&self, i: usize) -> Option<(usize, usize)> { Some((*self.chars.get(i)?, *self.chars.get(i + 1)?)) } + + /// UTF-16 offset `u` on a character boundary: inside a surrogate pair, the start of its + /// character, or with `up` the end of it. + fn boundary(&self, u: usize, up: bool) -> usize { + let b = self.byte(u, up); + self.chars.get(self.bytes.partition_point(|&x| x < b)).copied().unwrap_or_else(|| self.len()) + } } /// The words or paragraphs of `spans` that `s..e` touches: those it overlaps, or, for an empty @@ -201,6 +228,28 @@ pub(in crate::script) struct TextState { made: Cell, /// The span of each range object, by its number, whose `length` the script set. resized: RefCell>, + /// The bytes the offset tables of the frames' indexes hold ([`INDEX_BUDGET`]). + table_bytes: Cell, +} + +/// Puts `index` in the log of frame `key` and keeps the offset tables of all the frames within +/// [`INDEX_BUDGET`], giving up the tables of other frames first. +fn set_index(state: &TextState, frames: &mut HashMap<(u64, u64), Log>, key: (u64, u64), index: Index) { + let mut total = state.table_bytes.get() + index.table_bytes(); + if let Some(l) = frames.get_mut(&key) { + total -= l.index.table_bytes(); + l.index = Rc::new(index); + } + for (k, l) in frames.iter_mut() { + if total <= INDEX_BUDGET { + break; + } + if *k != key && !l.index.is_bare() { + total -= l.index.table_bytes(); + l.index = Rc::new(Index::bare(l.index.text.clone())); + } + } + state.table_bytes.set(total); } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -228,29 +277,36 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc {} + let fresh = match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => None, Some(l) => { - if l.reverts != st.reverts || !same_text(t, &l.index.text) { + let changed = l.reverts != st.reverts || !same_text(t, &l.index.text); + if changed { l.stamp += 1; l.floor = l.stamp; l.edits.clear(); - l.index = Rc::new(Index::new(t.plain_text())); } l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + changed.then(|| t.plain_text()) } None => { let l = Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, - index: Rc::new(Index::new(t.plain_text())), + index: Rc::new(Index::bare(String::new())), stamp: 0, floor: 0, edits: VecDeque::new(), }; frames.insert(key, l); + Some(t.plain_text()) } + }; + // Tables given up under the budget are made again from the text the log keeps. + let fresh = fresh.or_else(|| frames.get(&key).filter(|l| l.index.is_bare()).map(|l| l.index.text.clone())); + if let Some(text) = fresh { + set_index(&h.dom.text, &mut frames, key, Index::new(text)); } let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; Ok((l.index.clone(), l.stamp)) @@ -320,9 +376,9 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser l.floor = l.stamp; l.edits.clear(); } - l.index = Rc::new(Index::new(now)); l.doc = Arc::downgrade(&st.doc); l.reverts = st.reverts; + set_index(&h.dom.text, &mut frames, (st.uid, item.id.0), Index::new(now)); Ok(()) }) } @@ -718,16 +774,16 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let (r, part) = this_part(h, a)?; let contents = contents_of(arg(a, 1))?; let (index, s, e, _) = resolve(h, r)?; - let at = if before || matches!(arg(a, 2), Data::Undefined) { + let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) { let (items, spans) = part_spans(&index, part, s, e); let span = |k: usize| match spans { None => index.char_span(k), Some(list) => list.get(k).copied(), }; if before { - items.clone().next().and_then(span).map_or(s, |(x, _)| x) + (items.clone().next().and_then(span).map_or(s, |(x, _)| x), false) } else { - items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + (items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true) } } else { let rel = arg(a, 2); @@ -740,13 +796,16 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); } let (_, ts, te, _) = resolve(h, target)?; - if text_placement(arg(a, 3))? { te } else { ts } + if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) } }; + // An offset inside a character goes to its end for an insertion after, else to its start, for + // the edit, the edit log and the range returned alike. + let at = index.boundary(at, after); if contents.is_empty() { let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); } - let b = index.byte(at, false); + let b = index.byte(at, after); let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); let (lead, trail) = match part { Part::Characters => ("", ""), @@ -1379,19 +1438,25 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { } /// `removeAll()`: deletes every type object the collection lists in one command; a hidden or -/// locked one stops it first. +/// locked one, or one on a locked artboard, stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let (doc, c) = frames_scope(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); - Ok::<_, HostError>((ids, refused)) + 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)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index f49637c768..858d14396d 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -893,6 +893,31 @@ fn moves_are_validated() { assert_eq!(parent(&s, sub), None); } +/// `node.move` keeps a clip group's clipping path at its bottom: the path does not leave the group +/// or move up in it, and a row moved to index 0 goes directly above it. +#[test] +fn node_move_keeps_a_clip_groups_clipping_path_at_the_bottom() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 30.0), rect(&mut s, 60.0)); + let layer = parent(&s, a).unwrap(); + run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]})); + let g = id(&run(&mut s, "object.clippingMask.make", json!({}))); + let before = children(&s, g); + let mask = before[0]; + for p in [json!({"id": mask.0, "parent": layer.0, "index": 0}), json!({"id": mask.0, "parent": g.0, "index": 2})] { + let err = s.execute("node.move", &p).unwrap_err().to_string(); + assert!(err.contains("clipping path stays at the bottom"), "{p}: {err}"); + assert_eq!(children(&s, g), before, "{p}"); + } + let _ = s.execute("node.move", &json!({"id": mask.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g), before, "the clipping path stays where it is"); + let d = rect(&mut s, 90.0); + run(&mut s, "node.move", json!({"id": d.0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, d], "the row goes directly above the clipping path"); + run(&mut s, "node.move", json!({"id": before[2].0, "parent": g.0, "index": 0})); + assert_eq!(children(&s, g)[..2], [mask, before[2]]); +} + /// The Layers panel's commands refuse a switch given as text or as another value that is not true /// or false, and leave the document, the selection, the highlighted rows and the undo history as /// they were; true, false and null still work. diff --git a/crates/engine/src/tests/pixelalign.rs b/crates/engine/src/tests/pixelalign.rs index 00b4cce694..d4b3916f4a 100644 --- a/crates/engine/src/tests/pixelalign.rs +++ b/crates/engine/src/tests/pixelalign.rs @@ -478,6 +478,25 @@ fn paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned() { assert!(halves(&pts), "slice: {pts:?}"); } +/// A path that `node.move` puts into a pixel-aligned compound path snaps with it, though neither +/// the path nor where it came from was pixel-aligned. +#[test] +fn a_path_node_move_puts_into_an_aligned_compound_path_snaps() { + let mut s = new_doc(); + let a = path(&mut s, "M100 100 L110 100 L110 110 L100 110 Z", 1.0); + let b = path(&mut s, "M200 100 L210 100 L210 110 L200 110 Z", 1.0); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setPixelAligned", &json!({"ids": [c]})).unwrap(); + let loose = path(&mut s, "M300.25 100 L310 100 L310 110 L300.25 110 Z", 1.0); + assert!(!aligned(&s, loose)); + s.execute("node.move", &json!({"id": loose, "parent": c, "index": 99})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(loose)), Some(NodeId(c))); + let pts = compound_points(&s, c); + assert_eq!(pts.len(), 12); + assert!(halves(&pts), "{pts:?}"); +} + /// Art moved by Artboard Options with Move Artwork with Artboard, and the art copies of an /// artboard copied with its art, stay on the pixel grid. #[test] diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e8522ed334..94c92e591f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -133,6 +133,46 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +/// `controlBounds` takes in the direction handles of a curve, which reach past its visible bounds. +#[test] +fn control_bounds_take_in_the_direction_handles() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.selection[0]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let top = |v: &Value| v[1].as_f64().unwrap(); + assert!(top(&out[0]) < 180.0, "{out:?}"); + assert_eq!(top(&out[1]), 200.0, "{out:?}"); + assert_eq!(out[1][2].as_f64().unwrap(), out[0][2].as_f64().unwrap(), "{out:?}"); +} + +/// The `controlBounds` of a group leave out the handles of a hidden curve in it. +#[test] +fn control_bounds_leave_out_hidden_paths() { + let (mut s, a, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a.0, id]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("object.setProps", &json!({"id": id, "visible": false})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.selection[0].parent; vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[1], out[0], "{out:?}"); +} + +/// The `controlBounds` of a clip group leave out the handles of the clipped art past the clipping +/// path. +#[test] +fn control_bounds_of_a_clip_group_come_from_its_clipping_path() { + let (mut s, _, _) = doc(); + let id = s.execute("path.create", &json!({"d": "M100 200 C100 -400 200 -400 200 200"})).unwrap()["id"].as_u64().unwrap(); + let mask = rect(&mut s, 100.0, 150.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.visibleBounds); vc.log(g.controlBounds);"); + assert_eq!(out[0], json!(true), "{out:?}"); + assert_eq!(out[2], out[1], "{out:?}"); +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -257,6 +297,15 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps); } +/// An opacity near the one an item has, but not the one it reports, is set. +#[test] +fn an_opacity_close_to_the_current_one_is_set() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.opacity = 50.00009; vc.log(i.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -391,6 +440,27 @@ fn move_and_duplicate_place_by_element_placement() { assert!(e.contains("hidden or locked"), "{e}"); } +/// An object cannot go behind a clip group's clipping path; one put at the end of the group goes +/// directly above the clipping path. +#[test] +fn an_object_cannot_go_behind_a_clipping_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let before = kids(&s); + s.execute("object.setProps", &json!({"id": before[0].0, "name": "mask"})).unwrap(); + s.execute("object.setProps", &json!({"id": before[1].0, "name": "art"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('art').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);"); + assert!(e.contains("behind a clipping path"), "{e}"); + assert_eq!(kids(&s), before); + let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("object.setProps", &json!({"id": c.0, "name": "c"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('c').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), [before[0], c, before[1]]); +} + #[test] fn a_copy_goes_beside_its_source() { let (mut s, a, b) = doc(); @@ -1300,8 +1370,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 (same, other) = (serde_json::to_string(&p).unwrap(), serde_json::to_string(&format!("{p}.other")).unwrap()); + let query = format!("vc.log(app.getIsFileOpen({same})); 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. @@ -1830,6 +1901,8 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { let (a, b) = (run(&mut s, nested).unwrap(), run(&mut s, in_order).unwrap()); assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10]))); assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); + // A list built again for each lookup would add a host call to both. + assert_eq!(a["hostCalls"], json!(50), "{a}"); } #[test] diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a164ca396b..6101835982 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -432,7 +432,7 @@ fn text_fonts_list_and_assign_fonts_by_name() { &format!( "var f = app.textFonts, m = '';\ try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ - try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + m = ''; try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" @@ -508,6 +508,20 @@ fn collections_of_text_add_words_characters_and_paragraphs() { assert_eq!(plain(&s, id), "ab"); } +/// Text added after a range that ends inside a character goes after the whole character, and the +/// range returned holds the added text. +#[test] +fn text_added_after_half_a_character_goes_after_it() { + let (mut s, id) = doc_with("a\u{1F600}b"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.characters[0]; r.length = 2;\ + var x = t.characters.add('X', r, ElementPlacement.PLACEAFTER); vc.log([x.start, x.contents]);", + ); + assert_eq!(out, vec![json!([3, "X"])]); + assert_eq!(plain(&s, id), "a\u{1F600}Xb"); +} + #[test] fn text_fonts_find_a_bundled_face_by_its_postscript_name() { let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else { @@ -649,6 +663,22 @@ fn text_frames_of_a_layer_or_group_put_new_type_in_it() { assert_eq!(undo_steps(&s), before); } +/// `textFrames.removeAll()` deletes nothing when a type object it lists is on a locked artboard. +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let (mut s, id) = doc_with("abc"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", id.0)), "{e}"); + assert!(s.active().unwrap().doc.node(id).is_some()); + assert_eq!(undo_steps(&s), before); +} + #[test] fn text_create_puts_type_in_the_layer_or_group_it_names() { let mut s = Session::new(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 9c094a91cc..fd8f201d63 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -422,6 +422,9 @@ pub(crate) const XML_REF_BYTES: usize = 8; pub(crate) const XML_NS_BYTES: usize = 48; /// The estimated bytes of the measurement a `UnitValue` object holds. pub(crate) const UNIT_VALUE_BYTES: usize = 32; +/// The bytes of each part of the handle of an object of a host class: the part itself and its +/// copy in the key that finds the object again ([`crate::host_classes`]). +pub(crate) const HOST_PART_BYTES: usize = 16; /// The estimated bytes of a piece of code without its instructions, tables and strings. const CODE_BYTES: usize = 384; @@ -716,6 +719,7 @@ 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_PART_BYTES * h.handle.len(), _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..4c5cda0a70 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -155,10 +155,12 @@ impl Interp { } return Ok(Value::Object(id)); } - self.reserve_heap(crate::heap::OBJECT_BYTES)?; + let parts = crate::heap::HOST_PART_BYTES.saturating_mul(handle.len()); + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(parts))?; let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); + self.heap.bytes = self.heap.bytes.saturating_add(parts); 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 1da0d53002..eeac99a3ca 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -661,6 +661,25 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); } +/// The handles of the objects of a host class count toward the heap limit. +#[test] +fn host_class_handles_count_toward_the_heap_limit() { + let mut r = Realm::new(); + r.set_limits(Limits { heap_bytes: 64 << 20, ..Limits::default() }); + let n = Rc::new(Cell::new(0.0)); + let big: HostFunction = Rc::new(move |_| { + n.set(n.get() + 1.0); + Ok(host_ref("Thing", &vec![n.get(); 100_000])) + }); + let class = + HostClass { name: "Thing".into(), parent: None, members: vec![("big".to_string(), HostMember::Method(big))], index: None, construct: None }; + r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[0.0]))]).unwrap(); + match r.run("var a = []; for (var i = 0; i < 100; i++) a.push(thing.big()); a.length") { + Err(RunError { kind: RunErrorKind::Limit(k), .. }) => assert_eq!(k, LimitKind::Heap), + other => panic!("{other:?}"), + } +} + #[test] fn a_host_class_constructor_called_with_new_cannot_wait() { let mut r = realm(1_000_000); diff --git a/docs/mcp.md b/docs/mcp.md index b465eb83a9..e54bc89746 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 with the anchors and direction handles of the shown paths in the item), `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 @@ -2795,7 +2795,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path gives up its own paint, 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. + alignment, and a pixel-aligned compound path snaps a path it takes to the pixel grid. `node.move` leaves the + clipping path of a clip group or clipping layer at its bottom: it refuses to move the clipping path until the mask + is released, and puts a row given index 0 there directly above the clipping path. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type objects in paint order, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both @@ -2807,7 +2809,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `areaText` and `pathText` put the new type on top of the layer's or group's contents, whatever the current layer. Point type goes there with `text.create`'s `parent`, which takes a shown, unlocked layer or group and ignores the drawing mode, and area type and type on a path go there with `node.move`, in the same undo step. A hidden or - locked layer or group throws an error and changes nothing. A `TextFrame` + locked layer or group throws an error and changes nothing. `removeAll()` deletes every type object the collection + lists with `edit.clear` in one step; when one is hidden or locked, in a hidden or locked layer or group, or on a + locked artboard, it throws an error and deletes nothing. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to diff --git a/docs/roadmap.md b/docs/roadmap.md index 26f6a12e3f..a2a446a76a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -198,7 +198,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) | 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; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, and its text frames with their text ranges and the fonts; path properties, views, stories, text styles, the other classes of the script document model and batch work remain | 18–27 | | M14 | 1.0 polish (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) | 🟡 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), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f15c8d15ba..562885ca02 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1033,7 +1033,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - 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: 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`). Paths and the other classes are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `crates/engine/src/tests/script_dom.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`). Path properties and the classes that this bullet and the next two do not name are not there yet, except that `CompoundPathItem.pathItems` reads the paths of a compound path. `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.textFrames`, and the `textFrames` of a layer or group, which list the type directly in it and put new type on top of its contents (VectorCraft's own rule), make 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/, with https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ for the layer's and group's `textFrames`, describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.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`. From a22c730c03e89ec97c037043dec337924ef188f2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 21:21:28 -0800 Subject: [PATCH 05/28] Scripts: text edits refuse hidden or locked type, and lists start with the topmost frame - Text edits (contents, added text, character and paragraph attributes) throw Cannot edit with nothing changed when the frame, or a layer or group it is in, is hidden or locked. - Text added after a range that ends inside a character goes after that character, and styling an empty range changes nothing. - Point changes that wait are written before a call that is put back on failure, and before the points of another path are read, so a failed call does not drop them. - A new path's id is read exactly from the command's result. - A saved or Recent preset's rows above 1,000 read as 1,000, so file.new takes the preset as file.newPresets lists it. - textFrames lists type topmost first, as pageItems does on main; the tests and docs/mcp.md follow. --- crates/engine/src/cmd/newdoc.rs | 11 +++- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/paths.rs | 19 ++++--- crates/engine/src/script/dom/text.rs | 39 +++++++++----- crates/engine/src/tests/newdoc.rs | 19 +++++++ crates/engine/src/tests/script_dom_paths.rs | 22 ++++++++ crates/engine/src/tests/script_text.rs | 59 ++++++++++++++++++--- docs/mcp.md | 2 +- 8 files changed, 140 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 4aad006ff1..6aabd654c3 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 (a saved or Recent preset's + /// value above `MAX_ARTBOARDS` 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,12 @@ 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/script/dom.rs b/crates/engine/src/script/dom.rs index 1823b25a34..5537ab5d61 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -158,11 +158,13 @@ impl State { /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every /// document, the selection and the undo histories are as they were before it, with no undo step -/// and no change to the document's saved state. +/// and no change to the document's saved state. Point changes that wait in [`State`] are written +/// first, so a failure in `f` does not put them back. fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { if h.dom.saving.get() { return f(h); } + flush(h)?; let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate"); h.dom.saving.set(true); let r = f(h); diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 823ed46d41..ea57a3f49b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -164,13 +164,15 @@ fn same_path(a: Item, b: Item) -> bool { a.doc.uid == b.doc.uid && a.id == b.id } -/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. +/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. The +/// waiting point changes of another path are written first. fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result { if let Some((waiting, subs)) = &*h.dom.pending.borrow() && same_path(*waiting, item) { return Ok(f(subs)); } + flush(h)?; read_path(h, item, |_, _, pd| f(&pd.subpaths)) } @@ -372,20 +374,17 @@ 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 JSON result of a command that made an object, read exactly, as the text creators +/// read it. +fn made_id(r: &(Data, Value)) -> std::result::Result { + r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } /// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, /// and reverses the new path's direction when `reversed`. → the new path. 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 = made_id(&drawing_normally(h, || super::command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -544,7 +543,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, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 6595cfb926..4a25a8300f 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -193,7 +193,7 @@ type Spans = [(usize, usize)]; #[derive(Default)] pub(in crate::script) struct TextState { frames: RefCell>, - /// A document's uid, the document, and the ids of its type objects in paint order. + /// A document's uid, the document, and the ids of its type objects, topmost first. list: RefCell>, /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. @@ -301,6 +301,15 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u }) } +/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing +/// changed, when the frame or a layer or group it is in is hidden or locked. +fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { + return Err(HostError::Error(format!("Cannot edit TextFrame {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); + } + edit_item(h, item, id, params) +} + /// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. /// When the text is not what that edit gives, every earlier range goes stale. fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { @@ -445,7 +454,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { return Ok(Data::Undefined); } let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); - edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; record(h, r.item, &index, s, e - s, &insert)?; Ok(Data::Undefined) } @@ -719,16 +728,17 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let (r, part) = this_part(h, a)?; let contents = contents_of(arg(a, 1))?; let (index, s, e, _) = resolve(h, r)?; - let at = if before || matches!(arg(a, 2), Data::Undefined) { + // The place, and whether it is the end of a range, which rounds up to a character boundary. + let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) { let (items, spans) = part_spans(&index, part, s, e); let span = |k: usize| match spans { None => index.char_span(k), Some(list) => list.get(k).copied(), }; if before { - items.clone().next().and_then(span).map_or(s, |(x, _)| x) + (items.clone().next().and_then(span).map_or(s, |(x, _)| x), false) } else { - items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + (items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true) } } else { let rel = arg(a, 2); @@ -741,13 +751,15 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); } let (_, ts, te, _) = resolve(h, target)?; - if text_placement(arg(a, 3))? { te } else { ts } + if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) } }; + // A place inside a character (between the two halves of a surrogate pair) moves to its edge. + let b = index.byte(at, after); + let at = index.text[..b].encode_utf16().count(); if contents.is_empty() { let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); } - let b = index.byte(at, false); let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); let (lead, trail) = match part { Part::Characters => ("", ""), @@ -763,7 +775,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { ), }; let insert = format!("{lead}{contents}{trail}"); - edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; record(h, r.item, &index, at, 0, &insert)?; let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; let start = at + lead.encode_utf16().count(); @@ -1042,7 +1054,8 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; // A leading set on characters with auto leading fixes it even where auto gives that value. let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); - let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); + // An empty range changes nothing, also one inside a character that `ba..bb` widens to it. + let unchanged = s == e || ba == bb || styles.iter().all(|(st, p)| has(st, *p)); let fixed = match (attr, &wants) { (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), _ => None, @@ -1060,7 +1073,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { super::atomically(h, |h| { for (start, end, leading) in &spans { let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); - edit_item(h, r.item, "text.setRangeStyle", &p)?; + edit_text(h, r.item, "text.setRangeStyle", &p)?; } Ok(()) })?; @@ -1072,7 +1085,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + let answer = edit_text(h, r.item, "text.setRangeStyle", &p)?; if let Attr::TextFont = attr { let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; @@ -1234,7 +1247,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { o.insert("start".into(), json!(ba)); o.insert("end".into(), json!(bb)); } - edit_item(h, r.item, id, &p)?; + edit_text(h, r.item, id, &p)?; Ok(Data::Undefined) } @@ -1250,7 +1263,7 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember { get(link, doc_text_frames_impl) } -/// The ids of the document's type objects in paint order, kept while the document is unchanged. +/// The ids of the document's type objects, topmost first, kept while the document is unchanged. fn frame_ids(h: &Host, st: &DocState) -> Rc> { if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() && *uid == st.uid diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 89e050d68f..473077d8e6 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -272,6 +272,25 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() { assert_eq!(boards(&s).iter().map(|r| r.x0).collect::>(), [0.0, 100.0, 200.0], "side by side, not overlapping"); } +/// A saved preset whose rows the preferences hold above the most `file.new` takes reads as that +/// most, so `file.new` takes the preset as `file.newPresets` lists it; no rows stay no rows. +#[test] +fn a_saved_preset_with_too_many_rows_reads_in_range() { + let mut s = Session::new(); + let prefs = json!({ + "newDocPresets": [ + {"name": "Tall", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 1001}, + {"name": "Plain", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 0}, + ], + }); + s.apply_prefs(serde_json::from_value(prefs).unwrap()); + let saved = presets(&mut s, "Saved"); + assert_eq!(saved[0]["artboardLayout"]["rows"], json!(1000), "{}", saved[0]); + assert_eq!(saved[1]["artboardLayout"].get("rows"), None, "{}", saved[1]); + s.execute("file.new", &saved[0]).unwrap(); + assert_eq!(boards(&s).len(), 4); +} + /// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest /// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names /// the limit in points and, when the document's units aren't points, in those units too. diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index edd359282e..06c4670e93 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1207,3 +1207,25 @@ 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"); } + +/// A point change made before a call that fails and is put back, here a new document whose +/// profile cannot be read, is kept. +#[test] +fn a_point_change_before_a_failed_new_document_is_kept() { + let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + let (mut s, a, _) = doc(); + s.attach_new_doc_profiles(dir.clone()); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let out = log( + &mut s, + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\ + try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }", + ); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(out, vec![json!("refused")]); + assert_eq!(s.documents().len(), 1); + assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept"); +} diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 7d70741e69..dcecba422f 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -56,13 +56,13 @@ fn text_frames_add_point_area_and_path_type() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems;\ - var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ - var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ var pt = d.textFrames.add(); pt.contents = 'Point';\ var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ - vc.log(d.textFrames[3].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log(d.textFrames[0].contents); vc.log(d.textFrames[9] === undefined);\ vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", ); assert_eq!(out[0], json!(4)); @@ -297,6 +297,49 @@ fn bad_text_paint_is_refused_without_a_change() { assert_eq!(paints(&s, id), runs); } +#[test] +fn hidden_or_locked_type_is_not_edited() { + let (mut s, id) = doc_with("abc"); + let (runs, text) = (paints(&s, id), plain(&s, id)); + for hide in ["t.locked = true;", "t.hidden = true;"] { + for edit in [ + "r.characters[1].fillColor = red;", + "r.size = 30;", + "r.contents = 'xyz';", + "r.characters.add('!');", + "r.justification = Justification.CENTER;", + ] { + let e = failure( + &mut s, + &format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"), + ); + assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}"); + } + } + assert_eq!((paints(&s, id), plain(&s, id)), (runs, text)); +} + +#[test] +fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character() { + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = '\\uD83D\\uDE00X'; var r = t.textRange; r.length = 1;\ + var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);", + ); + assert_eq!(plain(&s, id), "\u{1F600}!X"); + assert_eq!(out, vec![json!(["!", "\u{1F600}"])]); + // An empty range there sits after the character too, and styling it changes nothing. + let runs = paints(&s, id); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; var r = t.textRange; r.length = 1;\ + var e = t.characters.add('', r), red = new RGBColor(); red.red = 255; e.fillColor = red; vc.log(e.length);", + ); + assert_eq!(out, vec![json!(0)]); + assert_eq!(paints(&s, id), runs); +} + #[test] fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { let (mut s, id) = doc_with("abc"); @@ -504,7 +547,7 @@ fn text_fonts_list_and_assign_fonts_by_name() { &format!( "var f = app.textFonts, m = '';\ try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ - try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + m = ''; try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" @@ -564,16 +607,16 @@ fn collections_of_text_add_words_characters_and_paragraphs() { let (mut s, id) = doc_with("ab"); s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); let before = undo_steps(&s); - let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);"); + let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); for (call, want) in [ ("t.words.add(null)", "contents must be a string or a number"), ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), - ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), ] { - let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); @@ -658,7 +701,7 @@ fn type_made_with_a_large_id_is_the_new_type() { fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); assert!(e.contains("this is not a TextFrame"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); assert!(e.contains("this is not a TextRange"), "{e}"); diff --git a/docs/mcp.md b/docs/mcp.md index a72b4cac53..793c599a3a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2838,7 +2838,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a placed item's `file`, are not defined yet and read as `undefined`. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type - objects in paint order, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and + objects topmost first, as `pageItems` lists them, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` From af7bf8bc69d021a531c89cdfefec77402ad12e89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:36:32 -0800 Subject: [PATCH 06/28] Scripts: textFrames.removeAll() refuses type on a locked artboard - textFrames.removeAll() deleted a text frame on a locked artboard, although its editable property reads false. It now throws "cannot delete objects on a locked artboard" with the ids before anything is deleted, as pathItems.removeAll() and remove() do. - add(contents, relativeObject) with a text range of a removed frame threw a type error. It now throws "Stale text range"; only an argument of another class gets the type error. - The hidden or locked edit test starts each case from a fresh frame, and checks run sizes and justification after each refused edit. The add test also checks the text of the frame the script edits. --- crates/engine/src/script/dom/text.rs | 23 ++++++++++----- crates/engine/src/tests/script_text.rs | 41 +++++++++++++++++++++++--- 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 4a25a8300f..0d993057ce 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -48,9 +48,9 @@ use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; use super::{ - Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, edit_item, editable, - float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, - typename_of, whole, with_doc, + Answer, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of, doc_ref, + edit_item, editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, + property, text, typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -744,8 +744,10 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let rel = arg(a, 2); let target = if handle_of(rel, "TextFrame").is_some() { whole_span(h, item_of(h, rel)?)?.1 + } else if handle_of(rel, "TextRange").is_some() { + span_of(h, rel, &["TextRange"])? } else { - span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + return Err(HostError::Type("relativeObject must be a TextRange or a TextFrame".into())); }; if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); @@ -1381,19 +1383,26 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3, 5, 6]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a +/// locked artboard, stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = frame_ids(h, st); let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + 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(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index dcecba422f..eef6b274e3 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -299,8 +299,10 @@ fn bad_text_paint_is_refused_without_a_change() { #[test] fn hidden_or_locked_type_is_not_edited() { - let (mut s, id) = doc_with("abc"); - let (runs, text) = (paints(&s, id), plain(&s, id)); + let state = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (paints(s, id), plain(s, id), sizes(s, id), t.para_at(0).justify), + _ => panic!("not text"), + }; for hide in ["t.locked = true;", "t.hidden = true;"] { for edit in [ "r.characters[1].fillColor = red;", @@ -309,14 +311,17 @@ fn hidden_or_locked_type_is_not_edited() { "r.characters.add('!');", "r.justification = Justification.CENTER;", ] { + // Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden. + let (mut s, id) = doc_with("abc"); + let before = state(&s, id); let e = failure( &mut s, &format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"), ); assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}"); + assert_eq!(state(&s, id), before, "{hide} {edit}"); } } - assert_eq!((paints(&s, id), plain(&s, id)), (runs, text)); } #[test] @@ -605,7 +610,7 @@ fn collections_of_text_add_words_characters_and_paragraphs() { } // Empty contents add nothing; bad arguments throw before anything changes. let (mut s, id) = doc_with("ab"); - s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); + let other = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap()["id"].as_u64().unwrap()); let before = undo_steps(&s); let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); @@ -620,7 +625,35 @@ fn collections_of_text_add_words_characters_and_paragraphs() { assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, other), "other"); assert_eq!(plain(&s, id), "ab"); + // A range of a frame that was removed is stale, not of the wrong class. + let e = failure(&mut s, "var f = app.activeDocument.textFrames, b = f[0], a = f[1], r = b.textRange; b.remove(); a.characters.add('x', r);"); + assert!(e.contains("Stale text range"), "{e}"); + assert_eq!(plain(&s, id), "ab"); +} + +/// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as +/// `pathItems.removeAll()` does. +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let (mut s, id) = doc_with("ab"); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&id.0.to_string()), "{e}"); + assert_eq!(plain(&s, id), "ab"); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + log(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]); } #[test] From 2f786096a50b28bffd73acf07ff87e5a0c7ad583 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:54:54 -0800 Subject: [PATCH 07/28] Scripts: path and type edits refuse objects on a locked artboard - A point edit (anchor, leftDirection, rightDirection, setEntirePath) and a paint, stroke or transform change of a path on a locked artboard changed it, although its editable property reads false. They now throw "Cannot edit PathItem : it is on a locked artboard" with nothing changed. - A text edit, createOutline() or a point/area conversion of type on a locked artboard, and areaText() or pathText() given a hidden or locked path, now throw "Cannot edit" with nothing changed. - A point assigned more than 4,000,000 pt from the origin was queued without a check and written by a later call. It now throws a range error when it is assigned, and the path keeps its points. --- crates/engine/src/script/dom/paths.rs | 46 ++++++++++++++----- crates/engine/src/script/dom/text.rs | 23 ++++++++-- crates/engine/src/tests/script_dom_paths.rs | 49 +++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 27 ++++++++++++ docs/mcp.md | 11 +++-- 5 files changed, 138 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ea57a3f49b..bb3759d62e 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -15,7 +15,9 @@ //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside //! groups and compound paths included. //! - 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. +//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing +//! changed. A point assigned more than `MAX_COORD` from the origin throws a range error when it +//! is assigned. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -106,6 +108,27 @@ fn cannot_edit(id: NodeId) -> HostError { HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) } +/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is +/// hidden or locked, or it is on a locked artboard. +fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { + if !editable(&st.doc, id) { + Some(cannot_edit(id)) + } else if super::on_locked_artboard(h, st, id) { + Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))) + } else { + None + } +} + +/// `p`, a point the script assigned, which must be within [`crate::MAX_COORD`] of the origin. +fn in_canvas(p: Point, what: &str) -> std::result::Result { + if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { + Ok(p) + } else { + Err(HostError::Range(format!("{what} is outside the canvas"))) + } +} + /// The path `d` names, which must still be in its document. fn path_of(h: &super::Host, d: &Data) -> std::result::Result { let item = item_of(h, d)?; @@ -179,7 +202,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// 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 +/// locked or is on a locked artboard, 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 { if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() @@ -190,14 +213,15 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; let r = f(&mut subs); - let (same, ok, aligned) = read_path(h, item, |st, _, pd| { + let (same, refused, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); - (pd.subpaths == subs, editable(d, item.id), aligned) + let same = pd.subpaths == subs; + (same, if same { None } else { protected(h, st, item.id) }, aligned) })?; if !same { - if !ok { - return Err(cannot_edit(item.id)); + if let Some(e) = refused { + return Err(e); } *h.dom.pending.borrow_mut() = Some((item, subs)); if aligned { @@ -253,9 +277,8 @@ fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { - let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)); - if !ok { - return Err(cannot_edit(item.id)); + if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) { + return Err(e); } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); @@ -676,7 +699,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { let f = with_doc(h, item.doc, |_, st| frame(st))?; let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; let c = h.dom.coords.get(); - let anchors: Vec = script.iter().map(|p| Anchor::corner(f.to_document(c, *p))).collect(); + let anchors: Vec = + script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; cut_points(h, item); @@ -1351,7 +1375,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul let p = point(arg(a, 1), what)?; let (item, _) = this_point(h, a)?; let fr = with_doc(h, item.doc, |_, st| frame(st))?; - Ok(fr.to_document(h.dom.coords.get(), p)) + in_canvas(fr.to_document(h.dom.coords.get(), p), what) } fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 0d993057ce..b051fcbb43 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -302,14 +302,26 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u } /// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing -/// changed, when the frame or a layer or group it is in is hidden or locked. +/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a +/// locked artboard. fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { - if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { - return Err(HostError::Error(format!("Cannot edit TextFrame {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); - } + refuse_protected(h, item, "TextFrame")?; edit_item(h, item, id, params) } +/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is +/// hidden or locked, or it is on a locked artboard. +fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> { + let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id))); + if !ok { + return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0))); + } + if on_locked { + return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0))); + } + Ok(()) +} + /// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. /// When the text is not what that edit gives, every earlier range goes stale. fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { @@ -548,6 +560,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { /// `null` when the type has nothing to outline and the command removed it. fn frame_outline(h: &Host, a: &[Data]) -> Answer { let item = this_frame(h, a)?; + refuse_protected(h, item, "TextFrame")?; let (_, r) = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; super::command_value(h, "type.createOutlines", &json!({})) @@ -569,6 +582,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), Some(true) => {} } + refuse_protected(h, item, "TextFrame")?; let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; new_ref(h, item.doc, result_id(&r).or(Some(item.id))) @@ -1365,6 +1379,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); } + refuse_protected(h, path, "PathItem")?; let orientation = if on_path { 4 } else { 2 }; let vertical = vertical_of(arg(a, orientation))?; let mode = if on_path { "onPath" } else { "area" }; diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 06c4670e93..591f0f1b05 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -854,6 +854,55 @@ fn locked_paths_and_wrong_objects_are_refused() { assert!(e.contains("not a PathPoint"), "{e}"); } +/// A point edit of a path on a locked artboard throws `Cannot edit` and changes nothing. +#[test] +fn point_edits_of_a_path_on_a_locked_artboard_are_refused() { + let (mut s, _, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let before = art(&s); + let steps = undo_steps(&s); + for source in [ + "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", + "app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, 1];", + "app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", + ] { + let e = failure(&mut s, source); + assert!(e.contains("Cannot edit PathItem") && e.contains("locked artboard"), "{source}: {e}"); + } + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +/// A point placed beyond the canvas throws when it is assigned, and the path keeps its points, so a +/// later member call does not lose an assignment that returned. +#[test] +fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { + let (mut s, a, _) = doc(); + let before = node(&s, a).path_data().unwrap().subpaths.clone(); + let far = crate::MAX_COORD * 1.5; + for source in [ + format!("app.activeDocument.pathItems[0].pathPoints[0].anchor = [{far}, 0];"), + format!("app.activeDocument.pathItems[0].pathPoints[0].rightDirection = [0, {far}];"), + format!("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [{far}, 1]]);"), + ] { + let e = failure(&mut s, &source); + assert!(e.contains("outside the canvas"), "{source}: {e}"); + } + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], q = p.pathPoints[1];\ + q.anchor = [45, 285];\ + try {{ p.pathPoints[0].anchor = [{far}, 0]; }} catch (e) {{ vc.log('threw'); }}\ + vc.log(q.anchor); vc.log(p.closed);" + ), + ); + assert_eq!(out, vec![json!("threw"), json!([45, 285]), json!(true)]); + let after = node(&s, a).path_data().unwrap().subpaths.clone(); + assert_eq!(after[0].anchors[0], before[0].anchors[0], "the point assigned beyond the canvas stays"); + assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); +} + #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index eef6b274e3..62e4d28a92 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -633,6 +633,33 @@ fn collections_of_text_add_words_characters_and_paragraphs() { assert_eq!(plain(&s, id), "ab"); } +/// Type on a locked artboard, and a hidden or locked path given to `areaText` or `pathText`, are +/// not changed. +#[test] +fn protected_type_and_paths_are_not_converted_or_edited() { + let (mut s, id) = doc_with("abc"); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + for edit in ["t.contents = 'xyz';", "t.textRange.size = 30;", "t.createOutline();", "t.convertPointObjectToAreaObject();"] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {edit}")); + assert!(e.contains("Cannot edit TextFrame") && e.contains("locked artboard"), "{edit}: {e}"); + } + assert_eq!(plain(&s, id), "abc"); + assert_eq!(undo_steps(&s), steps); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + for (hide, call) in [("p.locked = true;", "areaText(p)"), ("p.hidden = true;", "pathText(p)")] { + let e = failure(&mut s, &format!("var d = app.activeDocument, p = d.pathItems[0]; {hide} d.textFrames.{call};")); + assert!(e.contains("Cannot edit PathItem"), "{call}: {e}"); + assert_eq!(log(&mut s, "var d = app.activeDocument; vc.log([d.pathItems.length, d.textFrames.length]);"), vec![json!([1, 0])]); + } +} + /// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as /// `pathItems.removeAll()` does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 7edcb0be3e..726081df2c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2901,7 +2901,10 @@ other files through `$`: with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not - available yet. A `TextFrame` + available yet. `removeAll()` throws and deletes nothing when any type object is hidden or locked, is in a hidden or + locked layer or group, or is on a locked artboard (`cannot delete objects on a locked artboard`). A text edit, + `createOutline()` or a conversion of such a type object, and `areaText` or `pathText` given such a path, throw + `Cannot edit` with nothing changed. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to @@ -3033,8 +3036,10 @@ other files through `$`: `resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with `inscribed` true throw an error that says they are not available yet. 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 the fill, stroke and overprint of that compound path or + that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard, throws + `Cannot edit` with nothing changed. A point given to `setEntirePath` or assigned to `anchor`, `leftDirection` or + `rightDirection` more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps + its points. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity`, the gradient stops and the document's default paint are not available yet. From f1cb106d0293397c9f9a53bc39cc3e9eed289473 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 06:08:29 -0800 Subject: [PATCH 08/28] Docs: point limits name the x or y coordinate A script point is refused when its x or y is past MAX_COORD, not when its distance from the origin is. The module comment, the helper doc comment and docs/mcp.md now say so. --- crates/engine/src/script/dom/paths.rs | 6 +++--- docs/mcp.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index bb3759d62e..a9f36c1b4d 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -16,8 +16,8 @@ //! groups and compound paths included. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing -//! changed. A point assigned more than `MAX_COORD` from the origin throws a range error when it -//! is assigned. +//! changed. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a +//! range error when it is assigned. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -120,7 +120,7 @@ fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { } } -/// `p`, a point the script assigned, which must be within [`crate::MAX_COORD`] of the origin. +/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin. fn in_canvas(p: Point, what: &str) -> std::result::Result { if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD { Ok(p) diff --git a/docs/mcp.md b/docs/mcp.md index 726081df2c..dbb5934740 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3038,7 +3038,7 @@ other files through `$`: `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing changed. A point given to `setEntirePath` or assigned to `anchor`, `leftDirection` or - `rightDirection` more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps + `rightDirection` whose x or y is more than 4,000,000 pt from the origin throws a range error when it is given, and the path keeps its points. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity`, the gradient stops and From bb80534f3ea8b90512ff98f07e15442e778d9e93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:37:42 -0800 Subject: [PATCH 09/28] Scripts: path edits honor locked guides, keep selections and stay atomic PathItem handles carry the document's revert count, as main's page item handles now do, so points and new paths resolve again. resize() scales and changes the stroke weight in one step; paint writes that the command skips throw; Lock Guides refuses edits and removeAll on guide paths; removing a point remaps the selected anchors and segments; new paths go on the active layer while a group is isolated; translate's reflected parameters include changePositions; point tracking revisits only the paths an edit changed. StoryRange lists its fillColor, strokeColor and strokeWeight rows. --- crates/engine/src/script/dom/paths.rs | 177 +++++++++++++---- crates/engine/src/tests/script_dom_paths.rs | 184 ++++++++++++++++++ crates/engine/src/tests/script_text.rs | 4 +- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- 4 files changed, 323 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 1f308db41e..808567d3b6 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -115,6 +115,8 @@ fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option { Some(cannot_edit(id)) } else if super::on_locked_artboard(h, st, id) { Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))) + } else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) { + Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))) } else { None } @@ -158,9 +160,10 @@ fn read_path(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d }) } +/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count). fn path_ref(h: &super::Host, item: Item) -> Data { - let [high, low] = id_parts(item.id); - host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + host_ref("PathItem", &handle) } /// How many points a path with the subpaths `subs` has. @@ -264,9 +267,15 @@ 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. -fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { +fn drawing_normally(h: &super::Host, parent: Option, f: impl FnOnce() -> T) -> T { let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); + let isolation = h.session.borrow_mut().active_mut().map(|st| (st.uid, std::mem::replace(&mut st.isolation, parent))); let r = f(); + if let Some((uid, isolation)) = isolation + && let Some(st) = h.session.borrow_mut().document_mut(uid) + { + st.isolation = isolation; + } h.session.borrow_mut().draw_mode = kept; r } @@ -283,7 +292,13 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); } - keeping_paint(h, || edit_item(h, item, id, ¶ms)) + let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") + && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == "objects" && *v == Data::Number(0.0))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0))); + } + Ok(result) } /// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color @@ -378,11 +393,16 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); + if h.session.borrow().menu.guides_locked + && let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))) + { + return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0))); + } 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(); - (ids, refused, on_locked) - }); + Ok((ids, refused, on_locked)) + })?; 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}"))); @@ -407,7 +427,8 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { /// 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, || super::command_value(h, id, params))?)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, || super::command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -566,7 +587,8 @@ 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, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; + let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); + let id = made_id(&drawing_normally(h, parent, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -1137,19 +1159,22 @@ 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 (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)?; - } - if let Some(w) = new_width - && (w - width).abs() > 1e-9 - { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; - } - Ok(Data::Undefined) + // The scale and the stroke weight change together, or neither does. + super::atomically(h, |h| { + 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)?; + } + if let Some(w) = new_width + && (w - width).abs() > 1e-9 + { + edit_path(h, item, "stroke.set", json!({"weight": w}))?; + } + Ok(Data::Undefined) + }) } // ---- PathPoints ---- @@ -1216,7 +1241,10 @@ fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc> { fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { let node = { 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()) + s.documents().iter().find(|d| d.uid == key.0).and_then(|st| { + h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone()); + node_arc(&st.doc, NodeId(key.1)).cloned() + }) }; // A path that is gone makes its points stale, so that an undo that brings it back leaves them // stale. @@ -1242,31 +1270,39 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { /// at is skipped, as are its paths. 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; - } 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 seen = h.dom.point_nodes.borrow(); + let mut keys = Vec::new(); + docs.retain(|uid, before| { + let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc); + if after.is_some_and(|after| Arc::ptr_eq(before, after)) { + return 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); + let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) { + Some(item) => node_arc(before, item.id).into_iter().collect(), + None => before.layers.iter().collect(), + }; + while let Some(node) = todo.pop() { + if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) { + continue; } - None => { - docs.remove(uid); - changed.insert(*uid); + let key = (*uid, node.id.0); + if seen.contains_key(&key) { + keys.push(key); + } + if let Some(children) = node.children() { + todo.extend(children); } } - } - seen.keys().copied().filter(|(uid, _)| changed.contains(uid)).collect() + if let Some(after) = after { + *before = after.clone(); + true + } else { + false + } + }); + keys }; let editing = h.dom.editing.get(); for (uid, id) in keys { @@ -1549,16 +1585,71 @@ 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| { + let mut selection = with_doc(h, item.doc, |_, st| st.selection.clone()); + // The endpoints of the path's selected segments, before the point goes. + let old_ends: std::collections::BTreeSet<(usize, usize)> = match selection.segments.get(&item.id) { + Some(segments) => read_points(h, item, |subs| { + segments + .iter() + .filter_map(|&(sub, at)| subs.get(sub).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(sub, at), (sub, (at + 1) % sp.anchors.len())])) + .flatten() + .collect() + })?, + None => std::collections::BTreeSet::new(), + }; + let removed = edit_points(h, item, |subs| { if let Some((s, j)) = locate(subs, i) && let Some(sp) = subs.get_mut(s) { + let (n, closed) = (sp.anchors.len(), sp.closed); sp.anchors.remove(j); if sp.anchors.is_empty() { subs.remove(s); } + Some((s, j, n, closed)) + } else { + None } })?; + if let Some((s, j, n, closed)) = removed { + let remap = |(sub, at): (usize, usize)| { + if sub == s && (n == 1 || at == j) { None } else { Some((sub - usize::from(sub > s && n == 1), at - usize::from(sub == s && at > j))) } + }; + // Anchors held only as a selected segment's endpoints come back from the kept segments below. + if let Some(anchors) = selection.anchors.get_mut(&item.id) { + *anchors = anchors.iter().copied().filter(|a| !old_ends.contains(a)).filter_map(remap).collect(); + } + if let Some(segments) = selection.segments.get_mut(&item.id) { + *segments = segments + .iter() + .copied() + .filter(|&(sub, at)| sub != s || (at != j && (j == 0 || at != j - 1) && (!closed || j != 0 || at != n - 1))) + .filter_map(remap) + .collect(); + let ends: Vec<_> = read_points(h, item, |subs| { + segments + .iter() + .filter_map(|&(sub, at)| { + subs.get(sub).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(sub, at), (sub, (at + 1) % sp.anchors.len())]) + }) + .flatten() + .collect() + })?; + // Directly selected anchors stay selected; the kept segments' endpoints are added. + selection.anchors.entry(item.id).or_default().extend(ends); + } + if let Some((id, at)) = selection.key_anchor + && id == item.id + { + selection.key_anchor = remap(at).map(|at| (id, at)); + } + if selection.contains(item.id) && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || read_points(h, item, point_count)? == 0) { + selection.remove(item.id); + } + if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + st.selection = selection; + } + } cut_points(h, item); Ok(Data::Undefined) } @@ -1570,7 +1661,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec { let changes = [("changePositions", "boolean"), ("changeFillPatterns", "boolean"), ("changeFillGradients", "boolean"), ("changeStrokePattern", "boolean")]; let mut translate = vec![("deltaX", "number"), ("deltaY", "number")]; - translate.extend(changes.iter().skip(1)); + translate.extend(changes); let mut rotate = vec![("angle", "number")]; rotate.extend(changes); rotate.push(("rotateAbout", "Transformation")); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 591f0f1b05..b4da0d6850 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -299,6 +299,190 @@ fn path_point_wrapper_goes_stale_after_remove() { ); } +#[test] +fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.pathPoints[1].selected = PathPointSelection.ANCHORPOINT;\ + var anchor = p.pathPoints[1].anchor; p.pathPoints[0].remove();\ + vc.log(p.selectedPathPoints.length); vc.log(p.selectedPathPoints[0].anchor.join() == anchor.join());\ + vc.log(p.pathPoints[0].selected);", + ); + assert_eq!(out, vec![json!(1), json!(true), json!("PathPointSelection.ANCHORPOINT")]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); + assert!(s.active().unwrap().selection.contains(b)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(s.active().unwrap().selection.contains(b)); + + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert!(!s.active().unwrap().selection.contains(a)); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "set"})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(s.active().unwrap().selection.segments.get(&a).unwrap().iter().copied().collect::>(), vec![(0, 1)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); +} + +#[test] +fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { + let (mut s, a, _) = doc(); + s.execute( + "path.setAnchors", + &json!({"id": a.0, "subpaths": [ + {"anchors": [{"x": 0, "y": 0}]}, + {"anchors": [{"x": 10, "y": 10}, {"x": 20, "y": 20}, {"x": 30, "y": 30}]} + ]}), + ) + .unwrap(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [1, 1], [1, 2]]}], "mode": "set"})).unwrap(); + s.execute("select.key", &json!({"id": a.0, "anchor": [1, 2]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); + assert_eq!(s.active().unwrap().selection.key_anchor, Some((a, (0, 2)))); +} + +#[test] +fn locked_guides_refuse_path_edits_and_bulk_removal() { + let (mut s, a, _) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + s.set_guides_locked(true); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.pathPoints[0].anchor = [0, 0]", + "p.pathPoints[0].remove()", + "p.pathPoints.removeAll()", + "p.setEntirePath([[0, 0], [1, 1]])", + "p.closed = false", + "p.translate(1, 0)", + "p.filled = false", + "p.strokeWidth = 12", + "app.activeDocument.pathItems.removeAll()", + ] { + let out = + log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("guides are locked"), "{edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{edit}"); + } + assert!(is_guide(&s, a)); + s.set_guides_locked(false); + log(&mut s, "app.activeDocument.pathItems[0].translate(1, 0);"); + assert_ne!(art(&s), before); +} + +#[test] +fn document_path_creators_use_the_active_layer_during_isolation() { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let (mut s, a, b) = doc(); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": group.0})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap(); + let before = node(&s, group); + let selection = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let st = s.active().unwrap(); + let made = st.doc.node(layer).unwrap().children().unwrap().last().unwrap(); + assert!(matches!(made.kind, NodeKind::Path { .. }), "{create}"); + assert_eq!(st.doc.parent_of(made.id), Some(layer), "{create}"); + assert_eq!(node(&s, group), before, "{create}"); + assert_eq!(st.isolation, Some(group), "{create}"); + assert_eq!(st.selection, selection, "{create}"); + assert_eq!(undo_steps(&s), steps + 1, "{create}"); + } +} + +#[test] +fn paint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + for unpainted in [false, true] { + let (mut s, a, _) = doc(); + if unpainted { + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); + } + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute( + "graph.create", + &json!({ + "type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4" + }), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + let path = paths[0]; + s.execute("object.setProps", &json!({"ids": [path.0], "name": "generated"})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + for edit in [ + "p.fillColor = c", + "p.strokeColor = c", + "p.filled = !p.filled", + "p.stroked = !p.stroked", + "p.strokeWidth = 12", + "p.strokeCap = StrokeCap.ROUNDENDCAP", + "p.strokeJoin = StrokeJoin.BEVELENDJOIN", + "p.strokeMiterLimit = 22", + "p.strokeDashes = [3, 4]", + ] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), c = new RGBColor(); c.red = 123;\ + try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}" + ), + ); + assert_eq!(out.first(), Some(&json!("Error")), "{kind} {unpainted} {edit}: {out:?}"); + assert!(out[1].as_str().unwrap().contains("did not change the path"), "{kind} {edit}: {out:?}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{kind} {edit}"); + } + } + } +} + +#[test] +fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { + let (mut s, a, b) = doc(); + for i in 0..100 { + rect(&mut s, f64::from(i), 10.0, 2.0, 2.0); + } + let out = log( + &mut s, + &format!( + "var ps = app.activeDocument.pathItems, paths = [], points = [], expected = [];\ + for (var i = 0; i < ps.length; i++) {{ paths.push(ps[i]); points.push(ps[i].pathPoints[0]); }}\ + for (var i = 0; i < paths.length; i++) {{ paths[i].translate(2, 0); expected.push(points[i].anchor.join()); }}\ + var valid = true; for (var i = 0; i < points.length; i++) valid = valid && points[i].anchor.join() == expected[i]; vc.log(valid);\ + vc.run('object.move', {{ids: [{a}], dx: 1, dy: 0}});\ + try {{ points[100].anchor; }} catch (e) {{ vc.log(e.message); }}\ + paths[0].translate(1, 0); vc.log(points[101].anchor.join() == expected[101]);\ + vc.run('object.move', {{ids: [{b}], dx: 1, dy: 0}}); vc.run('edit.undo');\ + try {{ points[101].anchor; }} catch (e) {{ vc.log(e.message); }}", + a = a.0, + b = b.0 + ), + ); + assert_eq!(out, vec![json!(true), json!("Stale path point"), json!(true), json!("Stale path point")]); +} + #[test] fn points_read_before_a_removal_or_replacement_go_stale() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 0decf96eaf..29b676a377 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -360,7 +360,9 @@ fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character( var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);", ); assert_eq!(plain(&s, id), "\u{1F600}!X"); - assert_eq!(out, vec![json!(["!", "\u{1F600}"])]); + // Setting `length` to 1 moves the end out to the end of the emoji, and text added at a range's + // end joins the range. + assert_eq!(out, vec![json!(["!", "\u{1F600}!"])]); // An empty range there sits after the character too, and styling it changes nothing. let runs = paints(&s, id); let out = log( diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 1b74138da6..2a8b017f06 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -251,12 +251,12 @@ const INSIDE: &[(&str, &str)] = &[ "StoryRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \ characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \ - contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \ + contents contents= deSelect deSelect= duplicate duplicate= end end= fillColor fillColor= getLocalCharOverridesJSON \ getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \ getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \ length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \ paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \ - strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ + strikeThrough= strokeColor strokeColor= strokeWeight strokeWeight= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ underline underline= verticalScale verticalScale= words", ), ("StoryCharacters.", "prototype"), From e9010cd36384e0b643b1fd3e6ca230dac9e85636 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 22:03:07 -0800 Subject: [PATCH 10/28] Scripts: point handles go stale after a revert; flush keeps only live selections PathPoints and PathPoint handles carry the document's revert count. Writing point edits drops selected anchors and segments that no longer exist, in the same step as the edit. Overprint writes that the command skips throw, and changeFillGradients true with changePositions false throws until it is available. --- crates/engine/src/script/dom/paths.rs | 65 +++++++---- crates/engine/src/tests/script_dom_paths.rs | 113 ++++++++++++++++++++ 2 files changed, 159 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 808567d3b6..0a5aeacf31 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -54,7 +54,8 @@ //! are locked; assigning the value the path has runs no command. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, -//! so `changeFillGradients` false throws an error that says it is not available yet. +//! so `changeFillGradients` false throws an error that says it is not available yet, as does +//! `changeFillGradients` true with `changePositions` false. use std::rc::Rc; use std::sync::Arc; @@ -70,8 +71,8 @@ use vectorcraft_tools::params::gradient_params; use super::{ Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, - edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, - on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, typename_of, whole, with_doc, + edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, item_rect, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, returns, this_doc, typed, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -142,9 +143,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result std::result::Result { +/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them. +fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result { let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) { + return Err(HostError::Error(STALE_ITEM.into())); + } let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; path_of(h, &path_ref(h, Item { doc, id })) } @@ -255,7 +259,27 @@ 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}))?; + super::atomically(h, |h| { + if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { + let selection = &mut st.selection; + if let Some(anchors) = selection.anchors.get_mut(&item.id) { + anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len())); + } + if let Some(segments) = selection.segments.get_mut(&item.id) { + segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count())); + if segments.is_empty() { + selection.segments.remove(&item.id); + } + } + if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) { + selection.key_anchor = None; + } + if selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || point_count(&subs) == 0 { + selection.remove(item.id); + } + } + edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths})) + })?; Ok(()) } @@ -293,8 +317,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r o.entry("ids").or_insert_with(|| json!([item.id.0])); } let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; - if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") - && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == "objects" && *v == Data::Number(0.0))) + let count = if id == "object.setOverprint" { "changed" } else { "objects" }; + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint") + && matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0))) { return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0))); } @@ -603,8 +628,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { fn path_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; - let [high, low] = id_parts(item.id); - Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low])) + let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)); + Ok(host_ref("PathPoints", &handle)) } fn path_closed(h: &super::Host, a: &[Data]) -> Answer { @@ -1091,6 +1116,9 @@ fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::R if flags[2] == Some(false) { return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2]))); } + if flags[0] == Some(false) && flags[2] == Some(true) { + return Err(HostError::Error(format!("{} true with {} false is not available yet", names[2], names[0]))); + } if let (Some(f), Some(s)) = (flags[1], flags[3]) && f != s { @@ -1181,8 +1209,8 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result { let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; - path_at(h, *run, *uid, *high, *low) + let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; + path_at(h, *run, *uid, *high, *low, *reverts) } fn points_length(h: &super::Host, a: &[Data]) -> Answer { @@ -1196,8 +1224,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer { } fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { - let [high, low] = id_parts(item.id); - host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))]) + let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec(); + handle.extend([float(i as u64), float(point_cuts(h, item))]); + host_ref("PathPoint", &handle) } /// How many times the points read of `item` have gone stale, after [`see_points`] notes a change @@ -1368,8 +1397,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer { /// point of the path removed or replaced since `this` was read. pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> { let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let item = path_at(h, *run, *uid, *high, *low)?; + let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let item = path_at(h, *run, *uid, *high, *low, *reverts)?; if whole(*cuts) != Some(point_cuts(h, item)) { return Err(HostError::Error(STALE_POINT.into())); } @@ -1576,9 +1605,7 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { out })?; h.charge_call(picked.len() as u64)?; - let [high, low] = id_parts(item.id); - let cuts = float(point_cuts(h, item)); - let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect(); + let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); Ok(Data::Array(points)) } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b4da0d6850..b08ed50e9a 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -329,6 +329,56 @@ fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); } +#[test] +fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { + for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let anchors = selected_anchors(&s, a); + let steps = undo_steps(&s); + let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}")); + assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] }); + assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed); + let selection = &s.active().unwrap().selection; + assert!(selection.contains(b)); + assert_eq!(selected_anchors(&s, a), anchors); + let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect(); + assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] }); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, a).path_data().unwrap().subpaths[0].closed); + } + } +} + +#[test] +fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = node(&s, a); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\ + p.name = 'changed'; vc.run('file.revert');\ + try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\ + var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\ + fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);" + ), + ); + assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}"); + assert_ne!(node(&s, a).path_data(), before.path_data()); + s.execute("file.revert", &json!({})).unwrap(); + } +} + #[test] fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() { let (mut s, a, _) = doc(); @@ -458,6 +508,46 @@ fn paint_writes_refuse_generated_graph_design_paths() { } } +#[test] +fn overprint_writes_refuse_generated_graph_design_paths() { + for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] { + let (mut s, a, _) = doc(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap(); + s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap(); + let graph = NodeId( + s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"})) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap(); + let graph_node = node(&s, graph); + let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap(); + let mut paths = Vec::new(); + design.walk(&mut |n| { + if matches!(n.kind, NodeKind::Path { .. }) { + paths.push(n.id); + } + }); + s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap(); + let before = (art(&s), undo_steps(&s)); + for property in ["fillOverprint", "strokeOverprint"] { + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\ + try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);" + ), + ); + assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}"); + assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}"); + assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}"); + } + } +} + #[test] fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() { let (mut s, a, b) = doc(); @@ -1087,6 +1177,29 @@ fn a_point_beyond_the_canvas_throws_when_it_is_assigned() { assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written"); } +#[test] +fn transforms_refuse_moving_gradients_without_the_path() { + for transform in + ["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"] + { + let (mut s, a, b) = doc(); + s.execute( + "paint.setFill", + &json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + ) + .unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)); + let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}")); + assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}"); + assert!( + out[1].as_str().unwrap().contains("changeFillGradients true with changePositions false is not available yet"), + "{transform}: {out:?}" + ); + assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}"); + } +} + #[test] fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { let mut s = Session::new(); From 743e38ebf6549eeff373721e337f4dca3ecfb027 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:08:13 -0800 Subject: [PATCH 11/28] Scripts: path creation and paint edits replay as run; mixed picks keep their anchors Scripted shapes record the layer they were drawn on, so replay does not draw them behind other art or inside an isolated group. Paint edits on objects keep the new-art defaults on replay, and a solid new-art color copied to a path keeps its color model. An anchor picked next to a selected segment stays selected and is listed by selectedPathPoints. closed set on an empty path applies to its first points. Text fillColor and strokeColor reflect as Color. Saved file.new steps keep the old row rounding. --- crates/engine/src/cmd.rs | 6 ++ crates/engine/src/cmd/create.rs | 29 +++++- crates/engine/src/cmd/newdoc.rs | 9 +- crates/engine/src/cmd/paint.rs | 18 +++- crates/engine/src/cmd/select.rs | 9 +- crates/engine/src/cmd/stroke.rs | 2 +- crates/engine/src/script/dom/paths.rs | 61 +++++------ crates/engine/src/script/dom/text.rs | 1 + crates/engine/src/tests/script_dom.rs | 16 +++ crates/engine/src/tests/script_dom_paths.rs | 108 ++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 11 ++ docs/mcp.md | 24 +++-- 12 files changed, 245 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8a4e6ebe6f..4f8a211d51 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -441,6 +441,12 @@ pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&' /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in /// ([`plugin::run_command`]), which needs the command's id. pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + if matches!(spec.id, "shape.rectangle" | "shape.ellipse" | "shape.polygon" | "shape.star" | "path.create") { + return create::on_layer(s, p, spec.id, |s| (spec.run)(s, p)); + } + if matches!(spec.id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + return paint::object_only(s, p, spec.id, |s| (spec.run)(s, p)); + } if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 16ceda7d38..31b9950296 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -12,6 +12,25 @@ use super::{ }; use crate::EngineError; +pub(crate) fn on_layer(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if p.get("onLayer").is_none() { + return run(s); + } + let parent = object_param(p, "onLayer", cmd)?; + let d = &s.doc()?.doc; + if let Some(id) = parent + && !d.node(id).is_some_and(|n| n.is_layer() && d.is_editable(id)) + { + return Err(bad(cmd, "onLayer must name an editable layer")); + } + let mode = std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal); + let isolation = std::mem::replace(&mut s.doc_mut()?.isolation, parent); + let result = run(s); + s.doc_mut()?.isolation = isolation; + s.draw_mode = mode; + result +} + pub fn specs() -> Vec { vec![ cmd!( @@ -19,7 +38,7 @@ pub fn specs() -> Vec { "Rectangle", [], None, - "{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rectangle ), @@ -28,7 +47,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -37,7 +56,7 @@ pub fn specs() -> Vec { "Polygon", [], None, - "{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", + "{cx, cy, radius, onLayer?: layer id|null (draw normally on this layer), sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", has_doc, polygon ), @@ -46,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", has_doc, star ), @@ -137,7 +156,7 @@ pub fn specs() -> Vec { "Create Path", [], None, - "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], closed?: bool, d?: SVG path data} → {id}", + "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], onLayer?: layer id|null (draw normally on this layer), closed?: bool, d?: SVG path data} → {id}", has_doc, path_create ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index db0495ac97..0416c5b406 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -870,7 +870,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); - let mut settings = base.with_params(p, C)?; + let mut params = p.clone(); + if s.replaying() + && let Some(rows) = params.pointer_mut("/artboardLayout/rows") + && let Some(value) = rows.as_f64().filter(|r| r.is_finite() && *r >= 1.0) + { + *rows = json!(value.round().min(MAX_ARTBOARDS as f64) as u32); + } + let mut settings = base.with_params(¶ms, C)?; if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index c722e2a58b..726aada285 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", has_doc, |s, p| set_paint(s, p, true) ), @@ -948,6 +948,22 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) apply_paint_opacity(s, p, Some(paint), None, fill) } +pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if !switch_or(p, "objectOnly", false, cmd)? { + return run(s); + } + if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) { + return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly")); + } + let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone()); + let result = run(s); + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept; + if result.is_ok() { + s.note_defaults_only(); + } + result +} + /// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or /// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' /// own opacity for a fill (with no paint or a solid color), nothing on a target without that item. diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 931504dedb..0e937376bd 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1034,8 +1034,7 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } let mut members = Members::of(sel); for (id, refs) in items { - // A segment pick's endpoints aren't selected anchors: start from none of them. - let segment_pick = sel.segments.remove(&id).is_some(); + let endpoints = sel.segments.remove(&id).and_then(|segments| segment_endpoints(d, id, &segments, "select.anchorsMany").ok()); let all: BTreeSet = d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); // Anything but a path is selected, toggled or deselected as a whole. @@ -1049,8 +1048,10 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } // From the anchors selected now (all of them for a path selected as a whole). let now = match sel.partial(id) { - _ if segment_pick => BTreeSet::new(), - Some(a) => a.clone(), + Some(a) => match &endpoints { + Some(endpoints) => a.difference(endpoints).copied().collect(), + None => a.clone(), + }, None if members.contains(id) => all.clone(), None => BTreeSet::new(), }; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e1d64b2112..4ee4f01c10 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 0a5aeacf31..8c8e758c7b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -289,19 +289,11 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'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) } -/// 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. -fn drawing_normally(h: &super::Host, parent: Option, f: impl FnOnce() -> T) -> T { - let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); - let isolation = h.session.borrow_mut().active_mut().map(|st| (st.uid, std::mem::replace(&mut st.isolation, parent))); - let r = f(); - if let Some((uid, isolation)) = isolation - && let Some(st) = h.session.borrow_mut().document_mut(uid) - { - st.isolation = isolation; - } - h.session.borrow_mut().draw_mode = kept; - r +/// Runs a path creation command with its layer placement recorded. +fn drawing_normally(h: &super::Host, parent: Option, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { + let mut params = params.clone(); + params["onLayer"] = json!(parent.map(|p| p.0)); + super::command_value(h, id, ¶ms) } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which @@ -315,6 +307,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + o.insert("objectOnly".into(), json!(true)); + } } let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; let count = if id == "object.setOverprint" { "changed" } else { "objects" }; @@ -453,7 +448,7 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); - let id = made_id(&drawing_normally(h, parent, || super::command_value(h, id, params))?)?; + let id = made_id(&drawing_normally(h, parent, id, params)?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -613,9 +608,9 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); - let id = made_id(&drawing_normally(h, parent, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?; if unpainted { - keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; + command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?; } Ok(id) })?; @@ -640,7 +635,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points(h, item, |subs| { + if subs.is_empty() && closed { + subs.push(SubPath::new(Vec::new(), closed)); + } else { + subs.iter_mut().for_each(|sp| sp.closed = closed); + } + })?; Ok(Data::Undefined) } @@ -836,10 +837,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul Ok(match linked { true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}), true => json!({"swatch": name}), - false => json!({"color": colors::param(color)}), + false => json!({"color": colors::param(color), "keepModel": true}), }) } - Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})), + Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})), Paint::Gradient(g) => { let mut g = g.clone(); if g.geom.is_some() || g.freeform.is_some() { @@ -1502,12 +1503,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[ if held { return true; } - if !sel.contains(id) || sel.segments.contains_key(&id) { + if !sel.contains(id) { return false; } match sel.partial(id) { None => true, - Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + Some(picked) => locate(subs, i).is_some_and(|(s, j)| { + picked.contains(&(s, j)) + && !sel + .segments + .get(&id) + .is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j))) + }), } } @@ -1592,17 +1599,11 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { 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)) { + if !held && !sel.contains(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; - } - out + let total: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); + (0..total).filter(|&i| anchor_selected(sel, item.id, held, &pd.subpaths, i)).collect() })?; h.charge_call(picked.len() as u64)?; let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index e96645da43..f5a8c840fe 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1617,6 +1617,7 @@ fn attr_type(attr: Attr) -> &'static str { match attr { Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", Attr::TextFont => "TextFont", + Attr::FillColor | Attr::StrokeColor => "Color", _ => "number", } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4bebfb6ab9..7b44a3eb04 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1024,6 +1024,22 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn file_new_replays_legacy_fractional_and_large_rows() { + for (rows, rounded) in [(3.6, 4), (1001.2, 1000)] { + let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); + let mut s = Session::new(); + assert!(s.execute("file.new", ¶ms).unwrap_err().to_string().contains("rows must be a whole number")); + s.replay("file.new", ¶ms).unwrap(); + let mut expected = Session::new(); + let mut params = params; + params["artboardLayout"]["rows"] = json!(rounded); + expected.execute("file.new", ¶ms).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|b| b.rect).collect::>(); + assert_eq!(boards(&s), boards(&expected)); + } +} + #[test] fn a_listed_preset_keeps_more_rows_than_artboards() { use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b08ed50e9a..c1ec77f4e1 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -49,6 +49,114 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node { s.active().unwrap().doc.node(id).unwrap().clone() } +#[test] +fn path_creation_replays_on_top_of_the_active_layer() { + for mode in ["behind", "inside", "isolation"] { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let setup = || { + let (mut s, a, b) = doc(); + if mode == "isolation" { + let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "{mode}: {create}"); + assert_eq!(replay.draw_mode, s.draw_mode); + assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation); + } + } +} + +#[test] +fn path_paint_edits_replay_without_changing_new_art() { + let (mut s, a, _) = doc(); + let start = s.journal.len(); + log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ + p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\ + app.activeDocument.pathItems.rectangle(100, 200, 20, 30);", + ); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(node(&replay, a).appearance, node(&s, a).appearance); + assert_eq!(art(&replay), art(&s)); + assert_eq!(replay.paint, s.paint); + assert_eq!(replay.fill_active, s.fill_active); + assert_eq!(replay.recent_colors, s.recent_colors); +} + +#[test] +fn mixed_anchor_and_segment_picks_keep_independent_anchors() { + for selected in ["ANCHORPOINT", "NOSELECTION"] { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\ + vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\ + p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);", + if selected == "ANCHORPOINT" { 1 } else { 3 } + ), + ); + assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]); + assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 })); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] })); + } +} + +#[test] +fn an_empty_path_keeps_closed_before_points_are_added() { + for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);"] { + let (mut s, _, _) = doc(); + let start = s.journal.len(); + let out = log( + &mut s, + &format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"), + ); + assert_eq!(out, [json!(true), json!(true)]); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s)); + } +} + +#[test] +fn enabling_path_paint_preserves_the_new_art_color_model() { + for fill in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; + s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap(); + let new_art = s.new_art(); + let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; + log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); + let n = node(&s, a); + assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want); + } +} + /// Each number of `v` rounded to 3 decimals, in place. fn rounded(v: &Value) -> Value { match v { diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 29b676a377..a18184d7ce 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -46,6 +46,17 @@ fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { } } +#[test] +fn character_color_attributes_reflect_as_color() { + let (mut s, _) = doc_with("color"); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.characterAttributes;\ + vc.log(a.reflect.find('fillColor').dataType); vc.log(a.reflect.find('strokeColor').dataType);", + ); + assert_eq!(out, [json!("Color"), json!("Color")]); +} + #[test] fn text_frames_add_point_area_and_path_type() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 6070ae384a..1ff018d34e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3124,7 +3124,8 @@ through `$`: `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`, `fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and `strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with - `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Reflection reports + `fillColor` and `strokeColor` as `Color`. Paragraph attributes are `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` @@ -3175,7 +3176,9 @@ 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. These creation commands take `onLayer: layerId` to draw normally on that layer and + record this placement for replay. A null `onLayer` draws normally on the active layer. + A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item 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 @@ -3183,8 +3186,11 @@ through `$`: (counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the 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 + `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. + Script path paint and stroke edits pass `objectOnly: true` with explicit `ids` to keep new-art paint, the active proxy + and remembered colors during execution and replay. `paint.setFill`, `paint.setStroke` and `stroke.set` accept + this option with `ids` or `id`; it cannot be combined with `defaultsOnly: true`. + 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 read as the grid snaps them. @@ -3204,7 +3210,8 @@ through `$`: the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is - closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner + closed, and assigning it opens or closes them all. An empty path keeps an assigned closure state for its first + subpath. `setEntirePath` takes at most 100,000 points and gives corner points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed @@ -3212,7 +3219,8 @@ through `$`: than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point, - and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole. + and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment + picks. A path in a selected group or compound path is selected as a whole. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's @@ -3228,7 +3236,7 @@ through `$`: was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the - stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint + stroke. A copied solid new-art color keeps its color model. A new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. `fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. Sizes and radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000, @@ -10492,6 +10500,8 @@ the rows give the current number of artboards, and New Document drops the rows w `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). +Replaying a saved `file.new` command rounds legacy fractional row counts and caps them at 1000. New calls still +require whole row counts from 1 to 1000. `file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets, kept in the preferences by `file.newPresets.save` and removed by `file.newPresets.delete`). A listed preset can be passed straight back to `file.new`. Print presets and sizes without `units` start in `unitsGeneral`; screen presets From c822678ed7dc5695ab2d02106f1dd20a5314672d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 00:37:09 -0800 Subject: [PATCH 12/28] Scripts: point removal journals its selection, and point reads flush closures Removing a point records the shifted anchor selection as select commands, so replay moves the same points. Reading a point's selection writes waiting closure changes first when they drop a selected segment. selectedPathPoints walks the subpaths once. pathItems[name] looks up a numeric name that is not an index, as pageItems does. --- crates/engine/src/script/dom/paths.rs | 98 +++++++++++++++++++-- crates/engine/src/tests/script_dom_paths.rs | 61 +++++++++++++ 2 files changed, 150 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 8c8e758c7b..a828db6b00 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -178,6 +178,8 @@ fn point_count(subs: &[SubPath]) -> 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() { + #[cfg(test)] + tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1)); if i < sp.anchors.len() { return Some((s, i)); } @@ -380,17 +382,26 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer { }; } 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 match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }; + }; Ok(with_doc(h, doc, |_, st| path_items(h, st).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 Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + items_named(h, doc, name) +} + +fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { let ids = path_items(h, st); 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())); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -398,6 +409,7 @@ 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), + 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), @@ -1526,12 +1538,19 @@ 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 when they add or remove points of this path or invalidate +/// selected segments. 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) => read_path(h, item, |st, _, pd| { + !same_layout(subs, &pd.subpaths) + || st + .selection + .segments + .get(&item.id) + .is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count()))) + })?, _ => false, }; if moved { @@ -1602,8 +1621,25 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { if !held && !sel.contains(item.id) { return Vec::new(); } - let total: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); - (0..total).filter(|&i| anchor_selected(sel, item.id, held, &pd.subpaths, i)).collect() + let segments = sel.segments.get(&item.id); + let ends: std::collections::BTreeSet<_> = segments + .into_iter() + .flatten() + .filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())])) + .flatten() + .collect(); + let partial = sel.partial(item.id).filter(|_| !held); + let mut picked = Vec::new(); + let mut offset = 0; + for (s, sp) in pd.subpaths.iter().enumerate() { + for j in 0..sp.anchors.len() { + if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) { + picked.push(offset + j); + } + } + offset += sp.anchors.len(); + } + picked })?; h.charge_call(picked.len() as u64)?; let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); @@ -1674,8 +1710,22 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { if selection.contains(item.id) && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || read_points(h, item, point_count)? == 0) { selection.remove(item.id); } - if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) { - st.selection = selection; + super::flush(h)?; + let (doc, changed, layer, rows) = + with_doc(h, item.doc, |_, st| (st.doc.clone(), st.selection != selection, st.active_layer, st.highlighted_rows())); + if changed { + on_doc(h, item.doc.uid, false, |h| { + super::restore_selection(h, &doc, &selection)?; + if let Some(anchors) = selection.anchors.get(&item.id) + && with_doc(h, item.doc, |_, st| st.selection.anchors.get(&item.id) != Some(anchors)) + { + command(h, "select.anchors", &json!({"id": item.id.0, "anchors": anchors, "mode": "add"}))?; + if let Some(segments) = selection.segments.get(&item.id).filter(|s| !s.is_empty()) { + command(h, "select.segments", &json!({"id": item.id.0, "segments": segments, "mode": "add"}))?; + } + } + super::restore_layer(h, item.doc.uid, layer, &rows) + })?; } } cut_points(h, item); @@ -1836,3 +1886,33 @@ pub(super) fn classes(l: &Link) -> Vec { ), ] } + +#[cfg(test)] +mod tests { + use std::cell::Cell; + + use serde_json::json; + + use crate::Session; + + thread_local! { + pub(super) static LOCATE_STEPS: Cell = const { Cell::new(0) }; + } + + #[test] + fn selected_points_do_not_rescan_subpaths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128]; + s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap(); + s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap(); + LOCATE_STEPS.with(|steps| steps.set(0)); + let out = s + .execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"})) + .unwrap(); + assert_eq!(out["log"], json!([2])); + LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get())); + } +} diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index c1ec77f4e1..501d027f3b 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -221,6 +221,23 @@ fn path_items_read_with_a_name_give_the_named_path() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]); } +#[test] +fn path_items_read_non_index_numbers_as_names() { + for name in ["-1", "1.5", "4294967295"] { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": name})).unwrap(); + let out = log( + &mut s, + &format!( + "var d = app.activeDocument; vc.log(d.pathItems['{name}'].name);\ + vc.log(d.pathItems[{name}].name == d.pageItems[{name}].name);\ + vc.log(d.pathItems[-2] === undefined); vc.log(d.pathItems[1].name == '{name}');" + ), + ); + assert_eq!(out, vec![json!(name), json!(true), json!(true), json!(false)]); + } +} + /// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes /// nothing, as `pageItems.removeAll()` and `remove()` do. #[test] @@ -437,6 +454,50 @@ fn removing_a_point_remaps_selection_and_clears_deleted_geometry() { assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); } +#[test] +fn removing_a_point_replays_selection_before_moving_anchors() { + for segments in [false, true] { + let setup = || { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1], [0, 3]]})).unwrap(); + if segments { + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "add"})).unwrap(); + } else { + s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();"); + let a = s.active().unwrap().selection.objects[0]; + assert_eq!(selected_anchors(&s, a), Some(if segments { vec![(0, 0), (0, 1), (0, 2)] } else { vec![(0, 0), (0, 2)] })); + s.execute("path.moveAnchors", &json!({"dx": 7, "dy": 3})).unwrap(); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "segments: {segments}"); + assert_eq!(replay.active().unwrap().selection, s.active().unwrap().selection, "segments: {segments}"); + } +} + +#[test] +fn point_selection_reads_flush_removed_closing_segments() { + for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], first = p.pathPoints[0], last = p.pathPoints[3];\ + p.closed = false; vc.log(first.selected); vc.log(last.selected); p.name;\ + vc.log(first.selected); vc.log(last.selected); vc.log(p.pathPoints[1].selected);", + ); + assert_eq!(out[..4], vec![json!("PathPointSelection.ANCHORPOINT"); 4]); + assert_eq!(out[4], json!("PathPointSelection.NOSELECTION")); + } +} + #[test] fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() { for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] { From b270b624161988475bdd2da8b151e878f6c21fc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 22:38:28 -0800 Subject: [PATCH 13/28] Scripts: answer review points on selection, opacity, text ranges and host classes - A path saved with only segments selected is restored with its segments and the anchors at their ends, in its place in the selection, not with every anchor. - layer.opacity compares the new value with the rounded value the getter reports, so 50.00009 at 50% is set. - characters.add with a range of a removed frame throws "Stale text range" instead of a wrong-type error. - `i in object` of a host class reads the indexer's raw answer and makes no object of it. - define_host_classes checks the whole batch and reserves heap for the prototypes, constructors and member functions first, each property key once; a batch that fails later takes its classes and globals out again, so a corrected batch installs. - The receiver and the arguments that are objects of host classes count toward the crossing limits, with class names counted in UTF-16 units. - A hosted answer is checked for its limits and references, in the order it is written, before any object is made, so a refused answer leaves existing objects of host classes as they were. - A waiting member's answer that cannot be made (an unknown class) is thrown at the waiting call, where the script can catch it. - The array methods visit an object with a host indexer index by index, so slice and map see every index it answers. - docs/mcp.md and docs/roadmap.md: an omitted or null presetSettings uses the startup preset; PLACEATEND in a clip group or a clipped layer goes directly above the clipping path; layer opacity reads rounded to 4 decimals, and assigning the same opacity runs no command. - Tests: the selection test checks the refused assignment inside the script, and the Missing Glyph Protection test fails when a bundled face is missing or falls back to another face instead of returning. --- crates/engine/src/script/dom.rs | 21 ++- crates/engine/src/script/dom/layers.rs | 5 +- crates/engine/src/script/dom/text.rs | 6 +- crates/engine/src/tests/script_dom.rs | 45 ++++++ crates/engine/src/tests/script_text.rs | 14 +- crates/js/src/builtins/array.rs | 4 +- crates/js/src/file_classes.rs | 12 ++ crates/js/src/host.rs | 73 ++++++--- crates/js/src/host_classes.rs | 188 ++++++++++++++++++++++- crates/js/src/host_tests.rs | 205 +++++++++++++++++++++++++ crates/js/src/interp.rs | 2 +- crates/js/src/realm.rs | 19 ++- docs/mcp.md | 12 +- docs/roadmap.md | 2 +- 14 files changed, 560 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bde785060d..ba80bf3a0f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -563,9 +563,24 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - 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 => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), + // A path with only segments selected gets the anchors at their ends here, which + // keeps its place in the selection, and the segments below. + let anchors: Vec<[usize; 2]> = match (before.anchors.get(i), before.segments.get(i)) { + (Some(a), _) => a.iter().map(|(p, k)| [*p, *k]).collect(), + (None, Some(segments)) => { + let all: std::collections::BTreeSet<[usize; 2]> = + doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(); + let mut ends = std::collections::BTreeSet::new(); + for &(p, k) in segments { + // The last segment of a closed subpath ends at its first anchor. + let next = if all.contains(&[p, k + 1]) { [p, k + 1] } else { [p, 0] }; + ends.extend([[p, k], next].into_iter().filter(|a| all.contains(a))); + } + ends.into_iter().collect() + } + (None, 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}) }) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 684a6c84fb..208fae0f67 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -234,7 +234,10 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) + // The number the getter reports (rounded to 4 decimals), or one that stores as the opacity the + // layer has, leaves the layer as it is. + let same = |n: &crate::doc::Node| (f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4 == v || n.opacity == (v / 100.0) as f32; + set_layer(h, a, "object.setProps", same, json!({"opacity": v})) } fn layer_color(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index df600f6c6b..6313c9c272 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -790,7 +790,11 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { let target = if handle_of(rel, "TextFrame").is_some() { whole_span(h, item_of(h, rel)?)?.1 } else { - span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + // A range of a removed frame keeps its own error. + span_of(h, rel, &["TextRange"]).map_err(|e| match e { + HostError::Error(m) if m == STALE_RANGE => HostError::Error(m), + _ => HostError::Type("relativeObject must be a TextRange or a TextFrame".into()), + })? }; if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { return Err(HostError::Error("relativeObject must be text of the same text frame".into())); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 94c92e591f..ab103b191b 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -306,6 +306,19 @@ fn an_opacity_close_to_the_current_one_is_set() { assert_eq!(out, vec![json!(50.0001)]); } +/// A layer opacity near the one the layer has, but not the one it reports, is set. +#[test] +fn a_layer_opacity_close_to_the_current_one_is_set() { + let (mut s, _, _) = doc(); + let out = log(&mut s, "var l = app.activeDocument.layers[0]; l.opacity = 50; l.opacity = 50.00009; vc.log(l.opacity);"); + assert_eq!(out, vec![json!(50.0001)]); + // The same number again stores as the opacity the layer has, and runs no command. + let sets = |s: &Session| s.journal.iter().filter(|(id, _)| id == "object.setProps").count(); + let before = sets(&s); + log(&mut s, "app.activeDocument.layers[0].opacity = 50.00009;"); + assert_eq!(sets(&s), before); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -313,6 +326,18 @@ fn selection_assignment_is_atomic_across_invalid_items() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); assert!(e.contains("Cannot select PathItem"), "{e}"); assert!(s.active().unwrap().selection.objects.is_empty()); + // In either order, the refused assignment leaves nothing selected while the script runs. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + function pick(list) { var m = ''; try { d.selection = list; } catch (e) { m = e.message; } vc.log([m, d.selection === null]); }\ + pick([p[0], p[1]]); pick([p[1], p[0]]);", + ); + assert_eq!(out.len(), 2); + for o in &out { + assert!(o[0].as_str().is_some_and(|m| m.contains("Cannot select PathItem")), "{o}"); + assert_eq!(o[1], json!(true), "{o}"); + } s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log( &mut s, @@ -700,6 +725,26 @@ fn an_edit_keeps_direct_selected_anchors() { assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); } +/// A path saved with selected segments and no anchor entry gets its segments back, and only the +/// anchors at their ends. +#[test] +fn an_edit_gives_a_path_with_only_segments_no_other_anchors() { + let (mut s, a, b) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "set"})).unwrap(); + let ends = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert_eq!(ends.as_ref().map(|e| e.len()), Some(2)); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + s.active_mut().unwrap().selection.anchors.remove(&a); + let before = s.active().unwrap().selection.clone(); + assert!(before.segments.contains_key(&a) && !before.anchors.contains_key(&a)); + log(&mut s, "var p = app.activeDocument.pageItems; p[1].duplicate(); p[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.anchors.get(&a), ends.as_ref()); + assert_eq!(sel.segments.get(&a), before.segments.get(&a)); + assert_eq!(sel.objects, before.objects, "the path keeps its place in the selection"); +} + #[test] fn an_edit_keeps_the_order_of_a_mixed_selection() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 6101835982..7476a19751 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -301,8 +301,13 @@ fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() { let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}'); let db = vectorcraft_text::FontDb::global(); - let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c)); - if !covers(from) || covers(to) { + // Both faces ship in assets/fonts: with the bundled fonts the test fails when either one is + // missing, and without them it is skipped. A lookup that falls back to another face counts + // as missing. + let regular = |family: &str| db.face(family, "Regular").filter(|f| f.family == family && f.style == "Regular"); + let faces = regular(from).zip(regular(to)); + assert!(faces.is_some() || !cfg!(feature = "bundled-fonts"), "{from} Regular or {to} Regular is not available"); + if !faces.is_some_and(|(source, dest)| source.covers(c) && !dest.covers(c)) { return; // Installed fonts of these names cover other characters. } let mut s = Session::new(); @@ -500,6 +505,11 @@ fn collections_of_text_add_words_characters_and_paragraphs() { ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), + // A range of a frame that is gone stays stale rather than of the wrong type. + ( + "var o = app.activeDocument.textFrames[0].characters[0]; app.activeDocument.textFrames[0].remove(); t.words.add('x', o)", + "Stale text range", + ), ] { let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); assert!(e.contains(want), "{call}: {e}"); diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index bfb4de5eac..97b31bb8f1 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -113,7 +113,9 @@ fn chain(interp: &Interp, obj: ObjId) -> Vec<(ObjId, usize)> { impl Indices { fn new(interp: &mut Interp, obj: ObjId, lo: u64, hi: u64, ascending: bool, maps: Vec) -> JsResult { let mut it = Indices { obj, lo, hi, ascending, maps, sparse: None }; - if hi.saturating_sub(lo) > DENSE_SPAN { + // An object of a host class with an indexer can answer any index without holding a + // property for it, so its range is visited index by index. + if hi.saturating_sub(lo) > DENSE_SPAN && interp.host_indexer(obj)?.is_none() { let present: usize = chain(interp, obj).iter().map(|(_, n)| *n).fold(0, usize::saturating_add); if hi - lo > (present as u64).saturating_mul(8) { it.sparse = Some(it.gather(interp)?); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 8fb61c7d60..6205701370 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -1260,6 +1260,18 @@ mod tests { assert!(e.message.contains("is not a File or a Folder"), "{e:?}"); } + /// An answer that cannot be made into a value is thrown at the dialog's call, and the dialog + /// does not go on with it. + #[test] + fn an_answer_past_the_crossing_limits_is_thrown_at_the_dialog() { + let (mut r, _) = dialog_realm(); + r.set_data_limits(crate::DataLimits { depth: 8, bytes: 1_000, entries: 2 }); + r.start("var m; try { File.openDialog('Pick', '', true); m = 'went on'; } catch (e) { m = e.name; } m").unwrap(); + assert_eq!(until_wait(&mut r), None); + r.answer(Data::Array((0..5).map(|n| Data::String(format!("/f{n}"))).collect())).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("RangeError".into()))); + } + #[test] fn a_dialog_in_a_function_or_a_loop_resumes_where_it_was_called() { let (mut r, asked) = dialog_realm(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4e0275441a..61a31b33c6 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -240,6 +240,21 @@ impl Interp { Ok(()) } + /// The [`crate::host_ref`] of the object of a host class `id`, its class name and handle + /// charged to `r` as a string and an array of numbers are. + fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + // The charges come from the object itself, so a reference past the limits is not copied. + let (class, parts) = match &self.object(id)?.class { + Class::Host(h) => (self.host_class_name_len(h.class), h.handle.len()), + _ => return Err(Abrupt::Internal("host object without a class".into())), + }; + let key_bytes = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8); + let bytes = class.saturating_mul(3).saturating_add(2).saturating_add(parts.saturating_mul(8)).saturating_add(key_bytes); + self.charge_entries(r, parts.saturating_add(2))?; + self.charge_reading(r, bytes)?; + self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())) + } + fn read_data(&mut self, v: &Value, r: &mut Reading) -> JsResult { match v { Value::Undefined => Ok(Data::Undefined), @@ -266,7 +281,7 @@ impl Interp { } let shape = match &self.object(id)?.class { Class::Host(_) if r.hosted => { - return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); + return self.read_host_ref(id, r); } Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), @@ -342,12 +357,28 @@ impl Interp { Ok(Data::Object(out)) } - /// A host value as a JavaScript value, `frozen` when a script may not change it. A value - /// deeper or longer than the limits throws a `RangeError`. - pub(crate) fn write_data(&mut self, d: Data, depth: usize, frozen: bool) -> JsResult { + /// Throws the `RangeError` [`Self::write_data`] gives for a host value nested `depth` deep + /// when that is past the limit. + pub(crate) fn check_write_depth(&mut self, depth: usize) -> JsResult<()> { if depth > self.data_limits.depth { return Err(self.throw(ErrorType::Range, "a host value is nested too deep")); } + Ok(()) + } + + /// Throws the `RangeError` [`Self::write_data`] gives for an array or object of `entries` + /// entries when that is past the limit. + pub(crate) fn check_write_entries(&mut self, entries: usize) -> JsResult<()> { + if entries > self.data_limits.entries { + return Err(self.throw(ErrorType::Range, "a host value has too many entries")); + } + Ok(()) + } + + /// A host value as a JavaScript value, `frozen` when a script may not change it. A value + /// deeper or longer than the limits throws a `RangeError`. + pub(crate) fn write_data(&mut self, d: Data, depth: usize, frozen: bool) -> JsResult { + self.check_write_depth(depth)?; Ok(match d { Data::Undefined => Value::Undefined, Data::Null => Value::Null, @@ -370,9 +401,7 @@ impl Interp { } fn write_container(&mut self, items: Vec<(Slot, Data)>, array: bool, depth: usize, frozen: bool) -> JsResult { - if items.len() > self.data_limits.entries { - return Err(self.throw(ErrorType::Range, "a host value has too many entries")); - } + self.check_write_entries(items.len())?; let flags = if frozen { ENUMERABLE } else { crate::heap::OPEN }; self.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(items.len())))?; let id = if array { @@ -407,16 +436,9 @@ impl Interp { pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), - ArgRead::Hosted => { - let this = match this { - Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), - _ => Data::Undefined, - }; - let mut data = vec![this]; - data.extend(self.read_args(name, args, how)?); - data - } - _ => self.read_args(name, args, how)?, + // The receiver comes first, charged to the same limits as the arguments. + ArgRead::Hosted => self.read_args(name, args, how, Some(this))?, + _ => self.read_args(name, args, how, None)?, }; // Only the script's own code, in a run that can pause, can wait for a result, and a host // class's constructor called with `new` cannot. @@ -463,7 +485,7 @@ impl Interp { name: &Rc, args: &[Value], ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let data = self.read_args(name, args, &ArgRead::Data, None)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -505,8 +527,10 @@ impl Interp { r } - /// The arguments of host function `name` as [`Data`], read as `how` says. - fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { + /// The arguments of host function `name` as [`Data`], read as `how` says. With `this`, the + /// list starts with the receiver: its [`crate::host_ref`] when it is an object of a host class, + /// otherwise `undefined`. + fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead, this: Option<&Value>) -> JsResult> { let mut reading = Reading { limits: self.data_limits, bytes: 0, @@ -520,7 +544,14 @@ impl Interp { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, }; - let mut data = Vec::with_capacity(args.len()); + let mut data = Vec::with_capacity(args.len().saturating_add(1)); + if let Some(this) = this { + let receiver = match this { + Value::Object(o) if matches!(self.object(*o)?.class, Class::Host(_)) => self.read_host_ref(*o, &mut reading)?, + _ => Data::Undefined, + }; + data.push(receiver); + } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 4c5cda0a70..e8b24d072d 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -20,7 +20,7 @@ use std::rc::Rc; -use crate::heap::{Class, Func, ObjId, Object, Prop, key}; +use crate::heap::{Class, Func, Key, ObjId, Object, Prop, key}; use crate::host::ArgRead; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; use crate::value::Value; @@ -131,6 +131,12 @@ impl Interp { Ok(Some(host_ref(&name, &h.handle))) } + /// The length in UTF-16 units of the name of host class `class`, or 0 when there is no such + /// class. + pub(crate) fn host_class_name_len(&self, class: u32) -> usize { + self.host_classes.get(class as usize).map_or(0, |e| e.name.encode_utf16().count()) + } + /// The object of a host class that `d`, which a host function gave, stands for. pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { let Some((name, handle)) = host_ref_parts(d) else { @@ -178,10 +184,16 @@ impl Interp { /// `object[index]` of an object of a host class, which its class's indexer `f` answers. pub(crate) fn host_index(&mut self, f: &HostFunction, id: ObjId, index: u32) -> JsResult { + let d = self.host_index_data(f, id, index)?; + self.write_hosted(d) + } + + /// The indexer's answer for `index` as it gave it, before any object is made of it. + fn host_index_data(&mut self, f: &HostFunction, id: ObjId, index: u32) -> JsResult { self.use_fuel()?; - let Some(this) = self.host_ref_of(id)? else { return Ok(Value::Undefined) }; + let Some(this) = self.host_ref_of(id)? else { return Ok(Data::Undefined) }; match f(vec![this, Data::Number(f64::from(index))]) { - Ok(d) => self.write_hosted(d), + Ok(d) => Ok(d), Err(HostError::Wait) => Err(Abrupt::Internal("a host class's indexer waited for its result".into())), Err(e) => Err(self.host_error(e)?), } @@ -193,13 +205,38 @@ impl Interp { if let Some(i) = crate::value::array_index(k) && let Some(f) = self.host_indexer(id)? { - return Ok(!matches!(self.host_index(&f, id, i)?, Value::Undefined)); + // Only whether the answer is `undefined` counts, so no object is made of it. + return Ok(!matches!(self.host_index_data(&f, id, i)?, Data::Undefined)); } self.has_property(id, k) } /// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`]. pub(crate) fn write_hosted(&mut self, d: Data) -> JsResult { + // References and limits are checked before any objects are made. + let mut pending = vec![(&d, 0)]; + while let Some((item, depth)) = pending.pop() { + self.check_write_depth(depth)?; + match item { + Data::Object(items) if matches!(items.as_slice(), [(k, _)] if k == HOST_REF_KEY) => { + let Some((name, _)) = host_ref_parts(item) else { + return Err(self.throw(ErrorType::Type, "a host value names an object of a host class wrongly")); + }; + if !self.host_classes.iter().any(|e| &*e.name == name) { + return Err(self.throw(ErrorType::Type, &format!("a host value names the unknown class {name}"))); + } + } + Data::Object(items) => { + self.check_write_entries(items.len())?; + pending.extend(items.iter().rev().map(|(_, v)| (v, depth + 1))); + } + Data::Array(list) => { + self.check_write_entries(list.len())?; + pending.extend(list.iter().rev().map(|v| (v, depth + 1))); + } + _ => {} + } + } let was = std::mem::replace(&mut self.write_hosted, true); let r = self.write_data(d, 0, false); self.write_hosted = was; @@ -207,23 +244,158 @@ impl Interp { } } -/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. +/// Adds `classes` and the global objects `instances`, each made from the [`host_ref`] given. The +/// whole batch is checked and its heap reserved first; when a later step fails, the classes it +/// added are taken out again, each global it wrote gets its earlier property back in its place, +/// and each earlier object of a host class it made one of a new class gets its class back, so a +/// corrected batch can be given next. pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(String, Data)>) -> JsResult<()> { + check_batch(i, &classes, &instances)?; + let bytes = batch_bytes(i.object(i.global)?, &classes, &instances); + i.reserve_heap(bytes)?; + let count = i.host_classes.len(); + let made: Vec<(ObjId, u32, Option)> = i + .host_objects + .values() + .filter_map(|&id| match i.heap.object(id) { + Some(Object { class: Class::Host(h), proto, .. }) => Some((id, h.class, *proto)), + _ => None, + }) + .collect(); + let mut globals: Vec<(Key, Option)> = Vec::new(); + // The properties a batch replaces stay reachable until it is known whether they come back. + let mark = i.temp_roots.len(); + let r = install_all(i, classes, instances, &mut globals); + i.temp_roots.truncate(mark); + if r.is_err() { + i.host_classes.truncate(count); + let global = i.global; + if let Ok(o) = i.object_mut(global) { + for (k, before) in globals.into_iter().rev() { + match before { + Some(p) => { + if let Some(now) = o.props.get_mut(&k) { + *now = p; + } else { + o.props.insert(k, p); + } + } + None => { + o.props.remove(&k); + } + } + } + } + for (id, class, proto) in made { + if let Ok(o) = i.object_mut(id) + && let Class::Host(h) = &mut o.class + { + h.class = class; + o.proto = proto; + } + } + let heap = &i.heap; + i.host_objects.retain(|_, id| matches!(heap.object(*id).map(|o| &o.class), Some(Class::Host(h)) if (h.class as usize) < count)); + } + r +} + +/// The global property `name` as it is before the batch writes it, its values kept reachable. +fn global_before(i: &mut Interp, name: &str) -> JsResult<(Key, Option)> { + let k = key(name); + let before = i.object(i.global)?.props.get(&k).cloned(); + match &before { + Some(Prop::Data { value, .. }) => i.temp_roots.push(value.clone()), + Some(Prop::Accessor { get, set, .. }) => i.temp_roots.extend(get.iter().chain(set.iter()).map(|f| Value::Object(*f))), + _ => {} + } + Ok((k, before)) +} + +fn install_all(i: &mut Interp, classes: Vec, instances: Vec<(String, Data)>, globals: &mut Vec<(Key, Option)>) -> JsResult<()> { for class in classes { + globals.push(global_before(i, &class.name)?); install_class(i, class)?; } for (name, d) in instances { let v = i.write_hosted(d)?; + let mark = i.temp_roots.len(); + i.temp_roots.push(v.clone()); + // The value is made and must fit, and so must its global property when the name is new. + let bytes = if i.object(i.global)?.props.contains(&key(&name)) { 0 } else { prop_bytes(&name) }; + let room = i.reserve_heap(bytes); + i.temp_roots.truncate(mark); + room?; + globals.push(global_before(i, &name)?); let global = i.global; i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?; } Ok(()) } -fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { - if i.host_classes.iter().any(|e| *e.name == *class.name) { - return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); +/// The heap bytes of a property named `name`. +fn prop_bytes(name: &str) -> usize { + crate::heap::PROP_BYTES.saturating_add(crate::heap::string_bytes(name.encode_utf16().count())) +} + +/// Throws the error the first part of a batch that cannot be added gives: a class name defined +/// before or twice in the batch, a parent defined neither before nor earlier in the batch, or an +/// instance that names a class defined neither before nor in the batch. An instance that cannot +/// fail then does not change an object of an earlier batch's family before a later one fails. +fn check_batch(i: &mut Interp, classes: &[HostClass], instances: &[(String, Data)]) -> JsResult<()> { + let mut names: Vec<&str> = Vec::new(); + let known: Vec = i.host_classes.iter().map(|e| e.name.to_string()).collect(); + for class in classes { + if known.contains(&class.name) || names.contains(&class.name.as_str()) { + return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); + } + if let Some(p) = &class.parent + && !known.contains(p) + && !names.contains(&p.as_str()) + { + return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))); + } + names.push(&class.name); } + for (_, d) in instances { + if let Some((class, _)) = host_ref_parts(d) + && !known.iter().any(|k| k == class) + && !names.contains(&class) + { + return Err(i.throw(ErrorType::Type, &format!("a host value names the unknown class {class}"))); + } + } + Ok(()) +} + +/// The heap bytes the classes of a batch and the global properties of its instances take: each +/// class's prototype and constructor, their properties, its member functions and its global. +fn batch_bytes(global: &Object, classes: &[HostClass], instances: &[(String, Data)]) -> usize { + use crate::heap::{OBJECT_BYTES, PROP_BYTES, string_bytes}; + let prop = |name: &str| PROP_BYTES.saturating_add(string_bytes(name.encode_utf16().count())); + let mut names = std::collections::HashSet::new(); + let mut global_prop = |name: &str| { + if global.props.contains(&key(name)) || !names.insert(name.to_string()) { 0 } else { prop(name) } + }; + let classes = classes.iter().fold(0usize, |sum, c| { + // A prototype property key is charged once: a repeated member name, or one named + // `constructor`, replaces the property and only its functions take more heap. + let mut keys = std::collections::HashSet::from(["constructor"]); + let members = c.members.iter().fold(0usize, |m, (name, member)| { + let functions = if matches!(member, HostMember::Property { .. }) { 2 } else { 1 }; + let key = if keys.insert(name.as_str()) { prop(name) } else { 0 }; + m.saturating_add(key).saturating_add(OBJECT_BYTES.saturating_mul(functions)) + }); + sum.saturating_add(OBJECT_BYTES.saturating_mul(2)) + .saturating_add(prop("prototype")) + .saturating_add(prop("constructor")) + .saturating_add(global_prop(&c.name)) + .saturating_add(members) + }); + instances.iter().fold(classes, |sum, (name, _)| sum.saturating_add(global_prop(name))) +} + +fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); let (parent, family) = match &class.parent { None => (i.intrinsics.object_proto, own), diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index b697a02f0d..587ed04789 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -700,6 +700,211 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); } +/// An answer that names an unknown class throws its `TypeError` at the waiting call, where the +/// script catches it. +#[test] +fn an_answer_naming_an_unknown_class_is_thrown_at_the_waiting_call() { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + r.start("var m; try { thing.fetch(); m = 'none'; } catch (e) { m = e.name; } m").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.answer(host_ref("Nope", &[2.0])).unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("TypeError".into())); +} + +#[test] +fn a_refused_answer_keeps_an_existing_objects_class() { + for (bad, error) in [ + (host_ref("Nope", &[2.0]), "TypeError"), + (Data::Object(vec![(HOST_REF_KEY.into(), Data::Null)]), "TypeError"), + (Data::Array(vec![Data::Null]), "RangeError"), + (Data::Object(vec![("a".into(), Data::Null), ("b".into(), Data::Null), ("c".into(), Data::Null)]), "RangeError"), + ] { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + r.define_host_classes(vec![bare_class("Sub", Some("Thing"))], Vec::new()).unwrap(); + r.start("var m; try { thing.fetch(); } catch (e) { m = e.name; } [m, Object.getPrototypeOf(thing) === Thing.prototype].join()").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.set_data_limits(DataLimits { depth: 1, bytes: 1_000, entries: 2 }); + r.answer(Data::Array(vec![host_ref("Sub", &[1.0]), bad])).unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String(format!("{error},true"))); + } +} + +#[test] +fn hosted_answers_check_limits_and_references_in_write_order() { + for (answer, message) in [ + (Data::Array(vec![host_ref("Nope", &[2.0]), Data::Null, Data::Null]), "a host value has too many entries"), + (Data::Array(vec![Data::Array(vec![host_ref("Nope", &[2.0])])]), "a host value is nested too deep"), + (Data::Array(vec![host_ref("First", &[]), host_ref("Last", &[])]), "a host value names the unknown class First"), + (Data::Object(vec![("a".into(), host_ref("First", &[])), ("b".into(), host_ref("Last", &[]))]), "a host value names the unknown class First"), + ] { + let mut r = realm(1_000_000); + with_thing(&mut r, None); + r.start("var m; try { thing.fetch(); } catch (e) { m = e.message; } m").unwrap(); + assert_eq!(r.advance(1_000).unwrap(), Progress::Paused); + assert!(r.waits()); + r.set_data_limits(DataLimits { depth: 1, bytes: 1_000, entries: 2 }); + r.answer(answer).unwrap(); + assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String(message.into())); + } +} + +/// `i in` an object of a host class reads only whether the indexer gives `undefined`: it makes no +/// object of the value, so a value that `object[i]` refuses still counts as an entry. +#[test] +fn in_on_an_object_of_a_host_class_does_not_make_the_indexed_value() { + let mut r = realm(1_000_000); + let index: HostFunction = Rc::new(|a| Ok(if a.get(1) == Some(&Data::Number(0.0)) { host_ref("Nope", &[1.0]) } else { Data::Undefined })); + let class = HostClass { name: "List".into(), parent: None, members: Vec::new(), index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("list".into(), host_ref("List", &[1.0]))]).unwrap(); + let out = r.run("var m = ''; try { list[0]; } catch (e) { m = e.name; } [0 in list, 1 in list, m].join()").unwrap(); + assert_eq!(out, JsValue::String("true,false,TypeError".into())); +} + +/// The array methods visit every index an indexer answers, also over a range too long to visit +/// index by index for an ordinary object that holds few properties. +#[test] +fn array_methods_visit_every_index_a_host_indexer_gives() { + let mut r = realm(50_000_000); + let index: HostFunction = Rc::new(|a| { + Ok(match a.get(1) { + Some(Data::Number(n)) if *n < 10_000.0 => Data::Number(*n), + _ => Data::Undefined, + }) + }); + let length: HostFunction = Rc::new(|_| Ok(Data::Number(10_000.0))); + let members = vec![("length".to_string(), HostMember::Get(length))]; + let class = HostClass { name: "List".into(), parent: None, members, index: Some(index), construct: None }; + r.define_host_classes(vec![class], vec![("list".into(), host_ref("List", &[1.0]))]).unwrap(); + let out = r.run("var a = Array.prototype.slice.call(list, 0); [a.length, a[0], a[9999], 5000 in a].join()").unwrap(); + assert_eq!(out, JsValue::String("10000,0,9999,true".into())); +} + +fn bare_class(name: &str, parent: Option<&str>) -> HostClass { + HostClass { name: name.into(), parent: parent.map(Into::into), members: Vec::new(), index: None, construct: None } +} + +/// A batch of host classes that fails leaves none of its classes or globals behind, so the +/// corrected batch installs. +#[test] +fn a_refused_batch_of_host_classes_leaves_nothing_installed() { + let mut r = realm(1_000_000); + assert!(r.define_host_classes(vec![bare_class("Base", None), bare_class("Child", Some("Missing"))], Vec::new()).is_err()); + // The instance names an unknown class after the classes were made. + assert!(r.define_host_classes(vec![bare_class("Base", None)], vec![("b".into(), host_ref("Nope", &[1.0]))]).is_err()); + r.define_host_classes(vec![bare_class("Base", None), bare_class("Child", Some("Base"))], vec![("c".into(), host_ref("Child", &[1.0]))]).unwrap(); + assert_eq!(r.run("[typeof b, c instanceof Base].join()").unwrap(), JsValue::String("undefined,true".into())); +} + +/// A batch that fails after writing a global gives the global its earlier value back. +#[test] +fn a_refused_batch_of_host_classes_keeps_the_globals_it_wrote() { + let mut r = realm(1_000_000); + r.run("var x = 7; var z = 1;").unwrap(); + let instances = vec![("x".into(), host_ref("Base", &[1.0])), ("y".into(), Data::Array(vec![host_ref("Nope", &[1.0])]))]; + assert!(r.define_host_classes(vec![bare_class("Base", None)], instances).is_err()); + let out = r.run("var k = Object.keys(this); [x, typeof y, typeof Base, k.indexOf('x') < k.indexOf('z')].join()").unwrap(); + assert_eq!(out, JsValue::String("7,undefined,undefined,true".into())); +} + +/// An object of an earlier batch that a refused batch made one of its new class keeps its class. +#[test] +fn a_refused_batch_of_host_classes_gives_earlier_objects_their_class_back() { + let mut r = realm(1_000_000); + r.define_host_classes(vec![bare_class("Base", None)], vec![("a".into(), host_ref("Base", &[1.0]))]).unwrap(); + let instances = vec![("s".into(), host_ref("Sub", &[1.0])), ("bad".into(), Data::Array(vec![host_ref("Nope", &[1.0])]))]; + assert!(r.define_host_classes(vec![bare_class("Sub", Some("Base"))], instances).is_err()); + assert_eq!(r.run("Object.getPrototypeOf(a) === Base.prototype").unwrap(), JsValue::Bool(true)); +} + +#[test] +fn a_batch_of_host_classes_reserves_only_new_global_names() { + let mut probe = realm(1_000_000); + let before = probe.interp().settled_heap_bytes(); + probe.define_host_classes(vec![bare_class("Probe", None)], Vec::new()).unwrap(); + let class_bytes = probe.interp().settled_heap_bytes() - before; + let prop_bytes = |name: &str| crate::heap::PROP_BYTES + crate::heap::string_bytes(name.encode_utf16().count()); + for existing in [false, true] { + let mut r = realm(1_000_000); + if existing { + r.define_host_classes(Vec::new(), vec![("Probe".into(), Data::Null), ("slot".into(), Data::Null)]).unwrap(); + } + let interp = r.interp(); + interp.collect_garbage(); + let room = if existing { class_bytes - prop_bytes("Probe") } else { class_bytes + prop_bytes("slot") }; + interp.limits.heap_bytes = interp.heap.bytes + room; + let instances = vec![("Probe".into(), Data::Number(1.0)), ("slot".into(), Data::Number(2.0)), ("slot".into(), Data::Number(3.0))]; + r.define_host_classes(vec![bare_class("Probe", None)], instances).unwrap(); + r.set_limits(Limits::default()); + assert_eq!(r.run("[Probe, slot].join()").unwrap(), JsValue::String("1,3".into())); + } +} + +/// A batch of host classes whose definitions do not fit in the heap is refused with the heap +/// limit, and none of it is installed. +#[test] +fn a_batch_of_host_classes_past_the_heap_limit_is_refused_whole() { + let mut r = small_heap_realm(); + let f: HostFunction = Rc::new(|_| Ok(Data::Null)); + let members = (0..20_000).map(|n| (format!("m{n}"), HostMember::Method(f.clone()))).collect(); + let big = HostClass { name: "Big".into(), parent: None, members, index: None, construct: None }; + match r.define_host_classes(vec![big], Vec::new()) { + Err(RunError { kind: RunErrorKind::Limit(k), .. }) => assert_eq!(k, LimitKind::Heap), + other => panic!("{other:?}"), + } + assert_eq!(r.run("typeof Big").unwrap(), JsValue::String("undefined".into())); +} + +/// The receiver and the arguments that are objects of host classes count toward the limits on +/// what crosses to the host; short references pass. +#[test] +fn host_references_count_toward_the_crossing_limits() { + let mut r = realm(1_000_000); + r.set_data_limits(DataLimits { depth: 8, bytes: 1_000, entries: 100 }); + let count: HostFunction = Rc::new(|a| Ok(Data::Number(f64::from(u32::try_from(a.len()).unwrap_or(0))))); + let class = HostClass { + name: "Thing".into(), + parent: None, + members: vec![("count".to_string(), HostMember::Method(count))], + index: None, + construct: None, + }; + let instances = vec![("short".into(), host_ref("Thing", &[1.0])), ("long".into(), host_ref("Thing", &[1.0; 500]))]; + r.define_host_classes(vec![class], instances).unwrap(); + let out = r + .run( + "function m(f) { try { return f(); } catch (e) { return e.name; } }\ + [m(function () { return short.count(short); }), m(function () { return long.count(); }),\ + m(function () { return short.count(long); })].join()", + ) + .unwrap(); + assert_eq!(out, JsValue::String("2,RangeError,RangeError".into())); +} + +#[test] +fn host_reference_wrappers_count_toward_the_crossing_limits() { + let mut r = realm(1_000_000); + let count: HostFunction = Rc::new(|_| Ok(Data::Bool(true))); + let class = HostClass { + name: "Thing".into(), + parent: None, + members: vec![("count".to_string(), HostMember::Method(count))], + index: None, + construct: None, + }; + r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); + for (bytes, entries, fits) in [(1_000, 2, false), (1_000, 3, true), (56, 100, false), (57, 100, true)] { + r.set_data_limits(DataLimits { depth: 8, bytes, entries }); + for call in ["thing.count()", "thing.count.call(null, thing)"] { + let out = r.run(&format!("try {{ {call}; }} catch (e) {{ e.name; }}")).unwrap(); + assert_eq!(out, if fits { JsValue::Bool(true) } else { JsValue::String("RangeError".into()) }); + } + } +} + /// The handles of the objects of a host class count toward the heap limit. #[test] fn host_class_handles_count_toward_the_heap_limit() { diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 2514722ab6..ae4deff373 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -973,7 +973,7 @@ impl Interp { /// Finds the handler for an exception: in the top frame, or in the frames below it up to the /// boundary frame. Returns the exception when no handler takes it before the boundary frame. - fn unwind(&mut self, v: Value) -> JsResult<()> { + pub(crate) fn unwind(&mut self, v: Value) -> JsResult<()> { self.note_site(); let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); if !passed diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 99abaa6c7a..523fa68451 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -450,10 +450,21 @@ impl Realm { let hosted = std::mem::take(&mut interp.waiting_hosted); // The value on top of the stack stood in for the result. let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) }; - let r = written.and_then(|v| { - interp.stack.pop(); - interp.push(v) - }); + let r = match written { + Ok(v) => { + interp.stack.pop(); + interp.push(v) + } + // An exception from making the answer, such as a reference to an unknown class, is + // thrown at the waiting call, where the script can catch it. A built-in that made the + // call does not go on with it. + Err(Abrupt::Throw(v)) => { + interp.resuming = None; + interp.stack.pop(); + interp.unwind(v) + } + Err(e) => Err(e), + }; match r { Ok(()) => Ok(()), Err(e) => self.outcome(Err(e)).map(drop), diff --git a/docs/mcp.md b/docs/mcp.md index c3c9fb5624..34feafba0b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2699,9 +2699,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when - the preset it is given holds one of them with a value other than `null`, and makes no document. A - `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a - `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + the preset it is given holds one of them with a value other than `null`, and makes no document. An omitted or + `null` `presetSettings` uses the startup preset as it is; a `presetSettings` that is not a `DocumentPreset` (a + plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it that cannot be used, for example) goes to the Script Console as a line `addDocument: `. A `previewMode` of @@ -2724,7 +2724,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's, a - group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE` + group's or a compound path's contents, `PLACEATEND` under them (in a clip group or a clipped layer, directly + above the clipping path; a compound path takes only paths), `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. 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 @@ -2774,7 +2775,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`, `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run - `layer.setProps`, and `opacity` runs `object.setProps`. `move` and `zOrder` run `node.move`; a layer goes into + `layer.setProps`, and `opacity` runs `object.setProps`. `opacity` reads rounded to 4 decimals; assigning the number it + reads, or one that stores as the same opacity, runs no command. `move` and `zOrder` run `node.move`; a layer goes into another layer, to the top level of the document, or directly above or below another layer. Every page item has `layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has `clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem` diff --git a/docs/roadmap.md b/docs/roadmap.md index a2a446a76a..49ec063e59 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -198,7 +198,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) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, and its text frames with their text ranges and the fonts; path properties, views, stories, text styles, the other classes of the script document model and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, and its text frames with their text ranges and the fonts; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; path properties, views, stories, text styles, the other classes of the script document model and batch work remain | 18–27 | | M14 | 1.0 polish (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) | 🟡 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), 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 b893fce7016226b4cc3994775d8193a8193d7e64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 23:08:04 -0800 Subject: [PATCH 14/28] Scripts: emptying a path keeps an unrelated selection, and point removal keeps the layer Writing a path's points removes it from the selection only when it, its anchors or its segments are selected, so emptying an unselected path keeps a targeted layer. Removing a point that changes the selection puts back the current layer and the highlighted Layers rows. The New Document test reads fractional rows as rounded, as file.new does. --- crates/engine/src/script/dom/paths.rs | 4 +++- crates/engine/src/tests/script_dom_paths.rs | 10 ++++++++++ crates/ui-egui/src/dialogs/new_document.rs | 4 +--- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index a37ed8b71b..7785dc25a8 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -357,7 +357,9 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) { selection.key_anchor = None; } - if selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty()) { + if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id)) + && (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty())) + { selection.remove(item.id); } } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 9efa282707..93f2aaadf9 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -518,6 +518,16 @@ fn removing_the_last_selected_point_of_a_path_keeps_the_current_layer() { assert_eq!(st.highlighted_rows(), rows); } +#[test] +fn emptying_an_unselected_path_keeps_the_targeted_layer() { + let (mut s, a, _) = doc(); + let layer = NodeId(s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert!(!s.active().unwrap().selection.contains(a)); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints.removeAll();"); + assert_eq!(s.active().unwrap().selection.target, Some(layer)); +} + #[test] fn point_selection_reads_flush_removed_closing_segments() { for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] { diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 8f18b7fb46..c20582141e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -1293,9 +1293,7 @@ mod tests { let mut app = app(); open(&mut app); set(&app, "artboards", json!(5)).unwrap(); - // Rows that are not a whole number are refused, as `file.new` refuses them. - assert!(set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).is_err()); - set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4, "spacing": 10})).unwrap(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 3.6, "spacing": 10})).unwrap(); assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); create(&mut app); let st = app.session.active().unwrap(); From 2821f7d2b948ec02381653fa7068d1a692479d06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 09:50:18 -0800 Subject: [PATCH 15/28] Scripts: fix review points on layers and artboards - hasSelectedArtwork = true on a layer with nothing to add runs no command even when the selection already holds more than 10,000 objects; a layer whose art would take the selection past the limit still throws a RangeError. - artboards.insert() returns undefined. - Reflection gives Artboards.index an Artboard result and any key, and PageItems.parent any type, since layers, groups and compound paths have their own collections. - The node.move test now requires the move of a clipping path to its own place to succeed, and the opacity test changes the item whose opacity it set. - docs/mcp.md and the M13 roadmap line describe the changes and list Document.pathItems as available. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/layers.rs | 19 +++++++------ crates/engine/src/tests/layers.rs | 2 +- crates/engine/src/tests/script_dom.rs | 39 ++++++++++++++++++++++++-- docs/mcp.md | 5 ++-- docs/roadmap.md | 2 +- 6 files changed, 53 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b12813c3cb..9a80fc30ea 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -3021,7 +3021,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 c23894ce2b..f5b2810ad9 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -327,23 +327,23 @@ fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer { let mut have: std::collections::HashSet = selected.iter().copied().collect(); let mut ids = Vec::new(); for o in art { - if selected.len() + ids.len() > MAX_LISTED { - break; - } if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) { have.insert(o); ids.push(o); + if selected.len() + ids.len() > MAX_LISTED { + break; + } } } let total = selected.len() + ids.len(); (ids, total) }); - if total > MAX_LISTED { - return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); - } if ids.is_empty() { return Ok(Data::Undefined); } + if total > MAX_LISTED { + return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))); + } let command_id = if on { "select.add" } else { "select.toggle" }; on_doc(h, doc.uid, false, |h| command(h, command_id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; Ok(Data::Undefined) @@ -1340,12 +1340,13 @@ fn boards_add(h: &Host, a: &[Data]) -> Answer { add_board(h, a, None) } -/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. +/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → `undefined`. fn boards_insert(h: &Host, a: &[Data]) -> Answer { if matches!(arg(a, 2), Data::Undefined) { return Err(HostError::Type("insert needs an index".into())); } - add_board(h, a, Some(arg(a, 2))) + add_board(h, a, Some(arg(a, 2)))?; + Ok(Data::Undefined) } fn boards_remove(h: &Host, a: &[Data]) -> Answer { @@ -1505,7 +1506,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("typename", get(l, boards_typename), typed("string")), ("length", get(l, boards_length), typed("number")), ("parent", get(l, boards_parent), typed("Document")), - ("index", method(l, boards_index), returns("number", &[("itemKey", "Artboard")])), + ("index", method(l, boards_index), returns("Artboard", &[("itemKey", "*")])), ("getByName", method(l, boards_by_name), returns("Artboard", &[("name", "string")])), ("add", method(l, boards_add), returns("Artboard", &[("artboardRect", "Array")])), ("insert", method(l, boards_insert), returns("undefined", &[("artboardRect", "Array"), ("index", "number")])), diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index ec52627e32..b105a3fd90 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -1036,7 +1036,7 @@ fn node_move_keeps_a_clip_groups_clipping_path_at_the_bottom() { assert!(err.contains("clipping path stays at the bottom"), "{p}: {err}"); assert_eq!(children(&s, g), before, "{p}"); } - let _ = s.execute("node.move", &json!({"id": mask.0, "parent": g.0, "index": 0})); + run(&mut s, "node.move", json!({"id": mask.0, "parent": g.0, "index": 0})); assert_eq!(children(&s, g), before, "the clipping path stays where it is"); let d = rect(&mut s, 90.0); run(&mut s, "node.move", json!({"id": d.0, "parent": g.0, "index": 0})); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 1ace4c6464..22c4bb6840 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -598,7 +598,7 @@ fn blending_mode_reads_and_sets_the_objects_blend_mode() { fn an_opacity_close_to_the_current_one_is_set() { let (mut s, a, _) = doc(); s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); - let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.opacity = 50.00009; vc.log(i.opacity);"); + let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.opacity = 50.00009; vc.log(i.opacity);"); assert_eq!(out, vec![json!(50.0001)]); } @@ -2898,7 +2898,7 @@ fn new_artboards_get_a_name_no_other_artboard_has() { let out = log( &mut s, "var A = app.activeDocument.artboards; A[0].name = 'Artboard 2';\ - vc.log(A.add([500, 300, 700, 100]).name); vc.log(A.insert([0, -100, 100, -200], 0).name);\ + vc.log(A.add([500, 300, 700, 100]).name); A.insert([0, -100, 100, -200], 0); vc.log(A[0].name);\ vc.log(A.add([800, 300, 900, 100]).name);", ); assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]); @@ -3077,6 +3077,41 @@ fn has_selected_artwork_keeps_the_rest_of_the_selection() { assert_eq!(sel.guides.len(), 1); } +#[test] +fn has_selected_artwork_on_an_empty_layer_passes_a_full_selection() { + let (mut s, a, _) = doc(); + let n = crate::script::dom::MAX_LISTED; + // Each Duplicate of everything doubles the objects. + s.execute("select.all", &json!({})).unwrap(); + for _ in 0..n.ilog2() { + s.execute("edit.duplicate", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + } + assert!(s.active().unwrap().selection.objects.len() > n); + // The empty layer adds nothing, so the selection's size does not matter. + run(&mut s, "app.activeDocument.layers.add().hasSelectedArtwork = true;").unwrap(); + // A layer with an unselected object would take the selection past the limit. + s.execute("select.toggle", &json!({"ids": [a.0]})).unwrap(); + assert!(s.active().unwrap().selection.objects.len() > n); + let steps = undo_steps(&s); + assert!(failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;").contains("at most")); + assert!(!s.active().unwrap().selection.objects.contains(&a)); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn artboards_insert_gives_undefined_and_index_reflects_an_artboard() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var A = app.activeDocument.artboards; vc.log(typeof A.insert([500, 300, 700, 100], 0));\ + function info(o, n) { var m = o.reflect.methods; for (var i = 0; i < m.length; i++) if (m[i].name == n) return m[i].dataType + ':' + m[i].arguments[0].dataType; }\ + function prop(o, n) { var m = o.reflect.properties; for (var i = 0; i < m.length; i++) if (m[i].name == n) return m[i].dataType; }\ + vc.log(info(A, 'index')); vc.log(prop(app.activeDocument.pageItems, 'parent'));", + ); + assert_eq!(out, [json!("undefined"), json!("Artboard:*"), json!("*")]); +} + #[test] fn artboards_stop_at_one_hundred() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 3085164cba..616dd441c9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3119,7 +3119,7 @@ through `$`: `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. `clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/) has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new`), - `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`), `remove(index)` (runs + `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, and returns `undefined`), `remove(index)` (runs `artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`, `rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its @@ -3136,7 +3136,8 @@ through `$`: the next layer beside it and any art between them. `hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection (`select.add`), and `false` deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer - with nothing to add or deselect runs no command. + with nothing to add or deselect runs no command, whatever the size of the selection; adding art that takes the + selection past 10,000 objects throws a `RangeError`. `clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the layer's or group's contents, or of the current layer's for the document's collection, and `compoundPathItems.add()` diff --git a/docs/roadmap.md b/docs/roadmap.md index 683387321d..4752e558d2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -206,7 +206,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the rest of the script document model (paths, text lines 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 paths (`Document.pathItems` makes and edits them), its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the rest of the script document model (the `pathItems` of layers and groups, text lines 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) | 🟡 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 39a0fd69236dc6ee77b91666d4ef4c819539e676 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 12:01:00 -0800 Subject: [PATCH 16/28] Scripts: objectOnly paint, empty closed paths and style applyTo keep their rules - An objectOnly paint during an open interaction also restores the paint waiting for the commit, so it no longer reaches Recent Colors. - setEntirePath([]) on a closed path keeps an empty closed subpath, so the path stays closed. - A character or paragraph style's applyTo throws Cannot edit, with nothing changed, on a hidden or locked text frame or one on a locked artboard, as other text edits do. --- crates/engine/src/cmd/paint.rs | 4 ++-- crates/engine/src/script/dom/paths.rs | 2 +- crates/engine/src/script/dom/text/styles.rs | 4 +++- crates/engine/src/tests/editcolors.rs | 15 +++++++++++++++ crates/engine/src/tests/script_dom_paths.rs | 2 +- crates/engine/src/tests/script_text.rs | 3 +++ docs/mcp.md | 3 ++- 7 files changed, 27 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 726aada285..26951ce41c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -955,9 +955,9 @@ pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnc if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) { return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly")); } - let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone()); + let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone(), s.pending_paint.clone()); let result = run(s); - (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept; + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors, s.pending_paint) = kept; if result.is_ok() { s.note_defaults_only(); } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 7785dc25a8..5d2cfdd52f 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -857,7 +857,7 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { let c = h.dom.coords.get(); let anchors: Vec = script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?; - let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; + let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; cut_points(h, item); Ok(Data::Undefined) diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index e9121eee6b..45d1a428f3 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -342,7 +342,8 @@ fn target_span(h: &Host, d: &Data) -> std::result::Result { span_of(h, d, &TEXT) } -/// `applyTo(textItem, clearingOverrides?)`. +/// `applyTo(textItem, clearingOverrides?)`. Throws `Cannot edit`, with nothing changed, when the +/// text frame is protected as for any other text edit. fn style_apply_to(h: &Host, a: &[Data]) -> Answer { let style = this_style(h, a)?; let target = target_span(h, arg(a, 1))?; @@ -355,6 +356,7 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error("the text is in another document than the style".into())); } let (index, s, e, _) = resolve(h, target)?; + super::refuse_protected(h, target.item, "TextFrame")?; h.charge_call(16 + (e - s) as u64)?; let (start, end) = if style.para { let (_, ba, bb) = para_range(&index, s, e); diff --git a/crates/engine/src/tests/editcolors.rs b/crates/engine/src/tests/editcolors.rs index a42f2c4ca7..1539ece240 100644 --- a/crates/engine/src/tests/editcolors.rs +++ b/crates/engine/src/tests/editcolors.rs @@ -70,6 +70,21 @@ fn balance_previews_and_commits_one_step() { assert_eq!(fill_of(&s, a).to_hex(), "#808080"); } +/// An `objectOnly` paint during an open interaction keeps the remembered colors: the paint it would +/// leave waiting for the commit is not added to Recent Colors when the interaction commits. +#[test] +fn object_only_paint_in_an_interaction_keeps_recent_colors() { + let mut s = session(); + let a = rect(&mut s, json!("#808080")); + s.recent_colors.clear(); + let recent = (s.recent_colors.clone(), s.last_solid); + s.begin_interaction("Adjust Colors").unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000", "objectOnly": true})).unwrap(); + assert_eq!(fill_of(&s, a).to_hex(), "#ff0000"); + s.commit_interaction().unwrap(); + assert_eq!((s.recent_colors.clone(), s.last_solid), recent, "the recent colors are as they were"); +} + /// Saturate needs its intensity: a call without one, or with one that is not a number, is an error /// that changes nothing and records no undo step. A number outside −100..100 counts as its nearest end. #[test] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 93f2aaadf9..c0beeeb0a4 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -124,7 +124,7 @@ fn mixed_anchor_and_segment_picks_keep_independent_anchors() { #[test] fn an_empty_path_keeps_closed_before_points_are_added() { - for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);"] { + for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);", "p.setEntirePath([]);"] { let (mut s, _, _) = doc(); let start = s.journal.len(); let out = log( diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a18184d7ce..af5bc55ea0 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -348,6 +348,9 @@ fn hidden_or_locked_type_is_not_edited() { "r.contents = 'xyz';", "r.characters.add('!');", "r.justification = Justification.CENTER;", + "var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(r);", + "var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(t);", + "var c = app.activeDocument.paragraphStyles.add('C'); c.paragraphAttributes.justification = Justification.CENTER; c.applyTo(r);", ] { // Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden. let (mut s, id) = doc_with("abc"); diff --git a/docs/mcp.md b/docs/mcp.md index 555e456e3b..49d76671f4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3292,7 +3292,8 @@ through `$`: style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the style's document; a character style on an empty range inside text changes nothing, on empty text it styles the text typed or set later, and a paragraph style styles every paragraph the text touches. `clearingOverrides` left - out is false. A range lists each style once, in the order + out is false. `applyTo` on a frame that is hidden or locked, in a hidden or locked layer or group, or on a locked + artboard throws `Cannot edit` with nothing changed. A range lists each style once, in the order its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws From 5ad69e554aaeca5991c395a5e89389b2a9edcb5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 13:15:38 -0800 Subject: [PATCH 17/28] Scripts: fix stale index, clip mask moves, removeAll masks and active artboard - A stale layer or group collection throws its stale error from index(n) for any number, a negative one included, instead of Not found. - Moving a clipping path directly below the object above it is a no-op instead of throwing "an object cannot go below a clipping mask". - A clip group's removeAll() that deletes every object in it also releases the mask in the same undo step, so a later groupItems.add() is not made the clipping path. groupItems.removeAll() that leaves the clipping path keeps the mask. - setActiveArtboardIndex stores the chosen artboard on every call, so an artboard inserted before the default active one leaves it active, and a document the run opened is listed in the report. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 12 ++--- crates/engine/src/script/dom/layers.rs | 43 +++++++++++++++-- crates/engine/src/tests/script_dom.rs | 67 ++++++++++++++++++++++++++ docs/mcp.md | 14 ++++-- 4 files changed, 120 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d3dcb9c7a4..5a2ed9aadd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2239,10 +2239,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), // A number is a position only; a scoped list answers its own positions. - Data::Number(n) if layers::is_scoped(a) => match position(*n).map(|_| layers::scoped_at(h, a)).transpose()? { - None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())), - Some(d) => Ok(d), - }, + Data::Number(_) if layers::is_scoped(a) => layers::scoped_index(h, a), Data::Number(n) => { let doc = items_doc(h, a)?; match position(*n).map(|i| item_at(h, doc, i)).transpose()? { @@ -2808,6 +2805,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let from = d.position(id); let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + // The clipping path itself, put back where it is, stays the clipping path. + let mask_stays = from.is_some_and(|(p, j, _)| p == Some(to.parent) && j == 0); let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -2822,14 +2821,15 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let at = if how == Placement::Above { i + 1 } else { i }; // A place behind a clipping path is refused; an object put into the clip group // itself goes directly above the clipping path. - if clips && at == 0 { + if clips && at == 0 && !mask_stays { return Err(HostError::Error("an object cannot go below a clipping mask".into())); } at } (_, None) => count, }; - Ok::<_, HostError>(if clips { at.max(1) } else { at }) + let stays = mask_stays && at == 0 && to.how != Placement::Bottom; + Ok::<_, HostError>(if clips && !stays { at.max(1) } else { at }) })?; let now = with_doc(h, doc, |_, st| st.doc.position(id)); if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) { diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 02926e1317..739fe441b3 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -741,8 +741,11 @@ fn art_named(h: &Host, doc: Doc, c: Option, kind: Kind, name: &str) -> A fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer { match arg(a, 1) { Data::String(_) => art_by_name(h, a, kind), - // A number is a position only. - Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => Err(HostError::Error(NOT_FOUND.into())), + // A number is a position only. A stale collection throws its stale error first. + Data::Number(n) if whole(*n).is_none_or(|i| i >= u64::from(u32::MAX)) => { + art_scope(h, arg(a, 0), kind.class())?; + 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), @@ -780,7 +783,27 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { if !ids.is_empty() { // The container stays, empty, as a compound path whose last path `remove()` takes out does. 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))?; + // An emptied clipping group releases its mask, so an object added to it later is not + // made its clipping path. + // Only a deletion that takes every object of the group, its clipping path included, does. + let clipped = c.filter(|c| { + with_doc(h, doc, |_, st| { + st.doc.node(*c).is_some_and(|n| { + matches!(n.kind, NodeKind::Group { .. }) + && n.clips() + && n.children().is_some_and(|k| { + let gone: std::collections::HashSet = ids.iter().copied().collect(); + k.iter().all(|k| gone.contains(&k.id)) + }) + }) + }) + }); + on_doc(h, doc.uid, true, |h| { + if let Some(g) = clipped { + command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?; + } + command(h, "edit.clear", ¶ms) + })?; } Ok(Data::Undefined) } @@ -799,6 +822,10 @@ pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer { art_at(h, a, Kind::Any) } +pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer { + art_index(h, a, Kind::Any) +} + pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer { art_by_name(h, a, Kind::Any) } @@ -1368,11 +1395,17 @@ fn boards_set_active(h: &Host, a: &[Data]) -> Answer { let doc = boards_doc(h, a)?; let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st))); let i = board_index_arg(arg(a, 1), len, "index")?; - if i != now { + // The artboard's id is stored on every call, so an artboard inserted before it later does not + // change which artboard is active. + { let mut s = h.session.borrow_mut(); let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id); - drop(s); + } + // A document the run opened is reported whenever an artboard is chosen in it, since the report + // has no start index for it to compare with. + let new_doc = !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid); + if i != now || new_doc { let mut moved = h.dom.active_artboards.borrow_mut(); if !moved.contains(&doc.uid) { moved.push(doc.uid); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c1dcac9cae..bdced805e9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -872,6 +872,11 @@ fn an_object_cannot_go_behind_a_clipping_path() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; p.getByName('art').move(p.getByName('mask'), ElementPlacement.PLACEAFTER);"); assert!(e.contains("an object cannot go below a clipping mask"), "{e}"); assert_eq!(kids(&s), before); + // The clipping path moved directly below the object above it stays where it is. + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art'), ElementPlacement.PLACEAFTER);"); + assert_eq!(kids(&s), before); + assert_eq!(undo_steps(&s), steps); let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); s.execute("object.setProps", &json!({"id": c.0, "name": "c"})).unwrap(); log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('c').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); @@ -3193,6 +3198,68 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() { assert!(r.get("activeArtboards").is_none()); } +/// Choosing the artboard that is already active by default keeps that artboard active when another +/// is inserted before it. +#[test] +fn choosing_the_default_active_artboard_follows_it_past_an_insert() { + let (mut s, _, _) = doc(); + run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]);").unwrap(); + let first = s.active().unwrap().doc.artboards[0].id; + let out = log( + &mut s, + "var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());", + ); + assert_eq!(out, [json!(1)]); + assert_eq!(s.active().unwrap().active_artboard, Some(first)); + // In a document the run opens, the report gives the chosen artboard's index at the end. + let r = run(&mut s, "var d = app.documents.add(); d.artboards.setActiveArtboardIndex(0); d.artboards.insert([800, 300, 900, 100], 0);").unwrap(); + let boards = r["activeArtboards"].as_array().cloned().unwrap_or_default(); + assert!(boards.iter().any(|b| b["document"] == json!(1) && b["artboard"] == json!(1)), "{r}"); +} + +/// A stale container's `pageItems.index(n)` and `groupItems.index(n)` throw the stale error for +/// every number, a negative one included. +#[test] +fn a_stale_containers_list_throws_its_stale_error_for_any_index() { + let (mut s, ..) = doc(); + let folder = vectorcraft_testkit::TempDir::new("script-dom-stale-index"); + let path = folder.join("saved.vectorcraft"); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for list in ["pageItems", "groupItems"] { + let source = + format!("var d = app.activeDocument, p = d.layers[0].{list}; d.pageItems[0].name = 'changed'; vc.run('file.revert'); p.index(-1);"); + let e = failure(&mut s, &source); + assert!(e.contains("Stale page item"), "{list}: {e}"); + } +} + +/// `removeAll()` on a clip group releases its mask, so an object added to the group afterwards is +/// not its clipping path; the run's one undo step puts everything back. +#[test] +fn remove_all_on_a_clip_group_releases_its_mask() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); g.groupItems.add(); vc.log(g.clipped);"); + assert_eq!(out, [json!(false), json!(false)]); + assert!(!s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_steps(&s), steps); + let st = s.active().unwrap(); + assert!(st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // `groupItems.removeAll()` leaves the clipping path, and the group keeps its mask. + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0]; g.groupItems.add(); g.groupItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);", + ); + assert_eq!(out, [json!(true), json!(2)]); +} + #[test] fn the_report_gives_the_active_artboard_the_run_leaves() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 5f6503bf48..7850ab1515 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3035,9 +3035,10 @@ through `$`: group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws - `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception - is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the - document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. An object of + `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The exceptions + are `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself and `mask.move(art, + ElementPlacement.PLACEAFTER)` with the object directly above it, which succeed and leave the document unchanged; + `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. 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 @@ -3099,7 +3100,8 @@ 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 + and delete nothing. A clip group's `removeAll()` that deletes every object in it, the clipping path included, + also releases the group's clipping mask in the same undo step. 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, @@ -3183,7 +3185,9 @@ through `$`: `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 + artboards were inserted, removed or reordered before it, and a document the run opened in which an artboard was + chosen. The chosen artboard stays active when another is inserted before it, even if it was already the active + one. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and `GroupItems.createFromFile` throw an error that says they are not available yet. From d22384d6ba35ce437791e3c5a536233b72c5334b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:38:12 -0800 Subject: [PATCH 18/28] Scripts: release a mask whose clipping path is deleted, charge controlBounds - remove(), any collection's removeAll() and the document's pageItems.removeAll() release the mask of a clip group or clipping layer whose clipping path they delete, in the same undo step, so the object above it does not become the clipping path. A deletion that leaves the clipping path keeps the mask. - move(group, PLACEATEND) on a clip group's own clipping path leaves it where it is; INSIDE and PLACEATBEGINNING still throw node.move's error. - controlBounds charges each object and anchor it visits against the data a run may pass. - The scoped removeAll() test catches the locked-artboard error inside the script and checks that art on an unlocked artboard is still there. - A test checks that a layer, page item or artboard handle from before app.undo() does not name an object added afterwards. Docs: docs/mcp.md (artboards.insert runs artboard.reorder only when the index differs from the new artboard's). --- crates/engine/src/script/dom.rs | 59 +++++++++--- crates/engine/src/script/dom/layers.rs | 26 +----- crates/engine/src/tests/script_dom.rs | 121 ++++++++++++++++++++++++- docs/mcp.md | 16 ++-- 4 files changed, 180 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7234e4f179..c2d47e6b88 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2273,13 +2273,16 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { return layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(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(); - (ids, refused, on_locked) + // A clipping layer emptied of its art releases its mask, so art added later is not made its + // clipping path. + let released = masks_cleared_by(&st.doc, &ids); + (ids, refused, on_locked, released) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -2290,7 +2293,7 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {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::>()})))?; + on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } Ok(Data::Undefined) } @@ -2552,24 +2555,31 @@ fn item_control(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; // An object with nothing in it reads zeros, as its other bounds do. let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) }; - let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r))); + // Each object and anchor the walk visits is charged, so reading a large group's bounds again + // and again counts against the run. + let mut steps = 0u64; + let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r, &mut steps))); + h.charge_call(steps)?; Ok(f.bounds(h.dom.coords.get(), r)) } -/// `r` with the anchors and direction handles of the shown paths in `n`. Hidden objects, the -/// objects in them and guides are left out, as the visible bounds leave them out, and a clip group -/// or clipping layer gives only its clipping path's. -fn take_in_handles(n: &crate::doc::Node, mut r: Rect) -> Rect { +/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and +/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as +/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping +/// path's. +fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect { + *steps += 1; if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) { return r; } for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) { + *steps += 1; r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out); } let children = n.children().map_or(&[][..], Vec::as_slice); let children = if n.clips() { &children[..children.len().min(1)] } else { children }; for c in children { - r = take_in_handles(c, r); + r = take_in_handles(c, r, steps); } r } @@ -2704,11 +2714,37 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } + let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id])); // A compound path whose last path this is stays, empty, as it does after `move`. - edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?; + let params = json!({"ids": [item.id.0], "keepEmpty": true}); + paths::see_all_points(h); + let kept = h.dom.editing.replace(Some(item)); + let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, ¶ms))); + h.dom.editing.set(kept); + r?; Ok(Data::Undefined) } +/// The clip groups and clipping layers whose clipping path is one of `ids`. Deleting a clipping +/// path releases its mask, so the object above it does not become the clipping path. +pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec { + ids.iter() + .filter_map(|i| { + let p = d.parent_of(*i)?; + let n = d.node(p)?; + (n.clips() && n.children()?.first().is_some_and(|c| c.id == *i)).then_some(p) + }) + .collect() +} + +/// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`. +pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result { + for g in released { + command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?; + } + command(h, "edit.clear", params) +} + /// The error of `remove()` and `removeAll()` for an object on a locked artboard. pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; @@ -2842,7 +2878,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul } (_, None) => count, }; - let stays = mask_stays && at == 0 && to.how != Placement::Bottom; + // Any other place for the clipping path is left to `node.move`, which refuses it. + let stays = mask_stays && at == 0; Ok::<_, HostError>(if clips && !stays { at.max(1) } else { at }) })?; let now = with_doc(h, doc, |_, st| st.doc.position(id)); diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 739fe441b3..757d3b73c5 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -783,27 +783,11 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer { if !ids.is_empty() { // The container stays, empty, as a compound path whose last path `remove()` takes out does. let params = json!({"ids": ids.iter().map(|i| i.0).collect::>(), "keepEmpty": c.is_some()}); - // An emptied clipping group releases its mask, so an object added to it later is not - // made its clipping path. - // Only a deletion that takes every object of the group, its clipping path included, does. - let clipped = c.filter(|c| { - with_doc(h, doc, |_, st| { - st.doc.node(*c).is_some_and(|n| { - matches!(n.kind, NodeKind::Group { .. }) - && n.clips() - && n.children().is_some_and(|k| { - let gone: std::collections::HashSet = ids.iter().copied().collect(); - k.iter().all(|k| gone.contains(&k.id)) - }) - }) - }) - }); - on_doc(h, doc.uid, true, |h| { - if let Some(g) = clipped { - command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?; - } - command(h, "edit.clear", ¶ms) - })?; + // A deletion that takes a clipping path releases its clip group's or clipping layer's mask, + // so neither the object above it nor one added later is made the clipping path. A deletion + // that leaves the clipping path keeps the mask. + let released = with_doc(h, doc, |_, st| super::masks_cleared_by(&st.doc, &ids)); + on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms))?; } Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c3f250e909..7b732fe68f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -160,6 +160,25 @@ fn control_bounds_leave_out_hidden_paths() { assert_eq!(out[1], out[0], "{out:?}"); } +/// Each anchor `controlBounds` visits counts toward the data a run passes, so reading the bounds of +/// a large path again and again ends the run where reading its geometric bounds does not. +#[test] +fn control_bounds_count_the_anchors_they_visit() { + let (mut s, _, _) = doc(); + let d: String = (0..2000u32).map(|i| format!(" L{} {}", i % 300, (i * 7) % 200)).collect(); + let id = s.execute("path.create", &json!({"d": format!("M0 0{d}")})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // 100 reads of 2001 anchors are about 200 KB of steps, over a 64 KiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16))); + let read = |s: &mut Session, what: &str| run(s, &format!("var i = app.activeDocument.selection[0]; for (var n = 0; n < 100; n++) i.{what};")); + let geometric = read(&mut s, "geometricBounds"); + let control = read(&mut s, "controlBounds"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + geometric.unwrap(); + let e = control.unwrap_err().to_string(); + assert!(e.contains("passed more data"), "{e}"); +} + /// The `controlBounds` of a clip group leave out the handles of the clipped art past the clipping /// path. #[test] @@ -448,6 +467,36 @@ fn app_undo_and_redo_step_through_the_runs_edits() { assert!(failure(&mut s, "app.redo();").contains("No active document")); } +/// A layer, page item or artboard read before `app.undo()` took it away is stale, even when an +/// object added afterwards takes its id; one that `app.redo()` brings back, and one that was there +/// before the undone step, still work. +#[test] +fn a_handle_from_before_an_undo_does_not_name_a_later_object() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var d = app.activeDocument, kept = d.layers[0], m;\ + var a = d.layers.add(); app.undo(); var b = d.layers.add(); b.name = 'b';\ + m = ''; try { a.name = 'x'; } catch (e) { m = e.message; } vc.log([m, b.name]);\ + m = ''; try { a.groupItems.length; } catch (e) { m = e.message; } vc.log(m);\ + var p = d.groupItems.add(); app.undo(); var q = d.groupItems.add(); q.name = 'q';\ + m = ''; try { p.name = 'y'; } catch (e) { m = e.message; } vc.log([m, q.name]);\ + var r = d.artboards.add([500, 300, 700, 100]); app.undo(); var t = d.artboards.add([800, 300, 1000, 100]); t.name = 't';\ + m = ''; try { r.name = 'z'; } catch (e) { m = e.message; } vc.log([m, t.name]);\ + var c = d.layers.add(); app.undo(); app.redo(); c.name = 'c'; kept.name = 'kept'; vc.log([c.name, kept.name]);", + ); + assert_eq!( + out, + vec![ + json!(["Stale layer", "b"]), + json!("Stale layer"), + json!(["Stale page item", "q"]), + json!(["Stale artboard", "t"]), + json!(["c", "kept"]), + ] + ); +} + /// An opacity a graph mark already has still replaces the opacity another mark of its series left on /// the graph, as `object.setProps` does. #[test] @@ -877,6 +926,19 @@ fn an_object_cannot_go_behind_a_clipping_path() { log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art'), ElementPlacement.PLACEAFTER);"); assert_eq!(kids(&s), before); assert_eq!(undo_steps(&s), steps); + // The clipping path put at the end of its own clip group stays where it is; put on top of the + // group's contents, it is refused. + log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); + assert_eq!(kids(&s), before); + assert_eq!(undo_steps(&s), steps); + for place in ["INSIDE", "PLACEATBEGINNING"] { + let e = failure( + &mut s, + &format!("var p = app.activeDocument.pageItems; p.getByName('mask').move(p.getByName('art').parent, ElementPlacement.{place});"), + ); + assert!(e.contains("the clipping path stays at the bottom of its clip group"), "{place}: {e}"); + assert_eq!(kids(&s), before, "{place}"); + } let c = rect(&mut s, 300.0, 10.0, 5.0, 5.0); s.execute("object.setProps", &json!({"id": c.0, "name": "c"})).unwrap(); log(&mut s, "var p = app.activeDocument.pageItems; p.getByName('c').move(p.getByName('art').parent, ElementPlacement.PLACEATEND);"); @@ -2236,7 +2298,8 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { fn scoped_remove_all_refuses_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); - s.execute("object.group", &json!({})).unwrap(); + let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.setProps", &json!({"id": g, "name": "locked"})).unwrap(); let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); @@ -2249,20 +2312,32 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() { .unwrap(); }; lock(&mut s, true); + // A path and a group on a second, unlocked artboard, made last so each lists first in its + // scope, are not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let u = rect(&mut s, 1300.0, 100.0, 20.0, 20.0); + let v = rect(&mut s, 1100.0, 100.0, 20.0, 20.0); + let w = rect(&mut s, 1150.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [v.0, w.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); let before = format!("{:?}", s.active().unwrap().doc.layers); let steps = undo_steps(&s); for scope in [ "app.activeDocument.layers[0].pageItems", "app.activeDocument.layers[0].groupItems", "app.activeDocument.groupItems", - "app.activeDocument.groupItems[0].pageItems", + "app.activeDocument.groupItems.getByName('locked').pageItems", "app.activeDocument.layers[0].compoundPathItems", "app.activeDocument.compoundPathItems", ] { - let err = failure(&mut s, &format!("{scope}.removeAll();")); - assert!(err.contains("cannot delete objects on a locked artboard"), "{scope}: {err}"); + // The error is caught, so the run keeps whatever `removeAll()` did before it threw. + let out = log(&mut s, &format!("var m = ''; try {{ {scope}.removeAll(); }} catch (e) {{ m = e.message; }} vc.log(m);")); + assert!(out[0].as_str().is_some_and(|m| m.contains("cannot delete objects on a locked artboard")), "{scope}: {out:?}"); assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before, "{scope}"); assert_eq!(undo_steps(&s), steps, "{scope}"); + let doc = &s.active().unwrap().doc; + assert!([u, v, w].iter().all(|i| doc.node(*i).is_some()), "{scope}"); } lock(&mut s, false); let out = log(&mut s, "var d = app.activeDocument; d.layers[0].pageItems.removeAll(); vc.log(d.pageItems.length);"); @@ -3264,6 +3339,44 @@ fn remove_all_on_a_clip_group_releases_its_mask() { assert_eq!(out, [json!(true), json!(2)]); } +/// Deleting a clip group's clipping path while other art stays in the group releases the mask, so +/// the art above it is not made the clipping path. `remove()` on the clipping path does the same, +/// and so does emptying a clipping layer with the document's `pageItems.removeAll()`. +#[test] +fn deleting_a_clipping_path_releases_its_mask() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let e = rect(&mut s, 250.0, 100.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0, b.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let kids = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect::>(); + let mask = kids(&s)[0]; + assert!(matches!(s.active().unwrap().doc.node(mask).unwrap().kind, NodeKind::Compound { .. })); + s.execute("object.setProps", &json!({"id": mask.0, "name": "mask"})).unwrap(); + let clips = |s: &Session| s.active().unwrap().doc.node(g).unwrap().clips(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; g.compoundPathItems.removeAll(); vc.log([g.clipped, g.pageItems.length]);"); + assert_eq!(out, [json!([false, 2])]); + assert!(!clips(&s)); + assert_eq!(kids(&s), [a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(clips(&s)); + let out = + log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.getByName('mask').remove(); vc.log([g.clipped, g.pageItems.length]);"); + assert_eq!(out, [json!([false, 2])]); + assert!(!clips(&s)); + assert_eq!(kids(&s), [a, b]); + // A clipping layer emptied by `pageItems.removeAll()` releases its mask too. + let (mut s, _, _) = doc(); + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.active().unwrap().doc.layers[0].clips()); + log(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(!s.active().unwrap().doc.layers[0].clips()); +} + #[test] fn the_report_gives_the_active_artboard_the_run_leaves() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 49501ea0a8..f6914f9e10 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3042,9 +3042,11 @@ through `$`: directly above the relative object and `PLACEAFTER` directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The exceptions - are `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself and `mask.move(art, - ElementPlacement.PLACEAFTER)` with the object directly above it, which succeed and leave the document unchanged; - `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. An object of + are `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, `mask.move(art, + ElementPlacement.PLACEAFTER)` with the object directly above it and `mask.move(group, ElementPlacement.PLACEATEND)` + with its own clip group, which succeed and leave the document unchanged; + `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Any other place for the clipping path, such as + `INSIDE` or `PLACEATBEGINNING` of its own clip group, throws the `node.move` error below and moves nothing. 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 @@ -3106,8 +3108,9 @@ 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. A clip group's `removeAll()` that deletes every object in it, the clipping path included, - also releases the group's clipping mask in the same undo step. Setting `width` or `height` scales the object along + and delete nothing. `remove()`, and any collection's `removeAll()`, that deletes the clipping path of a clip group + or clipping layer also releases that clipping mask in the same undo step, so the object above the clipping path + does not become the new clipping path; a deletion that leaves the clipping path keeps the mask. 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, @@ -3153,7 +3156,8 @@ through `$`: `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. `clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/) has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new`), - `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, and returns `undefined`), `remove(index)` (runs + `insert(artboardRect, index)` (runs `artboard.new`, then `artboard.reorder` when `index` is not the index the new + artboard got, so an index that appends runs no `artboard.reorder`; returns `undefined`), `remove(index)` (runs `artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`, `rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its From b51d13d2a4d72cf233227e8bcf9dc050fa75c2cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:28:48 -0800 Subject: [PATCH 19/28] New document: a replayed rows count over 1000 is kept to 1000 A file.new step replayed from a journal or the Actions panel rounded artboardLayout.rows and then refused a result over 1000, so a step with rows 1000.5 or 5000 stopped the playback. The rows count now follows the columns rule: it is rounded, must be 1 or more, and is kept to at most 1000. Recent stores the kept count. docs/mcp.md says the same. --- crates/engine/src/cmd/newdoc.rs | 2 +- crates/engine/src/tests/newdoc.rs | 7 ++++++- crates/engine/src/tests/script_dom.rs | 4 ++-- docs/mcp.md | 2 +- 4 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 79ce3f97fa..3dc7f579d8 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -395,7 +395,7 @@ impl DocSettings { } "rows" => { self.rows = if replaying { - v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32) + v.as_f64().map(f64::round).filter(|n| *n >= 1.0).map(|n| n.min(f64::from(MAX_ARTBOARDS)) as u32) } else { count(v) } diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 200792d5fe..a320b09b18 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -219,6 +219,8 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { ("rows", 2.4, 2), ("rows", 0.6, 1), ("rows", 1000.4, 1000), + ("rows", 1000.6, 1000), + ("rows", 5000.0, 1000), ] { let mut p = json!({"width": 10, "height": 10, "artboards": 4, "artboardLayout": {"layout": "gridByColumn", "spacing": 0}}); @@ -236,8 +238,11 @@ fn replayed_counts_keep_their_rounding_and_range_rules() { p["artboardLayout"][key] = json!(expected); } assert_eq!(boards(&s), boards(&new_doc(p))); + if key == "rows" { + assert_eq!(presets(&mut s, "Recent")[0]["artboardLayout"]["rows"], json!(expected), "{value}"); + } } - for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] { + for layout in [json!({"columns": 0.6}), json!({"rows": 0.4})] { let mut p = json!({"artboardLayout": layout}); p["artboardLayout"]["layout"] = json!("gridByColumn"); let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ca827eb2ab..e4d2f62350 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1306,10 +1306,10 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { #[test] fn file_new_replays_legacy_fractional_and_large_rows() { - for (rows, rounded) in [(3.6, 4), (1000.4, 1000)] { + for (rows, rounded) in [(3.6, 4), (1000.4, 1000), (1000.5, 1000), (5000.0, 1000)] { let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); let mut s = Session::new(); - // A direct call refuses a fraction; a replay rounds it to a count from 1 to 1000. + // A direct call refuses a fraction or a count over 1000; a replay rounds it and keeps it to at most 1000. let direct = Session::new().execute("file.new", ¶ms); assert!(direct.is_err(), "{rows}: {direct:?}"); s.replay("file.new", ¶ms).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 5a0fb08062..14fd04a184 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -636,7 +636,7 @@ left out or null; `appearance.setActiveItem` reads a null `index` as clearing th whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of -1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000. +1 or more is rounded and kept to at most 1000, and a `rows` is rounded, must then be 1 or more, and is kept to at most 1000. A command that leaves out an object selected inside a selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes `ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value From 0d8a56cfde36e5c836b813ee45539c673b8ff6fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 18:44:26 -0800 Subject: [PATCH 20/28] Scripts: zOrderPosition reuses the layer list; textFrames.removeAll releases masks - Layer.zOrderPosition reads the sibling list through the cached layer lists, so reading it for every layer of a loop lists the layers once. Each read is still charged for the search through the list. - TextFrames.removeAll releases the mask of a group or layer whose clipping path is one of the type objects it deletes, as PageItems.removeAll and remove() do, so the object above the type is not made the clipping path. - GroupItems.createFromFile checks that its collection is still there first, so a collection whose group was deleted throws "Stale page item" instead of the not-available message. docs/mcp.md says so. --- crates/engine/src/script/dom.rs | 6 ++++- crates/engine/src/script/dom/layers.rs | 14 ++++++----- crates/engine/src/script/dom/text.rs | 10 +++++--- crates/engine/src/tests/script_dom.rs | 33 ++++++++++++++++++++++++++ crates/engine/src/tests/script_text.rs | 27 +++++++++++++++++++++ docs/mcp.md | 3 ++- 6 files changed, 82 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4c14498fe7..a0bd117d11 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -470,7 +470,8 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document, layer, page item, path point or text range `this` is still there. +/// the check that a document, layer, page item, path point, text range or `GroupItems` collection +/// `this` is still there. /// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and /// `reflect` leaves it out. pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { @@ -495,6 +496,9 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des "TextRange" => { text::check_range(&h, arg(&a, 0))?; } + "GroupItems" => { + layers::check_groups(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 8ca6423ea4..0b1b1f0e57 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -295,14 +295,12 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer { } /// The layer's place among the layers beside it, from 1 at the bottom. Art beside a sublayer is -/// not counted. +/// not counted. The list comes from [`layers_listed`], so reading it for each layer of a loop +/// lists the layers once. Each read is still charged for the search through the list. fn layer_z_position(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let at = with_doc(h, doc, |_, st| { - let parent = st.doc.parent_of(id); - let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len)); - h.charge_call(count as u64)?; - let list = layer_list(&st.doc, parent); + let list = layers_listed(h, st, st.doc.parent_of(id))?; h.charge_call(list.len() as u64)?; Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i)) })?; @@ -1356,9 +1354,13 @@ fn layers_to_string(h: &Host, a: &[Data]) -> Answer { Ok(text("[Layers]")) } fn groups_to_string(h: &Host, a: &[Data]) -> Answer { - art_scope(h, arg(a, 0), Kind::Group.class())?; + check_groups(h, arg(a, 0))?; Ok(text("[GroupItems]")) } +/// Fails when `d` is not a `GroupItems` collection or the document, layer or group it lists is gone. +pub(super) fn check_groups(h: &Host, d: &Data) -> Result<()> { + art_scope(h, d, Kind::Group.class()).map(|_| ()) +} fn compounds_to_string(h: &Host, a: &[Data]) -> Answer { art_scope(h, arg(a, 0), Kind::Compound.class())?; Ok(text("[CompoundPathItems]")) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index ab6a86222b..0555782952 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1480,13 +1480,16 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { /// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let (doc, c) = frames_scope(h, a)?; - let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released) = with_doc(h, doc, |_, st| { let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(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)) + // Type that clips a group or layer releases its mask, so the object above it is not made + // the clipping path. + let released = super::masks_cleared_by(&st.doc, &ids); + Ok::<_, HostError>((ids, refused, on_locked, released)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1497,7 +1500,8 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); } 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::>()}); + super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms)))?; } Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 7ebc1c2c40..8bc97bffe9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -3714,6 +3714,39 @@ fn a_loop_over_layers_lists_them_once() { assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); } +/// Reading `zOrderPosition` for every layer lists the layers once while the document is unchanged. +#[test] +fn z_order_position_of_each_layer_lists_them_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for _ in 0..39 { + s.execute("layer.new", &json!({})).unwrap(); + } + let n = s.active().unwrap().doc.layers.len() as u64; + crate::script::dom::LAYER_SCANS.with(|c| c.set(0)); + let out = log( + &mut s, + "var L = app.activeDocument.layers, k = L.length, z = []; for (var i = 0; i < k; i++) { z.push(L[i].zOrderPosition); } vc.log(z[0]); vc.log(z[k - 1]);", + ); + assert_eq!(out, vec![json!(n), json!(1)]); + let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get); + assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers"); +} + +/// `groupItems.createFromFile` on a collection whose group is gone reports the stale object before +/// the member that is not available yet. +#[test] +fn create_from_file_on_a_stale_group_collection_reports_it_stale() { + 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 e = failure(&mut s, "var g = app.activeDocument.groupItems[0], c = g.groupItems; g.remove(); c.createFromFile(new File('x.svg'));"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.groupItems[0].groupItems.createFromFile(new File('x.svg'));"); + assert!(e.contains("GroupItems.createFromFile is not available yet"), "{e}"); +} + /// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the /// document's `pageItems`, also when the list was already built. #[test] diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index cd4bc2f704..f64777a123 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -731,6 +731,33 @@ fn text_frames_of_a_layer_or_group_put_new_type_in_it() { assert_eq!(undo_steps(&s), before); } +/// `textFrames.removeAll()` on type that clips a group releases the mask, so the object above the +/// type stays an ordinary member and is not made the clipping path. +#[test] +fn text_frames_remove_all_releases_a_mask_the_type_clips() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + let t = s.execute("text.create", &json!({"x": 20, "y": 100, "text": "clip", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b, t]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let first = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().first().map(|c| c.id); + assert_eq!(first(&s), Some(NodeId(t)), "the type is the clipping path"); + let steps = undo_steps(&s); + let out = log(&mut s, "app.activeDocument.textFrames.removeAll(); vc.log(app.activeDocument.groupItems[0].clipped);"); + assert_eq!(out, [json!(false)]); + let st = s.active().unwrap(); + assert!(!st.doc.node(g).unwrap().clips()); + assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2); + // The run is one undo step, and undoing it puts back both the type and its mask. + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.active().unwrap().doc.node(g).unwrap().clips()); + assert_eq!(first(&s), Some(NodeId(t))); +} + /// `textFrames.removeAll()` deletes nothing when a type object it lists is on a locked artboard. #[test] fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { diff --git a/docs/mcp.md b/docs/mcp.md index b2d366a7c4..8e2c1b01fb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3343,7 +3343,8 @@ through `$`: one. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and - `GroupItems.createFromFile` throw an error that says they are not available yet. + `GroupItems.createFromFile` throw an error that says they are not available yet. `GroupItems.createFromFile` on a + collection whose document, layer or group was deleted throws `Stale page item` or `Stale document` first. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and From 80569dc577e6f8b7b1e83bc0db4591b4de0b0271 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:24:21 -0800 Subject: [PATCH 21/28] Scripts: deleting a clipping path cannot make a tracing remove(), the document's pageItems.removeAll() and textFrames.removeAll() release the mask of a clip group whose clipping path they delete. A clip group named Image Trace with an image next above its clipping path then became an ordinary group named as a tracing with an image first, which reads as a tracing. They now throw "Only Image Trace can make a tracing" and delete nothing in that case. docs/mcp.md names the removeAll() collections that release a mask and the ones that refuse to delete a clipping path instead. --- crates/engine/src/script/dom.rs | 26 ++++++++++- crates/engine/src/script/dom/text.rs | 9 +++- crates/engine/src/tests/script_dom_tracing.rs | 45 +++++++++++++++++++ docs/mcp.md | 10 +++-- 4 files changed, 83 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a0bd117d11..8168075b9b 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2337,7 +2337,7 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { return layers::scoped_remove_all(h, a); } let doc = items_doc(h, a)?; - let (ids, refused, on_locked, released) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); @@ -2346,7 +2346,8 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { // A clipping layer emptied of its art releases its mask, so art added later is not made its // clipping path. let released = masks_cleared_by(&st.doc, &ids); - (ids, refused, on_locked, released) + let tracing = release_makes_tracing(&st.doc, &released, &ids); + (ids, refused, on_locked, released, tracing) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -2356,6 +2357,9 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); } + if tracing { + return Err(HostError::Error(NOT_A_TRACING.into())); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -2851,6 +2855,10 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Error(NOT_A_TRACING.into())); } let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id])); + // A clip group named as a tracing, released with an image left first, would become one too. + if with_doc(h, item.doc, |_, st| release_makes_tracing(&st.doc, &released, &[item.id])) { + return Err(HostError::Error(NOT_A_TRACING.into())); + } // A compound path whose last path this is stays, empty, as it does after `move`. let params = json!({"ids": [item.id.0], "keepEmpty": true}); paths::see_all_points(h); @@ -2873,6 +2881,20 @@ pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec { .collect() } +/// Whether releasing the masks of `released` and deleting `removed` would leave one of those groups +/// an ordinary group named as a tracing with an image first in it, which would make it a tracing. +pub(super) fn release_makes_tracing(d: &Document, released: &[NodeId], removed: &[NodeId]) -> bool { + if released.is_empty() { + return false; + } + let removed: std::collections::HashSet = removed.iter().copied().collect(); + released.iter().filter_map(|g| d.node(*g)).any(|g| { + matches!(g.kind, NodeKind::Group { .. }) + && g.name.as_deref() == Some(crate::cmd::TRACE_NAME) + && g.children().and_then(|c| c.iter().find(|n| !removed.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))) + }) +} + /// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`. pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result { for g in released { diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 0555782952..1a86a1b50e 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1480,7 +1480,7 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { /// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let (doc, c) = frames_scope(h, a)?; - let (ids, refused, on_locked, released) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| { let ids = listed(h, st, c)?; let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); @@ -1489,7 +1489,8 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { // Type that clips a group or layer releases its mask, so the object above it is not made // the clipping path. let released = super::masks_cleared_by(&st.doc, &ids); - Ok::<_, HostError>((ids, refused, on_locked, released)) + let tracing = super::release_makes_tracing(&st.doc, &released, &ids); + Ok::<_, HostError>((ids, refused, on_locked, released, tracing)) })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); @@ -1499,6 +1500,10 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); } + // A clip group named as a tracing, released with an image left first, would become one. + if tracing { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } if !ids.is_empty() { let params = json!({"ids": ids.iter().map(|i| i.0).collect::>()}); super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms)))?; diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 24223785dd..0f6851d342 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1197,6 +1197,51 @@ fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() { let _ = std::fs::remove_dir_all(base); } +/// Deleting the clipping path of a clip group named as a tracing releases its mask, so `remove()` and +/// `textFrames.removeAll()` refuse it when an image would be left first in the released group. +#[test] +fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("release-trace-name"); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.rasterItems[0], d.pathItems.rectangle(10, 10, 20, 20)];\ + vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { d.pathItems[0].remove(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.clipped);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(true)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + let (mut s, _) = session(&base, false); + log( + &mut s, + &base, + "var d = app.activeDocument, t = d.textFrames.add(); t.contents = 'Clip';\ + d.selection = [d.rasterItems[0], t]; vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';", + ); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + let steps = undo_steps(&s); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, g = d.pageItems[0], m = '';\ + try { g.textFrames.removeAll(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.textFrames.length);", + ); + assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(1)]); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert_eq!(undo_steps(&s), steps); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object /// its trace did not make, before the document changes. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 8e2c1b01fb..c2b52798e3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3242,9 +3242,13 @@ 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. `remove()`, and any collection's `removeAll()`, that deletes the clipping path of a clip group - or clipping layer also releases that clipping mask in the same undo step, so the object above the clipping path - does not become the new clipping path; a deletion that leaves the clipping path keeps the mask. Setting `width` or `height` scales the object along + and delete nothing. `remove()`, the document's `pageItems.removeAll()` and any `textFrames.removeAll()` that + delete the clipping path of a clip group or clipping layer also release that clipping mask in the same undo step, + so the object above the clipping path does not become the new clipping path; a deletion that leaves the clipping + path keeps the mask. When the released group is named `Image Trace` and an image would be left at its bottom, they + throw `Only Image Trace can make a tracing` and delete nothing. The `removeAll()` of a layer's or group's + `pageItems`, and of any `groupItems` or `compoundPathItems`, does not release a mask: it throws as described + above. 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, From 95e2aa4804b046004584869052e977a6c2d1cf8c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:26:38 -0800 Subject: [PATCH 22/28] Tests: PDF import limits and optional content membership Add tests that fail when these PDF import paths break: - Optional content membership dictionaries: AllOn, AnyOff, AllOff and the default AnyOn decide which marked art the page walk skips, with groups given as an array or a single reference. Each shown path keeps the spot ink the walk found it painted in. - Tiling patterns and soft masks nested more than 8 levels deep open with their "nested too deeply" warnings. - The ink-space scan stops 32 levels into an object and after 4,096 spaces. - A one-ink image of more than 2^26 pixels is refused before its samples are decoded. --- crates/pdf/src/tests/import_color.rs | 60 +++++++++++++++++++++++++ crates/pdf/src/tests/import_fidelity.rs | 46 +++++++++++++++++++ crates/pdf/src/tests/import_layers.rs | 47 +++++++++++++++++++ 3 files changed, 153 insertions(+) diff --git a/crates/pdf/src/tests/import_color.rs b/crates/pdf/src/tests/import_color.rs index 086b711aec..a7e83e56f3 100644 --- a/crates/pdf/src/tests/import_color.rs +++ b/crates/pdf/src/tests/import_color.rs @@ -560,3 +560,63 @@ fn rgb_numbers_stand_in_editor_documents_only() { assert!(near(color(true), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(true)); assert!(!near(color(false), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(false)); } + +/// The space the scan of a page holding colour spaces `spaces` finds for a Gold Separation (tint +/// transform [`GOLD_TINT`]). +fn gold_space(spaces: &str) -> Space { + use craft::pdf::interpret::Function; + use craft::pdf::syntax::object::{FromBytes, Object}; + let key = format!("{:?}", Function::new(&Object::from_bytes(GOLD_TINT.as_bytes()).unwrap()).unwrap()); + let pdf = craft::pdf::syntax::Pdf::new(pdf(&[page_with(spaces, &[])], None)).unwrap(); + Colors::new(&pdf, vec![]).space_of(&format!("ColorSpace(Separation(Separation {{ tint_transform: {key} }}))"), 1, None) +} + +const GOLD_TINT: &str = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + +/// The scan for ink spaces looks 32 levels into an object and no deeper. +#[test] +fn ink_spaces_nested_past_the_scan_depth_are_not_found() { + let gold = format!("[/Separation /Gold /DeviceCMYK {GOLD_TINT}]"); + let nested = |levels: usize| format!("/A {}{gold}{}", "[".repeat(levels), "]".repeat(levels)); + assert_eq!(gold_space(&nested(20)), Space::Inks(0)); + assert_eq!(gold_space(&nested(40)), Space::Other); +} + +/// The scan keeps 4,096 ink spaces: a space after that many others is not found. +#[test] +fn ink_spaces_past_the_scan_count_are_not_found() { + let filler = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>"; + let spaces = |n: usize| -> String { + let fillers: String = (0..n).map(|i| format!("[/Separation /Ink{i} /DeviceCMYK {filler}]")).collect(); + format!("/A [{fillers}[/Separation /Gold /DeviceCMYK {GOLD_TINT}]]") + }; + assert_eq!(gold_space(&spaces(4095)), Space::Inks(4095)); + assert_eq!(gold_space(&spaces(4096)), Space::Other); +} + +/// A one-ink image of more pixels than a CMYK image may have is refused before its samples are +/// decoded; the same samples read at a smaller size are not. +#[test] +fn one_ink_images_past_the_pixel_cap_are_refused() { + use std::io::Write; + let side = 8193u32; + let row = (side as usize).div_ceil(8); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + z.write_all(&vec![0u8; row * side as usize]).unwrap(); + let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02x}")).collect(); + let image = format!( + "<< /Type /XObject /Subtype /Image /Width {side} /Height {side} /BitsPerComponent 1 /ColorSpace [/Separation /Gold /DeviceCMYK {GOLD_TINT}] /Filter [/ASCIIHexDecode /FlateDecode] /Length {} >>\nstream\n{hex}>\nendstream", + hex.len() + 1 + ); + let file = craft::pdf::syntax::Pdf::new(pdf_with(&[PdfPage::new(10.0, 10.0, "")], &[&image], None)).unwrap(); + let st = file + .objects() + .into_iter() + .find_map(|o| match o { + craft::pdf::syntax::object::Object::Stream(s) if s.dict().contains_key(b"Width") => Some(s), + _ => None, + }) + .unwrap(); + assert_eq!(crate::import_image::tint_gray(&st, side, side).map(|g| g.len()), Err(crate::import_image::UNREAD_TINTS)); + assert_eq!(crate::import_image::tint_gray(&st, 16, 2), Ok(vec![255; 32])); +} diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 731f18ff06..b009f56d1f 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -370,6 +370,52 @@ fn tiling_patterns_become_pattern_swatches() { assert_eq!(colors, vec![Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]); } +/// Links in the chains of nested patterns and soft masks below: more than are read. +const CHAIN: usize = 12; + +/// The warnings of opening a page drawing `content` with `resources`, plus `objects`. +fn warnings_of(objects: &[String], resources: &str, content: &str) -> Vec { + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + open_with(&one_page(content, resources, &extra), |_| {}).warnings +} + +/// Tiling patterns whose cells fill with the next pattern are read only so many levels deep: a +/// chain of them opens, with a warning. +#[test] +fn patterns_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let cells: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = match i + 1 < CHAIN { + true => (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f"), + false => (String::new(), "1 0 0 rg 0 0 5 5 re f"), + }; + stream(&format!("/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&cells, &format!("/Pattern << /P0 {first} 0 R >>"), "/Pattern cs /P0 scn 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("tiling patterns nested too deeply")), "{w:?}"); +} + +/// Soft masks whose groups draw through the next mask are read only so many levels deep: a chain +/// of them opens, with a warning. +#[test] +fn soft_masks_nested_too_deeply_stop_with_a_warning() { + let first = first_extra(1); + let mask =|i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); + let groups: Vec = (0..CHAIN) + .map(|i| { + let (resources, content) = match i + 1 < CHAIN { + true => (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f"), + false => (String::new(), "1 1 1 rg 0 0 100 100 re f"), + }; + stream(&format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >> /Resources << {resources} >>"), content) + }) + .collect(); + let w = warnings_of(&groups, &mask(0), "/GS0 gs 1 0 0 rg 0 0 100 100 re f"); + assert!(w.iter().any(|w| w.contains("soft masks nested too deeply")), "{w:?}"); +} + // ---------- text ---------- const HELVETICA: &str = diff --git a/crates/pdf/src/tests/import_layers.rs b/crates/pdf/src/tests/import_layers.rs index 33ada6d549..3badde2181 100644 --- a/crates/pdf/src/tests/import_layers.rs +++ b/crates/pdf/src/tests/import_layers.rs @@ -506,3 +506,50 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() { let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap(); assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]); } + +/// Art marked with a membership dictionary is skipped by its policy over its groups, by the page's +/// walk as by the interpreter, so each shown path keeps the ink the walk found it painted in: with +/// "Shapes" on and "Hidden" off, AllOn and AllOff over both are hidden, AnyOff and the default +/// AnyOn show. Groups named by a single reference, not an array, count the same: AllOff over +/// "Hidden" alone shows and AllOff over "Shapes" alone is hidden. +#[test] +fn membership_dictionaries_show_art_by_their_policy() { + let (objs, catalog, [a, b]) = groups(1, "/OFF [{B}]"); + let both = format!("[{a} 0 R {b} 0 R]"); + let runs = [ + ("AllOn", format!("{both} /P /AllOn")), + ("AnyOff", format!("{both} /P /AnyOff")), + ("AllOff", format!("{both} /P /AllOff")), + ("AnyOn", both.clone()), + ("OffAlone", format!("{b} 0 R /P /AllOff")), + ("OnAlone", format!("{a} 0 R /P /AllOff")), + ]; + let memberships: Vec = runs.iter().map(|(_, m)| format!("<< /Type /OCMD /OCGs {m} >>")).collect(); + let first = first_extra(1) + 2; + // Every ink has the same tint transform: only the walk tells the interpreter's paths apart. + let tint = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>"; + let mut content = String::new(); + let (mut props, mut spaces) = (String::new(), String::new()); + for (i, (ink, _)) in runs.iter().enumerate() { + content += &format!("/OC /M{i} BDC /CS{i} cs 1 scn {} 10 5 5 re f EMC ", 10 * i); + props += &format!("/M{i} {} 0 R ", first + i); + spaces += &format!("/CS{i} [/Separation /{ink} /DeviceCMYK {tint}] "); + } + let page = PdfPage { resources: format!("/Properties << {props}>> /ColorSpace << {spaces}>>"), ..PdfPage::new(100.0, 100.0, &content) }; + let mut extra: Vec<&str> = vec![&objs[0], &objs[1]]; + extra.extend(memberships.iter().map(String::as_str)); + let options = ImportOptions { layers: false, ..Default::default() }; + let r = import_with_report(&pdf_with_catalog(&[page], &extra, &catalog, None), &options).unwrap(); + assert_eq!(names(&r.document), ["Page 1"]); + let inks: Vec> = r.document.layers[0] + .children() + .unwrap() + .iter() + .map(|n| match n.appearance.fill().map(|f| &f.paint) { + Some(vectorcraft_color::Paint::Solid { swatch, .. }) => swatch.clone(), + _ => None, + }) + .collect(); + let shown = ["AnyOff", "AnyOn", "OffAlone"].map(|s| Some(s.to_string())); + assert_eq!(inks, shown, "{:?}", r.warnings); +} From 03c3d8264b273204b1c12405153f6fbef63915b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:41:13 -0800 Subject: [PATCH 23/28] Tests: format the nested pattern and soft mask chains --- crates/pdf/src/tests/import_fidelity.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index b009f56d1f..5697e70bb2 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -386,11 +386,13 @@ fn patterns_nested_too_deeply_stop_with_a_warning() { let first = first_extra(1); let cells: Vec = (0..CHAIN) .map(|i| { - let (resources, content) = match i + 1 < CHAIN { - true => (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f"), - false => (String::new(), "1 0 0 rg 0 0 5 5 re f"), + let (resources, content) = if i + 1 < CHAIN { + (format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f") + } else { + (String::new(), "1 0 0 rg 0 0 5 5 re f") }; - stream(&format!("/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources << {resources} >>"), content) + let cell = "/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10"; + stream(&format!("{cell} /Resources << {resources} >>"), content) }) .collect(); let w = warnings_of(&cells, &format!("/Pattern << /P0 {first} 0 R >>"), "/Pattern cs /P0 scn 0 0 100 100 re f"); @@ -402,14 +404,13 @@ fn patterns_nested_too_deeply_stop_with_a_warning() { #[test] fn soft_masks_nested_too_deeply_stop_with_a_warning() { let first = first_extra(1); - let mask =|i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); + let mask = |i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i); let groups: Vec = (0..CHAIN) .map(|i| { - let (resources, content) = match i + 1 < CHAIN { - true => (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f"), - false => (String::new(), "1 1 1 rg 0 0 100 100 re f"), - }; - stream(&format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >> /Resources << {resources} >>"), content) + let (resources, content) = + if i + 1 < CHAIN { (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f") } else { (String::new(), "1 1 1 rg 0 0 100 100 re f") }; + let group = "/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >>"; + stream(&format!("{group} /Resources << {resources} >>"), content) }) .collect(); let w = warnings_of(&groups, &mask(0), "/GS0 gs 1 0 0 rg 0 0 100 100 re f"); From 00cb293b9749c4055d4a27c4fe3c177a37525018 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 20:54:45 -0800 Subject: [PATCH 24/28] Tests: bent type on a path and the fallback file size limit - A rectangle bent along a circle keeps its corners at the ends of its step, its baseline edge on the circle and its other edge on the circle its height along the normal, with and without a rise off the path. A straight path and a glyph with no advance leave the outline as it is. - The file search for a character no loaded font covers loads a font that covers it, and skips the same font padded to 41 MiB. --- crates/text/src/fontdb.rs | 27 ++++++++++++ crates/text/src/layout/on_path.rs | 72 ++++++++++++++++++++++++++++++- 2 files changed, 98 insertions(+), 1 deletion(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index f2a7e4835e..30b95066b5 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -190,6 +190,33 @@ mod alias_tests { assert!(!sys.misses.contains(&'\u{E000}'), "an unsearched character is not a remembered miss"); } + /// The file search for a character no loaded font covers skips font files over 40 MiB + /// without reading them, and loads the same font at its own length. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_file_search_skips_font_files_over_40_mib() { + use crate::{FileFontInfo, FileGlyph, build_file_font}; + use kurbo::Shape; + let pua = '\u{E123}'; + let info = FileFontInfo { family: "Fallback Size Limit Regression".into(), style: "Regular".into(), ..Default::default() }; + let glyph = FileGlyph { ch: pua, outline: kurbo::Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 }; + let font = build_file_font(&info, &[glyph]).unwrap(); + let search = |name: &str, bytes: &[u8]| { + let dir = std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + std::fs::write(dir.join("Pua.ttf"), bytes).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + let found = db.system_fallback(pua); + std::fs::remove_dir_all(&dir).unwrap(); + found + }; + assert!(search("small", &font), "a font at its own length is loaded"); + let mut padded = font.clone(); + padded.resize(41 << 20, 0); + assert!(!search("padded", &padded), "the same font padded to 41 MiB is skipped"); + } + #[test] fn a_collection_lists_at_most_max_faces() { let mut font = name_font(&[(3, 0x0409, 1, "Fam"), (3, 0x0409, 2, "Regular")]); diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 54e4125e88..2fd95fd6b2 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -793,7 +793,77 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, #[cfg(test)] mod tests { - use super::longest_start_tried; + use super::{Affine, ArcPath, BezPath, GlyphBend, PathEl, Point, bend_outline, longest_start_tried}; + use vectorcraft_geom::{Rect, shapes}; + + /// A glyph-sized rectangle in pen space, `w` wide and `h` tall, standing on the baseline. + fn block(w: f64, h: f64) -> BezPath { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((w, 0.0)); + p.line_to((w, h)); + p.line_to((0.0, h)); + p.close_path(); + p + } + + fn end_points(path: &BezPath) -> Vec { + path.elements() + .iter() + .filter_map(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p), + PathEl::ClosePath => None, + }) + .collect() + } + + /// Bent along a circle, a rectangle's baseline edge follows the circle and its other edge + /// follows a circle `h` farther along the path's normal; its corners stay at the ends of its + /// step along the path. Moving it off the path (`rise`) moves both edges by the same amount. + #[test] + fn an_outline_bent_along_a_circle_follows_it() { + let (center, r) = (Point::new(100.0, 100.0), 100.0); + let ap = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + let (w, h, s) = (40.0, 20.0, 30.0); + let (p0, d0) = ap.at(s); + let (p1, _) = ap.at(s + w); + // Which way the path's normal points: away from the center (+1) or towards it (-1). + let side = (kurbo::Vec2::new(-d0.y, d0.x).dot(p0 - center)).signum(); + let at_radius = |p: Point, radius: f64| center + (p - center) * (radius / r); + for rise in [0.0, 5.0] { + let bend = GlyphBend { s, step: w, advance: w, rise }; + let bent = bend_outline(&block(w, h), Affine::IDENTITY, &ap, &bend).expect("a turning path bends the outline"); + let points = end_points(&bent); + let (base, top) = (r + side * rise, r + side * (rise + h)); + let corners = [at_radius(p0, base), at_radius(p1, base), at_radius(p1, top), at_radius(p0, top)]; + for c in corners { + assert!(points.iter().any(|p| p.distance(c) < 0.1), "rise {rise}: no point near the corner {c:?} in {points:?}"); + } + // The edges are cut into pieces that stay between the two circles; a straight chord + // between the corners would pass inside the inner one. + assert!(points.len() > 8, "rise {rise}: {} points", points.len()); + let (inner, outer) = (base.min(top), base.max(top)); + for p in &points { + let d = p.distance(center); + assert!(d > inner - 0.1 && d < outer + 0.1, "rise {rise}: {p:?} lies {d} from the center, outside {inner}..{outer}"); + } + let on_base = points.iter().filter(|p| (p.distance(center) - base).abs() < 0.1).count(); + assert!(on_base > 2, "rise {rise}: only {on_base} points on the baseline circle"); + } + } + + /// A path that does not turn under the glyph, and a glyph with no advance, leave the outline + /// as it is. + #[test] + fn an_outline_on_a_straight_path_is_not_bent() { + let line = ArcPath::new(&shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0))); + let bend = GlyphBend { s: 30.0, step: 40.0, advance: 40.0, rise: 0.0 }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &line, &bend).is_none()); + let circle = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0))); + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &bend).is_some()); + let no_advance = GlyphBend { advance: 0.0, ..bend }; + assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &no_advance).is_none()); + } /// The longest start that fits is found among the ones tried; past the tries, a binary search /// finds one that fits, with as many more tries as halvings of the rest. From d29d2d03dae6504ba283952f5e5f3b759b534e82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:00:46 -0800 Subject: [PATCH 25/28] Tests: harmony labels and DXF miles and kilometers - rules_parse_by_id_and_label reads a few shown labels back through parse(label(h)). The labels are written in vectorcraft-color and the ids come from craft-libs, so a label that drifts from its id no longer parses. - units_choose_the_default_scale covers $INSUNITS 3 (miles) and 7 (kilometers), which have no unit of their own and read as millimeters at their scale. --- crates/cad/src/import/tests.rs | 6 ++++++ crates/color/src/harmony.rs | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index ae5b2d5804..5faad39835 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -140,6 +140,12 @@ fn units_choose_the_default_scale() { assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); } + // Miles and kilometers have no unit of their own, so they read as millimeters at their scale. + for (code, name, pt) in [("3", "Miles", 72.0 * 63_360.0), ("7", "Kilometers", 72.0 / 0.0254 * 1e3)] { + let i = info(&drawing(&[(9, "$INSUNITS"), (70, code)], &[], &[], LINE)).unwrap(); + assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name)); + assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale); + } let survey_in = open(&drawing(&[(9, "$INSUNITS"), (70, "22")], &[], &[], LINE), &ImportOptions::default()).document; assert!((survey_in.artboards[0].rect.width() - 7200.0144000288).abs() < 1e-6, "{:?}", survey_in.artboards[0].rect); let imperial = info(&drawing(&[(9, "$MEASUREMENT"), (70, "0")], &[], &[], LINE)).unwrap(); diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 75a5fdc2a5..e7c613bf56 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -197,6 +197,11 @@ mod tests { assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary"); assert_eq!(Harmony::HighContrast3.id(), "highContrast3"); assert_eq!(parse("square"), None); + // The labels are written here and the ids come from the framework: a few shown labels read + // back as their rules. + for h in [Harmony::LeftComplement, Harmony::Monochromatic, Harmony::Compound2, Harmony::Pentagram] { + assert_eq!(parse(label(h)), Some(h), "{}", label(h)); + } } #[test] From 206fc9684f2e41266d3ae851b52105f9f427b21f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 21:34:29 -0800 Subject: [PATCH 26/28] Tests: remove the fallback size test's folder when the test panics The folder sits in a guard that removes it on drop, so a panic in the write or the search no longer leaves the 41 MiB file in the temporary directory. The normal path still removes it explicitly and fails on an error. --- crates/text/src/fontdb.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/text/src/fontdb.rs b/crates/text/src/fontdb.rs index 30b95066b5..78ff31af5f 100644 --- a/crates/text/src/fontdb.rs +++ b/crates/text/src/fontdb.rs @@ -201,14 +201,21 @@ mod alias_tests { let info = FileFontInfo { family: "Fallback Size Limit Regression".into(), style: "Regular".into(), ..Default::default() }; let glyph = FileGlyph { ch: pua, outline: kurbo::Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 }; let font = build_file_font(&info, &[glyph]).unwrap(); + // Removes the folder when dropped, so a panic part way through does not leave the 41 MiB file behind. + struct TempDir(std::path::PathBuf); + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } let search = |name: &str, bytes: &[u8]| { - let dir = std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir(&dir).unwrap(); - std::fs::write(dir.join("Pua.ttf"), bytes).unwrap(); - let db = FontDb::with_font_dirs(vec![dir.clone()]); + let dir = TempDir(std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir(&dir.0).unwrap(); + std::fs::write(dir.0.join("Pua.ttf"), bytes).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.0.clone()]); let found = db.system_fallback(pua); - std::fs::remove_dir_all(&dir).unwrap(); + std::fs::remove_dir_all(&dir.0).unwrap(); found }; assert!(search("small", &font), "a font at its own length is loaded"); From 3d69c8d49ac66a54652ff08053a12049d465d348 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 22:54:26 -0800 Subject: [PATCH 27/28] Scripts: removeAll cannot leave an image first in a group named Image Trace textFrames.removeAll() and the removeAll() of a group's pageItems, groupItems and compoundPathItems checked only clip groups whose mask they release. Deleting the type or art below an image in an ordinary group named Image Trace left the image first, so the group was read as a tracing and the image dropped out of pageItems. Both now throw "Only Image Trace can make a tracing" and delete nothing, checking the whole set being deleted at once. --- crates/engine/src/script/dom.rs | 13 +++++ crates/engine/src/script/dom/layers.rs | 4 ++ crates/engine/src/script/dom/text.rs | 3 +- crates/engine/src/tests/script_dom_tracing.rs | 51 +++++++++++++++++++ docs/mcp.md | 4 +- 5 files changed, 73 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4d87c3b8a8..2ad7469dbb 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -3049,6 +3049,19 @@ fn makes_tracing(d: &Document, parent: NodeId, id: NodeId, at: Option) -> } } +/// Whether deleting every object in `removed` together would leave one of their parents, an +/// ordinary group named as a tracing, with an image first in it, which would make it a tracing. +pub(super) fn removal_makes_tracing(d: &Document, removed: &[NodeId]) -> bool { + let going: std::collections::HashSet = removed.iter().copied().collect(); + let mut parents: Vec = removed.iter().filter_map(|i| d.parent_of(*i)).collect(); + parents.sort_unstable_by_key(|p| p.0); + parents.dedup(); + parents + .into_iter() + .filter(|p| 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(_)))) +} + /// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place. fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> { let index = with_doc(h, doc, |_, st| { diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 0b1b1f0e57..3f40ad4c11 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -855,6 +855,10 @@ 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}" ))); } + // Deleting the objects above an image in an ordinary group named as a tracing would make it one. + if with_doc(h, doc, |_, st| super::removal_makes_tracing(&st.doc, &ids)) { + return Err(HostError::Error(super::NOT_A_TRACING.into())); + } 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/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 6237af9179..b14b065c84 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1542,7 +1542,8 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { // Type that clips a group or layer releases its mask, so the object above it is not made // the clipping path. let released = super::masks_cleared_by(&st.doc, &ids); - let tracing = super::release_makes_tracing(&st.doc, &released, &ids); + // So would deleting the type above an image in an ordinary group named as a tracing. + let tracing = super::release_makes_tracing(&st.doc, &released, &ids) || super::removal_makes_tracing(&st.doc, &ids); Ok::<_, HostError>((ids, refused, on_locked, released, tracing)) })?; if !refused.is_empty() { diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 0f6851d342..403510d73c 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -1242,6 +1242,57 @@ fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tr let _ = std::fs::remove_dir_all(base); } +/// `textFrames.removeAll()` and `groupItems.removeAll()` on an ordinary group named as a tracing +/// refuse to leave an image first in it, before the document changes, and delete when another +/// object stays first. +#[test] +fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() { + let base = folder("remove-all-trace-name"); + let refused = json!("Only Image Trace can make a tracing"); + for (under, call) in [ + ("var u = d.textFrames.add(); u.contents = 'Under';", "g.textFrames.removeAll();"), + ("d.selection = [d.pathItems.rectangle(50, 50, 5, 5)]; vc.run('object.group'); var u = d.pageItems[0];", "g.groupItems.removeAll();"), + ] { + let (mut s, _) = session(&base, false); + // The group holds the type or group at the bottom and the image above it. + log( + &mut s, + &base, + &format!( + "var d = app.activeDocument; var p = d.pathItems.rectangle(10, 10, 20, 20); d.selection = [p]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; {under} u.move(g, ElementPlacement.PLACEATEND);\ + d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING); p.remove();" + ), + ); + 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, g = d.pageItems[0], m = ''; try {{ {call} m = 'done'; }} catch (e) {{ m = e.message; }} vc.log(m); vc.log(g.typename);" + ), + ); + assert_eq!(out, [refused.clone(), json!("GroupItem")], "{call}"); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{call}"); + assert_eq!(undo_steps(&s), steps, "{call}"); + assert!(traces(&s).is_empty()); + } + // With a rectangle left first, the type goes and the group stays an ordinary group. + let (mut s, _) = session(&base, false); + let out = log( + &mut s, + &base, + "var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\ + var g = d.pageItems[0]; g.name = 'Image Trace'; var t = d.textFrames.add(); t.contents = 'Over';\ + t.move(g, ElementPlacement.PLACEATBEGINNING); d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);\ + g.textFrames.removeAll(); vc.log(g.textFrames.length); vc.log(g.pageItems.length); vc.log(g.typename);", + ); + assert_eq!(out, [json!(0), json!(2), json!("GroupItem")]); + assert!(traces(&s).is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object /// its trace did not make, before the document changes. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1abf72fbba..30ac0bfb82 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3246,7 +3246,9 @@ through `$`: delete the clipping path of a clip group or clipping layer also release that clipping mask in the same undo step, so the object above the clipping path does not become the new clipping path; a deletion that leaves the clipping path keeps the mask. When the released group is named `Image Trace` and an image would be left at its bottom, they - throw `Only Image Trace can make a tracing` and delete nothing. The `removeAll()` of a layer's or group's + throw `Only Image Trace can make a tracing` and delete nothing. `textFrames.removeAll()` and the `removeAll()` of a + group's `pageItems`, `groupItems` or `compoundPathItems` throw the same error and delete nothing when they would + leave an image at the bottom of an ordinary group named `Image Trace`. The `removeAll()` of a layer's or group's `pageItems`, and of any `groupItems` or `compoundPathItems`, does not release a mask: it throws as described above. 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 From 5e68ecd7c8c9d438a82f4f22f9b59b1f34cc25f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 23:39:52 -0800 Subject: [PATCH 28/28] macOS: closing Preferences no longer crashes on Macs with a Touch Bar Clicking OK or Cancel in Preferences ended the app with an uncaught NSRangeException from -[_NSTouchBarFinderObservation invalidate] whenever the Touch Bar server runs (any Mac with a Touch Bar). When a window closes, accesskit_macos 0.27.1 put the content view's original class back, which removed the key-value observing subclass AppKit's Touch Bar support had installed on the view. AppKit then failed to remove its observer. accesskit_macos 0.27.2 leaves the class alone when key-value observing has subclassed the view (AccessKit/accesskit#835). Cargo.lock moves to it, with accesskit 0.25.2 and accesskit_consumer 0.39.2, which it requires. Fixes #10473 --- Cargo.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d0216e2962..ff70d04bdf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "accesskit" -version = "0.25.1" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" dependencies = [ "uuid", ] @@ -27,9 +27,9 @@ dependencies = [ [[package]] name = "accesskit_consumer" -version = "0.39.1" +version = "0.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" dependencies = [ "accesskit", "hashbrown 0.17.1", @@ -51,9 +51,9 @@ dependencies = [ [[package]] name = "accesskit_macos" -version = "0.27.1" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" +checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84" dependencies = [ "accesskit", "accesskit_consumer",