Scripts: open options with an importer, null export options and close checks for files that keep every artboard

- document.open refuses page, cropTo, pages and crop when a named importer reads the file (linkPages
  still uses the built-in reader).
- exportFile with explicit null options throws a TypeError for GIF, PNG8 and TIFF too.
- close(SaveOptions.SAVECHANGES) saves a modern .ai or .ait file and an SVG file with Preserve
  Editing whatever range was remembered; a range the save refuses still refuses.
- The script checker keeps a try statement's catch and finally, and an else after a nested
  do-while, inside the loop body; a line break after a label does not start a new statement; a
  this assignment in a function that hides a global clears the global's saved methods; and
  holder.d['saveAs'] = ... no longer counts as a write to d.
- docs/mcp.md describes which files keep every artboard on close.
This commit is contained in:
dotCooCoo committed 2026-11-30 03:36:01 -08:00
1 parent 3a8b8b8f25
commit f4c911d4d3
11 files changed
+215 -26

No files matched your search

+1 -1
View File
@@ -125,7 +125,7 @@ pub use screens::{
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list,
preset_rows as screen_preset_rows,
};
pub(crate) use svg::lost_artboards_warning as svg_lost_artboards_warning;
pub(crate) use svg::{lost_artboards_warning as svg_lost_artboards_warning, preserves_editing as svg_preserves_editing};
/// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file,
/// which holds the artboards its own options pick? An unknown version counts as one.
+11 -2
View File
@@ -1096,8 +1096,17 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result<Value> {
source(p, "document.open")?
}
};
if crate::file_access::in_script_command() && ["page", "cropTo"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
let pdf = detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait")) && !vectorcraft_pdf::is_postscript(&src.bytes);
let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
let (options, aliases) = (given(&["page", "cropTo"]), given(&["pages", "crop"]));
if crate::file_access::in_script_command() && (options || aliases) {
// An importer plug-in receives only the params, so it cannot apply the pages or the crop
// box; `linkPages` reads the file with the built-in reader before any importer.
let link_pages = p.get("linkPages").and_then(Value::as_bool) == Some(true);
let built_in = link_pages || super::importer::pick(src.name, &src.bytes, p)?.is_none();
let pdf = built_in
&& (!options
|| (detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait"))
&& !vectorcraft_pdf::is_postscript(&src.bytes)));
if !pdf {
return Err(bad("document.open", "PDF open options require a PDF file"));
}
+7 -2
View File
@@ -174,12 +174,17 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Docu
/// Editing Capabilities).
pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
let n = doc.artboards.len();
let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing);
(n > 1 && !preserved).then(|| {
(n > 1 && !preserves_editing(doc, p)).then(|| {
format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.")
})
}
/// Whether a save of `doc` as SVG with options `p` (flat or nested in `svg`) embeds the native
/// document (Preserve Editing Capabilities), which keeps every artboard.
pub(crate) fn preserves_editing(doc: &Document, p: &Value) -> bool {
plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing)
}
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
/// outside the read roots of the request being served (the open document keeps it).
fn native_attachment(doc: &Document) -> Vec<u8> {
+24 -7
View File
@@ -767,6 +767,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
},
Some(o) => match kind.options {
Some(class) => options_params(class, o)?,
None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())),
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
},
};
@@ -946,21 +947,37 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
return false;
}
let options = Value::Object(crate::cmd::fileio::remembered_save_options(st));
if matches!(st.format, "svg" | "svgz") && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() {
let svg = matches!(st.format, "svg" | "svgz");
if svg && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() {
return true;
}
if st.format == "pdf" && options.get("useArtboards") == Some(&Value::Bool(false)) {
return true;
}
if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait")
&& options.get("separateArtboards") == Some(&Value::Bool(true))
&& !crate::cmd::fileio::saves_legacy_ai(st.format, &options)
{
let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options);
if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy {
return false;
}
let count = st.doc.artboards.len();
let pick = serde_json::from_value::<crate::cmd::fileio::ArtboardPick>(options);
match pick.map_err(|e| e.to_string()).and_then(|p| p.resolve(count)) {
// A `.ai` file other than a legacy one saves with `range` "all" (a `range` that isn't text is
// left for the save to refuse).
let modern_ai = matches!(st.format, "ai" | "ait") && !legacy;
let mut effective = options.clone();
if let (true, Value::Object(o)) = (modern_ai, &mut effective)
&& o.get("range").is_none_or(|r| r.is_string() || r.is_null())
{
o.insert("range".into(), json!("all"));
}
let resolved = serde_json::from_value::<crate::cmd::fileio::ArtboardPick>(effective).map_err(|e| e.to_string()).and_then(|p| p.resolve(count));
// Such a `.ai` file, and an SVG file that carries the native document, keep every artboard;
// a pick the save refuses still refuses (an SVG save with `useArtboards: false` reads no pick).
if modern_ai {
return resolved.is_err();
}
if svg && crate::cmd::fileio::svg_preserves_editing(&st.doc, &options) {
return options.get("useArtboards") != Some(&Value::Bool(false)) && resolved.is_err();
}
match resolved {
Ok(None) => false,
Ok(Some(indices)) => (0..count).any(|i| !indices.contains(&i)),
Err(_) => true,
@@ -763,6 +763,10 @@ fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() {
let trim = s.active().unwrap().doc.artboards[0].rect;
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFCROPBOX}});"));
let crop = s.active().unwrap().doc.artboards[0].rect;
// Without the embedded document and without a crop box, the file opens at its trim box too.
s.execute("document.open", &json!({"path": file.to_string_lossy(), "editingData": false})).unwrap();
let implicit = s.active().unwrap().doc.artboards[0].rect;
assert_eq!((implicit.width(), implicit.height()), (trim.width(), trim.height()), "{extension}");
assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}");
assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}");
}
@@ -845,6 +849,9 @@ fn explicit_null_options_do_not_save_export_open_or_close() {
for call in [
format!("app.activeDocument.saveAs({f}, null);"),
format!("app.activeDocument.exportFile({f}, ExportType.SVG, null);"),
format!("app.activeDocument.exportFile({f}, ExportType.GIF, null);"),
format!("app.activeDocument.exportFile({f}, ExportType.PNG8, null);"),
format!("app.activeDocument.exportFile({f}, ExportType.TIFF, null);"),
format!("app.open({f}, null);"),
format!("app.open({f}, undefined, null);"),
"app.activeDocument.close(null);".into(),
@@ -1074,6 +1081,38 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() {
let _ = std::fs::remove_dir_all(base);
}
/// A `.ai` file saved without separate artboard files, and an SVG file that carries the native
/// document, keep every artboard whatever `range` names, so `close(SaveOptions.SAVECHANGES)` saves
/// them; a `range` the save refuses still refuses.
#[test]
fn closing_with_save_changes_saves_files_that_keep_every_artboard() {
let base = folder("closekeepall");
let dir = {
let mut s = session(&base);
data_folder(&mut s, &base)
};
for (name, options) in [("whole.ai", json!({"range": "2"})), ("native.svg", json!({"preserveEditing": true, "range": "1"}))] {
let mut s = session(&base);
data_folder(&mut s, &base);
let file = dir.join(name);
s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap();
let mut save = options.clone();
save["path"] = json!(file.to_string_lossy());
s.execute("document.save", &save).unwrap();
let before = std::fs::read(&file).unwrap();
logged(
&mut s,
&base,
"Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);",
);
assert!(s.documents().is_empty(), "{name}");
assert_ne!(std::fs::read(&file).unwrap(), before, "{name}");
s.execute("document.open", &json!({"path": file.to_string_lossy()})).unwrap();
assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "{name} keeps both artboards");
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() {
let base = folder("closeepsboards");
+27
View File
@@ -121,6 +121,33 @@ fn scripted_open_converts_importer_output_to_the_requested_color_space() {
let _ = std::fs::remove_dir_all(dir);
}
/// A script's PDF open options are refused for a file the named importer reads, which is given
/// only the params, even when the file's extension is a PDF one.
#[test]
fn scripted_pdf_open_options_are_refused_for_an_importer() {
let mut s = Session::new();
install(&mut s, &tpl::returning(&tpl::importer("test.scriptpdfoptions", r#"["ai"]"#, "{}"), RECT));
let dir = tmp_dir("scriptpdfoptions");
s.attach_script_data(dir.join("settings/Script Data"));
let file = dir.join("x.ai");
std::fs::write(&file, b"importer input").unwrap();
let script = dir.join("main.jsx");
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
for option in ["page: 1", "cropTo: 'media'", "pages: '1'", "crop: 'media'"] {
std::fs::write(
&script,
format!("Folder.userData; vc.run('document.open', {{path: {path}, importer: 'plugin.test.scriptpdfoptions', {option}}});"),
)
.unwrap();
let count = s.documents().len();
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()}));
let text = format!("{out:?}");
assert!(text.contains("PDF open options require a PDF file"), "{option}: {text}");
assert_eq!(s.documents().len(), count, "{option}");
}
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn an_importer_adds_a_read_only_format_while_it_is_installed() {
let mut s = Session::new();
+18 -1
View File
@@ -619,6 +619,8 @@ struct Analyzer<'s, 'a, 'l> {
file: Option<&'a str>,
/// The four significant tokens before this one, the latest first.
h: [Option<Sig<'s>>; 4],
/// The significant token before the four of [`Self::h`].
h4: Option<Sig<'s>>,
brackets: Brackets,
/// Nesting too deep to follow was reported: it is reported once.
deep: bool,
@@ -723,6 +725,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
acc,
file,
h: [None; 4],
h4: None,
brackets: Brackets::default(),
deep: false,
active: None,
@@ -853,6 +856,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.features(&t);
self.newer(&t);
self.module_check(&t);
self.h4 = self.h[3];
self.h = [Some(t), self.h[0], self.h[1], self.h[2]];
}
@@ -1401,7 +1405,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
let body = self.scopes.last().map_or(0, |s| s.depth);
let starts = before.is_none()
|| [";", "{", "}"].iter().any(|p| is(before, p))
|| (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do"));
// A line break after a label's `:` does not end the statement the label may be
// the body of (`if (c) l:` before the line).
|| (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do"));
let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body);
if self.objects.len() < self.acc.limits.nesting {
self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None });
@@ -1483,6 +1489,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
}
}
/// The global variable `name` is assigned as a property of `this`: as [`Self::reassigned_later`],
/// and when a function body's own variable hides it, the global's methods saved for the body's
/// end are no longer known either.
pub(super) fn reassigned_global(&mut self, name: &str) {
self.reassigned_later(name);
if let Some(saved) = self.scopes.iter_mut().find_map(|s| s.saved.get_mut(name)) {
saved.writer = 0;
}
}
/// Whether `name` is declared in the innermost function body (`var name`, `function
/// name`, a parameter).
fn declared_in_body(&self, name: &str) -> bool {
@@ -1736,6 +1752,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
self.var_depth = None;
self.conds.clear();
self.h = [None; 4];
self.h4 = None;
self.acc.steps = self.acc.steps.saturating_add(1);
let d = directives::parse(t.text);
let Some(name) = d.known else {
+27 -6
View File
@@ -163,6 +163,9 @@ enum Stage {
Head,
/// The parentheses after the `while` of a `do` loop.
DoHead,
/// The `)` of a `do` loop's `while` was read: the loop ends with the `;` after it, or before the
/// next token.
DoEnd,
/// The body's first token is next.
Start,
/// A body in braces.
@@ -170,7 +173,7 @@ enum Stage {
/// A body that is one statement without braces.
Statement,
/// The statement of a body without braces has reached its end: the loop ends at the next token,
/// unless it is `else`, which goes on with the statement.
/// unless it is `else`, `catch` or `finally`, which go on with the statement.
Tail,
}
@@ -274,7 +277,7 @@ impl<'s> Declarations<'s, '_, '_> {
/// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any
/// variable may be assigned in one ([`Declared::looped_full`]).
fn loop_start(&mut self, t: &Sig<'s>) {
let [h0, ..] = self.h;
let [h0, h1, ..] = self.h;
let depth = self.depth();
while let Some(l) = self.loops.last_mut() {
let after_head = std::mem::take(&mut l.after_head);
@@ -288,14 +291,19 @@ impl<'s> Declarations<'s, '_, '_> {
// don't go on with it, as in [`Analyzer::token`], and it does not follow the
// parentheses of an `if` or another statement that the body goes on with.
Stage::Statement
if t.nl && depth == l.depth && !goes_on_after(h0) && !goes_on_with(t) && !after_head && !word(h0, "else") && !word(h0, "do") =>
if t.nl
&& depth == l.depth
&& !goes_on_after(h0)
&& !goes_on_with(t)
&& !after_head
&& !["else", "do", "catch", "finally"].iter().any(|w| word(h0, w) && !member_mark(h1)) =>
{
l.stage = Stage::Tail;
}
Stage::Statement => {
if depth == l.depth {
if t.is("{") {
l.block = t.stmt || after_head || word(h0, "else");
l.block = t.stmt || after_head || word(h0, "else") || (word(h0, "finally") && !member_mark(h1));
} else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) {
l.head = true;
}
@@ -310,7 +318,14 @@ impl<'s> Declarations<'s, '_, '_> {
l.stage = Stage::Statement;
break;
}
Stage::Tail => {
// The `catch` and `finally` of a `try` statement that is the body go on with it.
Stage::Tail if t.word("catch") || t.word("finally") => {
l.stage = Stage::Statement;
l.head = t.word("catch");
break;
}
Stage::DoEnd if t.is(";") && depth == l.depth => break,
Stage::Tail | Stage::DoEnd => {
self.pop_loop(t.start);
// A body of one statement that is this loop ends with it.
if let Some(outer) = self.loops.last_mut()
@@ -366,7 +381,13 @@ impl<'s> Declarations<'s, '_, '_> {
}
false
}
Stage::DoHead => t.is(")") && depth == l.depth,
Stage::DoHead => {
if t.is(")") && depth == l.depth {
l.stage = Stage::DoEnd;
}
false
}
Stage::DoEnd => t.is(";") && depth == l.depth,
Stage::Block => {
if t.is("}") && depth == l.depth && l.do_loop {
l.stage = Stage::Tail;
+6 -5
View File
@@ -403,15 +403,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the
// global variable of that name may get another value.
if changes {
let global = if is(h1, ".") && word(h2, "this") {
// `this`, not a property named `this` (`holder.this.d`).
let global = if is(h1, ".") && word(h2, "this") && !member_mark(h3) {
h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string())
} else if is(h0, "]") && is(h2, "[") && word(h3, "this") {
} else if is(h0, "]") && is(h2, "[") && word(h3, "this") && !member_mark(self.h4) {
h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64))
} else {
None
};
if let Some(name) = global {
self.reassigned_later(&name);
self.reassigned_global(&name);
}
}
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text);
@@ -431,8 +432,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
// `local['name' + k]`.
writer(h2, h3).filter(|_| !t.is("]"))
} else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) {
// `local['saveAs'] = …`
writer(h3, None)
// `local['saveAs'] = …`, not `other.local['saveAs'] = …`.
writer(h3, self.h4)
} else {
None
};
+50
View File
@@ -761,6 +761,56 @@ fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() {
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..]));
}
/// The `catch` and `finally` of a `try` body, and an `else` after a `do` loop inside a body without
/// braces, are in the loop; a statement after the whole loop is not.
#[test]
fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() {
let r = report(concat!(
"var f = new File(p);\n",
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
"var h = {saveAs: function () {}};\n",
"while (i++ < 2) try { d.saveAs(f); } finally { d = app.activeDocument; }\n",
"while (i++ < 2)\n",
" if (i === 2) do e.saveAs(f); while (false);\n",
" else e = app.activeDocument;\n",
"while (n--) do g.saveAs(f); while (false);\n",
"g = app.activeDocument;\n",
"while (n--) h.saveAs(f), holder.finally\n",
"h = app.activeDocument;\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6][..]));
}
/// A literal after a label's line break may not run, a `this` assignment in a function whose own
/// variable hides the global one changes the global, and a property `d` of another object is not
/// the variable `d`.
#[test]
fn labels_hidden_globals_and_other_objects_keep_writes_known() {
let r = report(concat!(
"var f = new File(p);\n",
"var a = app.activeDocument;\n",
"if (no) l:\n",
"var a = {saveAs: function () {}};\n",
"a.saveAs(f);\n",
"var b = {saveAs: function () {}};\n",
"function change() { var b; this.b = app.activeDocument; }\n",
"change(); b.saveAs(f);\n",
"var c = {saveAs: function () {}};\n",
"function keep() { var c; c = 1; }\n",
"keep(); c.saveAs(f);\n",
"var d = {saveAs: function () {}};\n",
"holder.d['saveAs'] = 1;\n",
"d.saveAs(f);\n",
"var e = {saveAs: function () {}};\n",
"e['saveAs'] = app.activeDocument.saveAs;\n",
"e.saveAs(f);\n",
"var g = {saveAs: function () {}};\n",
"function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n",
"other(); g.saveAs(f);\n",
));
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17][..]));
}
/// Only a `var` statement directly in a function body or the global code that gives its first name
/// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the
/// statement. A literal given in a branch, one the value goes on from, one given by an assignment
+5 -2
View File
@@ -3169,8 +3169,11 @@ through `$`:
and leaves the document open when the document has no file (a converted or recovered document included) or when
the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several
artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with
`useArtboards: false` omits artboards; a native or `.ai` file (other than a version 7 `.ai` file) saved with
`separateArtboards` keeps every artboard whatever its range names.
`useArtboards: false` omits artboards; a native file saved with `separateArtboards` and a `.ai` or `.ait` file other
than a version 7 `.ai` file keep every artboard whatever their range names. An SVG file saved with Preserve
Editing Capabilities carries the native document with every artboard, so `close(SaveOptions.SAVECHANGES)` does not
refuse it for omitted artboards. The SVG drawing still shows one artboard, or the art bounds with
`useArtboards: false`, and the SVG save still refuses a range that selects several artboards.
`SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot
show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that
`saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name