mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
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.
This commit is contained in:
1 parent
90752660ad
commit
6db0f6c1ad
10 files changed
+81
-13
No files matched your search
@@ -500,7 +500,7 @@ fn set_binding(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<crate::doc::DataSet>)> {
|
||||
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<crate::doc::DataSet>)>) {
|
||||
variables::after_command(h, before);
|
||||
}
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
|
||||
@@ -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<Vec<(u64, u64)>>,
|
||||
}
|
||||
|
||||
/// 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<DataSet>)> {
|
||||
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<DataSet>)>) {
|
||||
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<u64> = {
|
||||
let seen = hs.seen.borrow();
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -530,6 +530,14 @@ fn the_scripts_own_platform_names_are_not_the_platforms() {
|
||||
assert_eq!(r.outside.iter().map(|o| o.id).collect::<Vec<_>>(), ["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::<Vec<_>>(), [("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]
|
||||
|
||||
+4
-3
@@ -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
|
||||
|
||||
Reference in new issue
Block a user