From 6db0f6c1adef609bba16c8eec4ce0a37e178d2ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:15:47 -0800 Subject: [PATCH] Scripts: visibility variables on embedded images, data sets kept after a no-op import - variable.setBinding refuses an embedded image only for an image variable, so a script can bind an embedded image's visibility. - A Dataset object stays usable after dataset.import, variable.loadLibrary or variable.import leaves the document's data sets as they were, or the import is put back; it goes stale only when the data sets change. - script.check reports a document's exportVariables as filesWritten and file.write, and the script host test lists the variable and data set names the host adds. Docs: docs/mcp.md. --- crates/engine/src/cmd/variablecmds.rs | 2 +- crates/engine/src/script/dom.rs | 10 +++++++-- crates/engine/src/script/dom/variables.rs | 22 ++++++++++++++----- crates/engine/src/script/mod.rs | 3 ++- crates/engine/src/tests/script_variables.rs | 19 ++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 18 +++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 2 +- crates/scriptcheck/src/catalog.rs | 3 +++ crates/scriptcheck/src/tests.rs | 8 +++++++ docs/mcp.md | 7 +++--- 10 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index fdd4231dc3..28022865e6 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -500,7 +500,7 @@ fn set_binding(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("variable `{name}` is a {} variable, and this slot takes a {} variable", have.label(), kind.label()))); } check_bindable(doc, &[id], kind, C)?; - if matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { + if kind == VariableKind::Image && matches!(doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()) { return Err(bad(C, format!("node {} is an embedded image, and an image variable drives only a linked image", id.0))); } } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a7303cf4e6..7e46779791 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -42,9 +42,15 @@ mod variables; pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE}; +/// What [`after_command`] compares with, taken before each command a script runs +/// ([`variables::before_command`]). +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + variables::before_command(h, id) +} + /// After each command a script runs ([`variables::after_command`]). -pub(super) fn after_command(h: &Host, id: &str) { - variables::after_command(h, id); +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { + variables::after_command(h, before); } /// The error for a member read or called with no document open. diff --git a/crates/engine/src/script/dom/variables.rs b/crates/engine/src/script/dom/variables.rs index 270a7cfc08..d36c9f1f45 100644 --- a/crates/engine/src/script/dom/variables.rs +++ b/crates/engine/src/script/dom/variables.rs @@ -46,7 +46,7 @@ use super::{ Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, function, get, handle_of, item_of, item_ref, method, named, num, on_doc, property, text, typename, whole, with_doc, }; -use crate::doc::{Node, Variable, VariableKind}; +use crate::doc::{DataSet, Node, Variable, VariableKind}; use crate::file_access::Access; /// The error for a `Variable` whose variable left the document, or that came from an earlier run. @@ -138,16 +138,28 @@ pub(super) struct Handles { seen: RefCell>, } +/// The data sets of the active document before a command that may replace them (an import), while +/// the run holds a `Dataset`; `None` for any other command. +pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec)> { + if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() { + return None; + } + let s = h.session.try_borrow().ok()?; + s.active().map(|st| (st.uid, st.doc.variables.datasets.clone())) +} + /// After each command a script runs: the objects whose variable or data set it removed stop -/// working, so one made again under the same name does not bring them back. A command that replaces -/// the data sets (an import) stops every `Dataset` of its document. -pub(super) fn after_command(h: &Host, id: &str) { +/// working, so one made again under the same name does not bring them back. An import that leaves +/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset` +/// of that document, also when the new data sets reuse the names; an import that failed, was put +/// back or left the data sets as they were stops none. +pub(super) fn after_command(h: &Host, before: Option<(u64, Vec)>) { let hs = &h.dom.vars; if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() { return; } let Ok(s) = h.session.try_borrow() else { return }; - let replaced = matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import").then(|| s.active().map(|st| st.uid)).flatten(); + let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid)); let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect(); let changed: HashSet = { let seen = hs.seen.borrow(); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0780a34e98..39acd9897b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1313,6 +1313,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let params = params.clone(); let session = host.session.clone(); let started = clock(); + let before = dom::before_command(host, &id); let r = { let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) @@ -1346,7 +1347,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } - dom::after_command(host, &id); + dom::after_command(host, before); crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_variables.rs b/crates/engine/src/tests/script_variables.rs index e60afb03d2..5ff2301bbf 100644 --- a/crates/engine/src/tests/script_variables.rs +++ b/crates/engine/src/tests/script_variables.rs @@ -188,6 +188,13 @@ fn an_embedded_image_cannot_take_an_image_variable() { let e = failure(&mut s, "var d = app.activeDocument; vc.log(d.pageItems[0].typename); d.pageItems[0].contentVariable = d.variables[0];"); assert!(e.contains("embedded image"), "{e}"); assert!(s.active().unwrap().doc.variables.bindings.is_empty()); + // Its visibility still takes a visibility variable. + s.execute("variable.define", &json!({"name": "shown", "kind": "visibility"})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument; d.pageItems[0].visibilityVariable = d.variables.getByName('shown'); vc.log(d.pageItems[0].visibilityVariable.name);", + ); + assert_eq!(out, vec![json!("shown")]); } #[test] @@ -259,6 +266,18 @@ fn a_data_set_object_goes_stale_when_an_import_replaces_the_rows() { assert!(e.contains("Stale data set"), "{e}"); } +#[test] +fn an_import_that_leaves_the_data_sets_as_they_were_keeps_the_data_set_objects() { + let (mut s, t, _) = doc(); + s.execute("variable.define", &json!({"name": "title", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "title", "ids": [t.0]})).unwrap(); + s.execute("dataset.import", &json!({"csv": "title\nNew"})).unwrap(); + let out = log(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nNew'}); vc.log(x.name);"); + assert_eq!(out.len(), 1, "{out:?}"); + let e = failure(&mut s, "var x = app.activeDocument.dataSets[0]; vc.run('dataset.import', {csv: 'title\\nOther'}); x.name;"); + assert!(e.contains("Stale data set"), "{e}"); +} + #[test] fn variables_locked_refuses_new_variables_but_not_bindings() { let (mut s, _, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..4519f35c5e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,6 +37,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), + ("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -70,6 +71,23 @@ const INSIDE: &[(&str, &str)] = &[ "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ getRelativeURI modified name parent path relativeURI resolve selectDlg toString", ), + // Variables and data sets. `importVariables` reads the library file it is given. + ("", "Dataset Datasets Variable VariableKind Variables"), + ("VariableKind.", "GRAPH IMAGE TEXTUAL Unknown VISIBILITY"), + ("Variables.", "prototype"), + ("Variables.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Variable.", "prototype"), + ("Variable.prototype.", "constructor kind kind= name name= pageItems parent remove typename"), + ("Datasets.", "prototype"), + ("Datasets.prototype.", "add constructor getByName index length parent removeAll typename"), + ("Dataset.", "prototype"), + ("Dataset.prototype.", "constructor display name name= parent remove typename update"), + ("Document.prototype.", "activeDataset activeDataset= dataSets importVariables variables variablesLocked variablesLocked="), + ("PageItem.prototype.", "visibilityVariable visibilityVariable="), + ("GraphItem.prototype.", "contentVariable contentVariable="), + ("PlacedItem.prototype.", "contentVariable contentVariable="), + ("RasterItem.prototype.", "contentVariable contentVariable="), + ("TextFrame.prototype.", "contentVariable contentVariable="), ]; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..eef0fb77c1 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -301,7 +301,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if file && catalog::FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..940b1db4e0 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -72,6 +72,9 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; +// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportVariables"]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..1f4c9f3e70 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,14 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one. +#[test] +fn export_variables_writes_a_file() { + let r = report("var f = new File(p);\napp.activeDocument.importVariables(f);\napp.activeDocument.exportVariables(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 2d35d2d0b9..7d454966ce 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,9 +2558,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, - `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, - `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). + File object's `length`, `hidden` or `readonly` counts too, and so does a document's `exportVariables`), + `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), + `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` + (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, template literals and XML literals that aren't closed, brackets that don't match, syntax newer than ES3 and unknown directives) and notes on its text (bytes that aren't valid UTF-8, mixed line endings, and nesting deeper