From 630716c81c3fc71ed7fcb04b4c14635b9d148234 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:32:57 -0800 Subject: [PATCH 1/3] Scripts: PageItem.blendingMode reads and sets an object's blending mode A page item's blendingMode gives the object's own blend mode as a BlendModes value, and assigning one sets it through object.setProps. The global BlendModes holds the 16 members the scripting constants page lists; COLORBLEND and SATURATIONBLEND set the Color and Saturation modes. Any other value throws "blendingMode needs a BlendModes value" and changes nothing. Assigning the mode the object has adds no undo step. An object in a hidden or locked layer refuses the change with "Cannot edit", as opacity does. --- crates/engine/src/script/dom.rs | 66 +++++++++++++++++-- crates/engine/src/tests/script_dom.rs | 59 +++++++++++++---- .../tests/it/script_host_vs_scriptcheck.rs | 7 +- docs/mcp.md | 19 +++--- docs/target-app-parity.md | 2 +- 5 files changed, 126 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 39c740cb2e..b94cc3efc1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -42,11 +42,12 @@ //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. //! - Members the help pages list that are not here yet throw an error that says so. -//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an -//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change -//! nothing, even for the value the object has. The exception is `opacity` given the value the -//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps -//! another opacity it would still change the graph, so it is refused too. Its `name` and `note` +//! - Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or +//! `height` to an object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` +//! and change nothing, even for the value the object has. The exception is `opacity` or +//! `blendingMode` given the value the object has when that changes nothing; on a graph's mark or +//! label whose series or kind keeps another opacity or blend mode it would still change the graph, +//! so it is refused too. Its `name` and `note` //! still change. An object that is hidden or locked itself, or is in a hidden or locked group, //! takes them. //! - `name` and `note` take a number or a Boolean as the text `String(value)` gives. @@ -60,6 +61,7 @@ use std::rc::Rc; use std::sync::Arc; use serde_json::{Value, json}; +use vectorcraft_color::BlendMode; use vectorcraft_geom::{Point, Rect}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; @@ -1600,6 +1602,56 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) } +/// The members of `BlendModes` with the blend mode each one names. +const BLEND_MODES: [(&str, BlendMode); 16] = [ + ("COLORBLEND", BlendMode::Color), + ("COLORBURN", BlendMode::ColorBurn), + ("COLORDODGE", BlendMode::ColorDodge), + ("DARKEN", BlendMode::Darken), + ("DIFFERENCE", BlendMode::Difference), + ("EXCLUSION", BlendMode::Exclusion), + ("HARDLIGHT", BlendMode::HardLight), + ("HUE", BlendMode::Hue), + ("LIGHTEN", BlendMode::Lighten), + ("LUMINOSITY", BlendMode::Luminosity), + ("MULTIPLY", BlendMode::Multiply), + ("NORMAL", BlendMode::Normal), + ("OVERLAY", BlendMode::Overlay), + ("SATURATIONBLEND", BlendMode::Saturation), + ("SCREEN", BlendMode::Screen), + ("SOFTLIGHT", BlendMode::SoftLight), +]; + +fn item_blending_mode(h: &Host, a: &[Data]) -> Answer { + read_item(h, a, |_, n| { + let name = BLEND_MODES.iter().find(|(_, m)| *m == n.blend).map_or("NORMAL", |(name, _)| name); + Ok(text(format!("BlendModes.{name}"))) + }) +} + +/// `blendingMode = BlendModes.`: the object's own blend mode, as `object.setProps` sets it. +/// The mode the object already has may be assigned while its layer is hidden or locked, unless it +/// would still replace the blend mode a graph keeps for the item's series or kind. +fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer { + let mode = match arg(a, 1) { + Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode), + _ => None, + }; + let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?; + let item = this_item(h, a)?; + let (same, keeps_other) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let same = d.node(item.id).is_some_and(|n| n.blend == mode); + let keeps_other = + crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]); + (same, keeps_other) + }); + if !same || keeps_other { + refuse_in_closed_layer(h, item)?; + } + set_props(h, a, |_| false, json!({"blend": mode.label()})) +} + fn item_selected(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)))) @@ -2077,6 +2129,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect(); + realm.define_host_object("BlendModes", blend_modes)?; let l = link; let mut application = named(vec![ ("typename", typename_of("Application")), @@ -2161,6 +2215,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("locked", property(l, item_locked, item_set_locked)), ("selected", property(l, item_selected, item_set_selected)), ("opacity", property(l, item_opacity, item_set_opacity)), + ("blendingMode", property(l, item_blending_mode, item_set_blending_mode)), ("position", property(l, item_position, item_set_position)), ("left", property(l, item_left, item_set_left)), ("top", property(l, item_top, item_set_top)), @@ -2180,7 +2235,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), page_item.extend( [ "artworkKnockout", - "blendingMode", "isIsolated", "layer", "pixelAligned", diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..07131a18e9 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -278,6 +278,40 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(undo_steps(&s), steps + 1); } +/// `blendingMode` reads and sets the object's own blend mode as a `BlendModes` value; the mode it +/// already has adds no undo step, and any other value throws and changes nothing. +#[test] +fn blending_mode_reads_and_sets_the_objects_blend_mode() { + let (mut s, a, b) = doc(); + let blend = |s: &Session, id: NodeId| s.active().unwrap().doc.node(id).unwrap().blend; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var i = app.activeDocument.pageItems[1]; vc.log(i.blendingMode);\ + i.blendingMode = BlendModes.MULTIPLY; vc.log(i.blendingMode);\ + vc.log([i.hasOwnProperty('blendingMode'), BlendModes.SATURATIONBLEND, BlendModes.COLORBLEND]);", + ); + assert_eq!(out[..2], [json!("BlendModes.NORMAL"), json!("BlendModes.MULTIPLY")]); + assert_eq!(out[2], json!([true, "BlendModes.SATURATIONBLEND", "BlendModes.COLORBLEND"])); + assert_ne!(blend(&s, a), blend(&s, b), "only the assigned object changed"); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let (before, steps) = (blend(&s, a), undo_steps(&s)); + log(&mut s, "var i = app.activeDocument.pageItems[1]; i.blendingMode = BlendModes.MULTIPLY; i.blendingMode = i.blendingMode;"); + assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "the mode the object has adds no step"); + // Two modes the help page names with a suffix set the modes the Transparency panel calls Color + // and Saturation. + log(&mut s, "var p = app.activeDocument.pageItems; p[1].blendingMode = BlendModes.COLORBLEND; p[0].blendingMode = BlendModes.SATURATIONBLEND;"); + assert_eq!((blend(&s, a).label(), blend(&s, b).label()), ("Color", "Saturation")); + let (before, steps) = (blend(&s, a), undo_steps(&s)); + for value in + ["'BlendModes.SCREEN '", "'MULTIPLY'", "'Multiply'", "'BlendModes.multiply'", "'BlendModes.NOPE'", "5", "null", "ZOrderMethod.BRINGTOFRONT"] + { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[1].blendingMode = {value};")); + assert!(e.contains("blendingMode needs a BlendModes value"), "{value}: {e}"); + assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "{value}"); + } +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -876,13 +910,13 @@ fn a_startup_preset_alone_gives_its_first_size() { fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] + ["app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); // A deleted item or an earlier run's document is stale first. - let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;"); + let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;"); assert!(e.contains("Stale page item"), "{e}"); run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap(); let e = failure(&mut s, "#targetengine keep\nd.layers;"); @@ -1407,7 +1441,7 @@ fn unsupported_members_say_so() { /// A script that names each visible selected object after its place in `app.selection`, testing /// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not -/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is +/// available yet, such as `isIsolated`, is read only when `hasOwnProperty` reports it, so it is /// never read. const NAME_PICKED: &str = "\ var picked = app.selection, k = picked.length, named = 0;\ @@ -1415,7 +1449,7 @@ const NAME_PICKED: &str = "\ while (k--) {\ var obj = picked[k];\ var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\ - if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\ + if (obj.hasOwnProperty('isIsolated') && obj.isIsolated) usable = false;\ if (usable) { obj.name = 'picked ' + k; named += 1; }\ }\ if (picked.length && named < picked.length) alert('Some objects were skipped.');"; @@ -1494,9 +1528,9 @@ fn page_items_report_their_available_members_as_their_own() { vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\ Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\ app.hasOwnProperty('activeDocument')]);\ - vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ + vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\ p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\ - vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);", + vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);", ); assert_eq!(out[0], json!([true, true, true, true, true, true, true])); // Members that are not available yet, unknown names and inherited ones are not the object's own. @@ -1625,7 +1659,7 @@ fn a_collection_read_with_a_name_gives_the_named_object() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); } -/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or +/// `opacity`, `blendingMode`, `hidden`, `locked` and the position and size setters on an object in a hidden or /// locked layer throw and the run changes nothing, while its name and note still change; an object /// that is hidden or locked itself takes them. #[test] @@ -1645,6 +1679,7 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { // `hidden` and `locked` are refused even when the value is the one the object has. for set in [ "opacity = 50", + "blendingMode = BlendModes.MULTIPLY", "hidden = true", "hidden = false", "locked = true", @@ -1666,9 +1701,9 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let out = log( &mut s, "var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\ - vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';", + c.blendingMode = c.blendingMode; vc.log([c.name, c.note, c.opacity, c.blendingMode]); c.name = 'closed'; c.note = '';", ); - assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}"); + assert_eq!(out, vec![json!(["renamed", "n", 100, "BlendModes.NORMAL"])], "{on}"); s.execute("object.setProps", &off).unwrap(); } s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); @@ -1676,9 +1711,11 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() { let out = log( &mut s, "var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\ - vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);", + p.getByName('locked').blendingMode = BlendModes.SCREEN; p.getByName('free').blendingMode = BlendModes.DARKEN;\ + vc.log([p.getByName('locked').opacity, p.getByName('free').opacity, p.getByName('locked').blendingMode,\ + p.getByName('free').blendingMode]);", ); - assert_eq!(out, vec![json!([50, 40])]); + assert_eq!(out, vec![json!([50, 40, "BlendModes.SCREEN", "BlendModes.DARKEN"])]); } /// `name` takes a number or a Boolean as the text `String` gives it, and nothing else. diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 4368ce29b7..c92729083a 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -75,7 +75,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ + "activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= ZOrderMethod", ), @@ -117,6 +117,11 @@ const INSIDE: &[(&str, &str)] = &[ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ( + "BlendModes.", + "COLORBLEND COLORBURN COLORDODGE DARKEN DIFFERENCE EXCLUSION HARDLIGHT HUE LIGHTEN LUMINOSITY MULTIPLY NORMAL \ + OVERLAY SATURATIONBLEND SCREEN SOFTLIGHT", + ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), diff --git a/docs/mcp.md b/docs/mcp.md index e963a4bd42..c938b3843c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2702,7 +2702,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds 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 + 100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"` + (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value + throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the visible bounds), `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)` @@ -2715,11 +2717,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, - `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer - throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such - an object throws `Cannot edit` too. The one exception is `opacity` given the value the object already has, which - changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity, that - value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an + `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or + locked layer throws `Cannot edit` and changes nothing, even when the value is the one the object has, and + `zOrder()` on such an object throws `Cannot edit` too. The one exception is `opacity` or `blendingMode` given the + value the object already has, which changes nothing and does not throw; on a graph's mark or label whose series or + kind keeps another opacity or blend mode, that value would still change the graph, so it throws `Cannot edit` as + well. Its `name` and `note` still change, and an object that is hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds @@ -2729,7 +2732,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a - `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, + `RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `BlendModes`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and `DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`. `pageItems` lists the art topmost first, as the example on @@ -2770,7 +2773,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and + Document and PageItem pages list, such as `Document.layers`, `PageItem.isIsolated`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b5346c5af7..5f037cf900 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`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). Layers, paths, type and the other classes are not there yet. `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`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 63706325221f6072b18024fe1b857a697de48d6b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:27:12 -0800 Subject: [PATCH 2/3] Scripts: the blendingMode test catches each refused value in the script Each invalid assignment is now caught inside the script, and the mode is read right after it, so a setter that changed the mode before throwing fails the test instead of being hidden by the run's rollback. --- crates/engine/src/tests/script_dom.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 07131a18e9..ae7faace45 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -306,8 +306,19 @@ fn blending_mode_reads_and_sets_the_objects_blend_mode() { for value in ["'BlendModes.SCREEN '", "'MULTIPLY'", "'Multiply'", "'BlendModes.multiply'", "'BlendModes.NOPE'", "5", "null", "ZOrderMethod.BRINGTOFRONT"] { - let e = failure(&mut s, &format!("app.activeDocument.pageItems[1].blendingMode = {value};")); + // The error is caught in the script, so the run does not roll back and the mode read right + // after it is the one the setter left. + let out = log( + &mut s, + &format!( + "var i = app.activeDocument.pageItems[1], e = '';\ + try {{ i.blendingMode = {value}; }} catch (x) {{ e = String(x); }}\ + vc.log(e); vc.log(i.blendingMode);" + ), + ); + let e = out[0].as_str().unwrap_or_default(); assert!(e.contains("blendingMode needs a BlendModes value"), "{value}: {e}"); + assert_eq!(out[1], json!("BlendModes.COLORBLEND"), "{value}"); assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "{value}"); } } From 3ac7c97f091d7b4878ba71e3de4767afa3f5f60a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:43:20 -0800 Subject: [PATCH 3/3] Scripts: graph opacity and blend checks read only the edited object's graph The checks behind `opacity` and `blendingMode` assignments, and the captures `object.setProps` runs for object opacity and blend mode, now find an object's graph series or label kind through its parents instead of walking the whole document. Assigning modes to many objects no longer costs a pass over the document for each one. A new test covers a blend mode a graph mark or axis label already has, in an open layer and in a hidden or locked one. --- crates/engine/src/cmd/graph/series.rs | 58 +++++++++++++++++++++------ crates/engine/src/tests/script_dom.rs | 46 +++++++++++++++++++++ 2 files changed, 91 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index c79f795b50..3ea811392d 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -576,23 +576,36 @@ struct ObjectOpacity { knockout_shape: bool, } +/// The series `id` belongs to when it is a graph series group or a path directly in one, as [`series_members`] finds +/// it. Looked up through its parents, with no pass over the document. +fn series_group_or_mark(doc: &Document, id: NodeId) -> Option { + let node = doc.node(id)?; + let chain = doc.ancestry(id)?; + let parent = doc.node(*chain.iter().rev().nth(1)?)?; + let in_graph = |group: &Node, graph: &Node| { + let index = group.extras().series_index.and_then(|i| usize::try_from(i).ok())?; + graph.extras().graph.as_deref().filter(|spec| index < series_count(spec)).map(|_| SeriesRef { graph: graph.id, group: group.id, index }) + }; + if let Some(r) = in_graph(node, parent) { + return Some(r); + } + // Only the paths the graph draws again, not the copy of a graph design. + if !matches!(node.kind, NodeKind::Path { .. }) { + return None; + } + in_graph(parent, doc.node(*chain.iter().rev().nth(2)?)?) +} + /// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object -/// transparency of each of `edited` that is one of those, in order. +/// transparency of each of `edited` that is one of those, in order. Each object is looked up through its parents +/// ([`series_group_or_mark`]), so an edit of a few objects does not read the rest of the document. fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> { - if edited.is_empty() { - return Vec::new(); - } - let members = series_members(doc); - if members.is_empty() { - return Vec::new(); - } edited .iter() .filter_map(|id| { - let r = members.get(id)?; + let r = series_group_or_mark(doc, *id)?; let group = r.group == *id; - // Only the series group and the paths the graph draws again, not the copy of a graph design. - let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?; + let node = doc.node(*id)?; let mut look = ObjectOpacity { opacity: (node.opacity < 1.0).then_some(node.opacity), blend: (node.blend != BlendMode::Normal).then_some(node.blend), @@ -675,6 +688,25 @@ fn graph_labels(doc: &Document) -> HashMap { out } +/// The graph and kind of generated label `id`, as [`graph_labels`] finds it. Only the graphs among its parent and +/// grandparent are read, with no pass over the document; `own` keeps each graph's labels read so far. +fn graph_label_of(doc: &Document, id: NodeId, own: &mut HashMap>) -> Option<(NodeId, Role)> { + if !doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { + return None; + } + let chain = doc.ancestry(id)?; + // The nearer graph first: [`graph_labels`] visits it later, so its entry is the one kept. + for graph in chain.iter().rev().skip(1).take(2) { + let Some(n) = doc.node(*graph) else { continue }; + let Some(spec) = n.extras().graph.as_deref() else { continue }; + let labels = own.entry(*graph).or_insert_with(|| own_labels(n, spec).into_iter().collect()); + if let Some(role) = labels.get(&id) { + return Some((*graph, *role)); + } + } + None +} + /// The generated labels of graph `n` (with spec `g`) and what each shows, as [`graph_labels`] finds them. fn own_labels(n: &Node, g: &GraphSpec) -> Vec<(NodeId, Role)> { let mut out = vec![]; @@ -1725,9 +1757,9 @@ fn label_rows_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role, Option)> = vec![]; - for (&(g, role), n) in ids.iter().rev().filter_map(|id| Some((labels.get(id)?, doc.node(*id)?))) { + for ((g, role), n) in ids.iter().rev().filter_map(|id| Some((graph_label_of(doc, *id, &mut own)?, doc.node(*id)?))) { if !picked.iter().any(|(pg, pr, _)| *pg == g && *pr == role) { picked.push((g, role, label_rows(n))); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ae7faace45..f535d65ebb 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -260,6 +260,52 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { assert_eq!(kept(&s), None); } +/// A blend mode a graph mark or axis label already has still replaces the blend mode another object +/// of its series or kind left on the graph, and is refused in a hidden or locked layer. +#[test] +fn a_blend_mode_a_graph_mark_or_label_already_has_replaces_the_one_the_graph_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let spec = |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().clone(); + let kept_mark = |s: &Session| spec(s).series_paints.first().and_then(|p| p.blend); + let kept_label = |s: &Session| spec(s).label_styles.values_rows.as_ref().and_then(|r| r.paint.blend); + let graph = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = graph.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + let marks: Vec = group.children().unwrap().iter().map(|m| m.id).collect(); + let axes = graph.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone(); + // The value axis numbers come first among the Axes group's labels. + let labels: Vec = axes.children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| c.id).collect(); + s.execute("object.setProps", &json!({"id": marks[0].0, "blend": "Multiply"})).unwrap(); + s.execute("object.setProps", &json!({"id": labels[0].0, "blend": "Screen"})).unwrap(); + let both = (Some(vectorcraft_color::BlendMode::Multiply), Some(vectorcraft_color::BlendMode::Screen)); + assert_eq!((kept_mark(&s), kept_label(&s)), both); + s.execute("object.setProps", &json!({"id": marks[1].0, "name": "mark"})).unwrap(); + s.execute("object.setProps", &json!({"id": labels[1].0, "name": "label"})).unwrap(); + let layer = s.active().unwrap().doc.layers[0].id; + for (on, off) in [ + (json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})), + (json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})), + ] { + s.execute("object.setProps", &on).unwrap(); + for name in ["mark", "label"] { + let steps = undo_steps(&s); + let e = failure(&mut s, &format!("var m = app.activeDocument.pageItems.getByName('{name}'); m.blendingMode = m.blendingMode;")); + assert!(e.contains("Cannot edit"), "{on} {name}: {e}"); + assert_eq!((kept_mark(&s), kept_label(&s)), both, "{on} {name}"); + assert_eq!(undo_steps(&s), steps, "{on} {name}"); + } + s.execute("object.setProps", &off).unwrap(); + } + log( + &mut s, + "var p = app.activeDocument.pageItems; p.getByName('mark').blendingMode = BlendModes.NORMAL; p.getByName('label').blendingMode = BlendModes.NORMAL;", + ); + assert_eq!((kept_mark(&s), kept_label(&s)), (None, None)); +} + /// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. #[test] fn assigning_the_reported_opacity_changes_nothing() {