From 55f7dc920538db9a773dca99fd03429e3f0889c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:51:09 -0800 Subject: [PATCH 01/20] Scripts: Document.saveAs, Document.exportFile and app.open with option classes Scripts save, export and open documents through Document.saveAs, Document.exportFile and app.open, with IllustratorSaveOptions, EPSSaveOptions, PDFSaveOptions, ExportOptionsPNG24, ExportOptionsJPEG, ExportOptionsSVG and a PDFFileOptions record, the ExportType and related enumerations, and app.userInteractionLevel. Each method runs file.saveAs, document.export or document.open inside the run's transaction. - A File argument reaches the host as its path only when the File class made it: the path is held in an internal slot that scripts cannot set, and a plain object that imitates a File is refused. - Each path is checked as a File opened for reading or writing would be, before the command runs, and the command's own reads and writes are then held to the script's grants, leaving out the open documents' files. A read-only file is not written over. - Options a command maps are applied; a listed option that is not mapped is accepted only at its documented default, and any other value, a bad type or an out-of-range number throws before anything is written. Without options, saveAs to a .ai, .eps or .pdf path and exportFile as PNG24, JPEG or SVG use the defaults a new options object holds. With pDFPreset named, a PDFSaveOptions option still at its default keeps the preset's value. A raster export at 100% has one pixel per point. - An export or save that writes several files, such as an SVG that writes its embedded images beside it or an EPS with a file per artboard, checks every path before writing the first. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/export_names.rs | 10 +- crates/engine/src/cmd/fileio/save.rs | 14 +- crates/engine/src/file_access.rs | 26 +- crates/engine/src/script/dom.rs | 11 +- crates/engine/src/script/dom/save_open.rs | 738 +++++++++++++++++++ crates/engine/src/script/files.rs | 36 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_save_open.rs | 510 +++++++++++++ crates/js/src/file_classes.rs | 93 ++- crates/js/src/heap.rs | 7 +- crates/js/src/host.rs | 12 +- crates/js/src/lib.rs | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 36 + docs/target-app-parity.md | 1 + 39 files changed, 1499 insertions(+), 22 deletions(-) create mode 100644 crates/engine/src/script/dom/save_open.rs create mode 100644 crates/engine/src/tests/script_save_open.rs diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 5f2c14bfd5..48a8c828ab 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -73,7 +73,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator, key: im /// Write an export's files for the destination `path` → `{path, bytes, files?, linked?, …extra}` /// (`files`: every file when there are several; `linked`: the images it links to); with no path -/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. +/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is +/// checked against the file access in force before the first file is written, so a refused path +/// writes none of them. pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result { let files = enc.named(doc, path.unwrap_or(name)); let (main, linked) = files.split_at(enc.files.len()); @@ -82,6 +84,12 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do None => json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }), }; if path.is_some() { + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 { + for (p, _) in &files { + super::may_write(p)?; + } + } for (p, bytes) in &files { write_file(p, bytes)?; } diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..94187808c6 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1044,7 +1044,8 @@ impl SaveJob { } /// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in - /// order: when `stop` returns a value, nothing is written and that value is returned. Work + /// order: when `stop` returns a value, nothing is written and that value is returned. When a + /// save writes several files and the file access in force refuses one, none is written. Work /// canceled ([`crate::cancel`]) before the first file is written returns /// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the /// others are written too. @@ -1069,6 +1070,15 @@ impl SaveJob { if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::>()) { return Ok(stopped); } + // Every path is checked against the file access in force before the first file is + // written. A refused file goes to `write` first, which refuses it with the error the + // caller gives (naming the path as the caller does), so none of the files is written. + #[cfg(not(target_arch = "wasm32"))] + if files.len() > 1 + && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + { + write(p, bytes)?; + } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { write(p, bytes)?; @@ -1369,7 +1379,7 @@ pub(super) fn specs() -> Vec { "Save Document", [], None, - "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", + "{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to -. beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to _.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel", has_doc, |s, p| save(s, SaveMode::Save, p) ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..4769146ad8 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -310,7 +310,9 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + // A read-only file is not written over, also where a rename could replace it. + let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); + !read_only && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))) }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -957,6 +959,28 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + #[test] + fn a_script_gate_does_not_write_over_a_read_only_file() { + let (base, _) = folders("gate-read-only"); + let out = base.join("out/kept.svg"); + std::fs::write(&out, "").unwrap(); + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::of_folder(&base.join("out")), documents: vec![], also: None }; + let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg"))); + let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok())); + assert_eq!(check(&kept), (true, true)); + let mut perms = std::fs::metadata(&out).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&out, perms.clone()).unwrap(); + assert_eq!(check(&kept), (false, true), "a read-only file is read but not written"); + assert!(check(&fresh).0, "a new file next to it is written"); + let documents = ScriptGate { documents: vec![kept.clone()], ..gate.clone() }; + assert!(!with_script_gate(documents, || check_write(&kept).is_ok()), "also when it is an open document's file"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&out, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..5e16f2a121 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod save_open; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -92,6 +94,8 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + /// `app.userInteractionLevel` ([`save_open`]). + save_options: save_open::State, } impl State { @@ -1707,7 +1711,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { - for (name, members) in ENUMS { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } @@ -1721,6 +1725,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("getIsFileOpen", method(l, app_is_open)), ]); application.push(later(l, "Application", "beep")); + application.extend(save_open::application_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -1761,10 +1766,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); + document.extend(save_open::document_members(l)); classes.push(class("Document", None, document, None)); classes.push(class( "PageItems", @@ -1829,6 +1835,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ); classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(save_open::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs new file mode 100644 index 0000000000..ebdebc4c10 --- /dev/null +++ b/crates/engine/src/script/dom/save_open.rs @@ -0,0 +1,738 @@ +//! Saving, exporting and opening documents in the script object model: `Document.saveAs`, +//! `Document.exportFile`, `app.open` and `app.userInteractionLevel`, with the option classes the +//! help pages , +//! , +//! , +//! , +//! , +//! , +//! , +//! and +//! describe. +//! +//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's +//! transaction. The file is a `File` object, and the method reads and writes only where that +//! `File` may ([`super::super::files`]): the path is checked before the command runs, and the +//! command's own reads and writes leave out the files of the open documents that `vc.run`'s +//! commands may use. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `saveAs` without options saves in the format the path's extension names; it writes the file +//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and +//! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds. +//! `exportFile` adds the format's extension unless the name already ends +//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes +//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. +//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it, +//! and when one of those files may not be written, none of them is. +//! - An option the classes here map is applied; a listed option that is not mapped is accepted at +//! the default its help page gives and throws an error that says it is not available yet at any +//! other value; a property the help pages do not list is left out. With `pDFPreset` named, a +//! `PDFSaveOptions` option still at a new object's default keeps the preset's value. +//! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: +//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. +//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The +//! commands a script runs never show a dialog, so the level does not change what they do, and it +//! never allows a file the script's grants do not. + +use std::cell::Cell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; + +use super::{ + Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, given, method, named, num, on_doc, property, + text, this_doc, whole, +}; + +/// The most a scale factor of an export takes, in percent. +pub const MAX_SCALE_PERCENT: f64 = 776.19; + +/// What the run keeps for these members: whether `userInteractionLevel` is `DONTDISPLAYALERTS`. +#[derive(Default)] +pub(in crate::script) struct State { + quiet: Cell, +} + +/// The enumerations these members use, as `dom`'s are made. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]), + ( + "Compatibility", + &[ + "ILLUSTRATOR8", + "ILLUSTRATOR9", + "ILLUSTRATOR10", + "ILLUSTRATOR11", + "ILLUSTRATOR12", + "ILLUSTRATOR13", + "ILLUSTRATOR14", + "ILLUSTRATOR15", + "ILLUSTRATOR16", + "ILLUSTRATOR17", + "ILLUSTRATOR19", + "JAPANESEVERSION3", + ], + ), + ("PDFCompatibility", &["ACROBAT4", "ACROBAT5", "ACROBAT6", "ACROBAT7", "ACROBAT8"]), + ("PDFBoxType", &["PDFARTBOX", "PDFBLEEDBOX", "PDFBOUNDINGBOX", "PDFCROPBOX", "PDFMEDIABOX", "PDFTRIMBOX"]), + ("EPSPreview", &["BWTIFF", "COLORTIFF", "TRANSPARENTCOLORTIFF", "None"]), + ("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]), + ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), + ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), +]; + +const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; +const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS"; + +/// The default a listed option that is not mapped keeps: a value equal to it is accepted. +#[derive(Clone, Copy)] +enum Default { + Bool(bool), + Num(f64), + Text(&'static str), + /// An enumerated value, by its enumeration and member (`("DownsampleMethod", "NODOWNSAMPLE")` for + /// `DownsampleMethod.NODOWNSAMPLE`). + Member(&'static str, &'static str), + /// The help page gives no default: any value throws. + Unset, +} + +impl Default { + fn matches(self, d: &Data) -> bool { + match (self, d) { + (Default::Bool(a), Data::Bool(b)) => a == *b, + (Default::Num(a), Data::Number(b)) => (a - b).abs() < 1e-9, + (Default::Text(a), Data::String(b)) => a == b, + (Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m), + _ => false, + } + } +} + +/// A mapped option: from its name and value into the command's params, `Ok(false)` for a name it +/// does not map. +type Mapper = fn(&str, &Data, &mut Map) -> std::result::Result; + +/// An option class: its name, its mapped options, its listed options that are not mapped, and the +/// defaults a new object starts with. +struct OptionClass { + name: &'static str, + map: Mapper, + kept: &'static [(&'static str, Default)], + starts: fn() -> Vec<(&'static str, Data)>, +} + +fn not_available(class: &str, name: &str) -> HostError { + HostError::Error(format!("{class}.{name} is not available yet")) +} + +fn whole_in(d: &Data, what: &str, lo: u64, hi: u64) -> std::result::Result { + match d { + Data::Number(n) => { + whole(*n).filter(|n| (lo..=hi).contains(n)).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from {lo} to {hi}"))) + } + _ => Err(HostError::Type(format!("{what} must be a number"))), + } +} + +/// The member of `enumeration` that `d` names (`"Enumeration.MEMBER"`), one of `members`. +fn member<'a>(d: &'a Data, enumeration: &str, members: &[&str], what: &str) -> std::result::Result<&'a str, HostError> { + let bad = || HostError::Type(format!("{what} must be a {enumeration} value")); + let Data::String(s) = d else { return Err(bad()) }; + let m = s.strip_prefix(enumeration).and_then(|r| r.strip_prefix('.')).ok_or_else(bad)?; + if members.contains(&m) { Ok(m) } else { Err(bad()) } +} + +/// A `Compatibility` value: the versions from 17 on are the file VectorCraft writes; older ones are +/// not available. +fn compatibility(class: &str, d: &Data) -> std::result::Result<(), HostError> { + let all = ENUMS.iter().find(|(n, _)| *n == "Compatibility").map_or(&[][..], |(_, m)| *m); + match member(d, "Compatibility", all, &format!("{class}.compatibility"))? { + "ILLUSTRATOR17" | "ILLUSTRATOR19" => Ok(()), + _ => Err(not_available(class, "compatibility")), + } +} + +/// An artboard range: a string, given to the command as `range` unless it is empty. +fn range(d: &Data, what: &str, p: &mut Map) -> std::result::Result<(), HostError> { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("{what} is too long"))); + } + if !s.trim().is_empty() { + p.insert("range".into(), json!(s)); + } + Ok(()) +} + +// ---- Save options ---- + +fn ai_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("IllustratorSaveOptions.{name}"); + match name { + "compressed" => p.insert("compress".into(), json!(boolean(d, &what)?)), + "pdfCompatible" => p.insert("pdfCompatible".into(), json!(boolean(d, &what)?)), + "embedICCProfile" => p.insert("embedProfiles".into(), json!(boolean(d, &what)?)), + "compatibility" => { + compatibility("IllustratorSaveOptions", d)?; + None + } + _ => return Ok(false), + }; + Ok(true) +} + +const AI_KEPT: &[(&str, Default)] = &[ + ("artboardRange", Default::Text("")), + ("embedLinkedFiles", Default::Bool(false)), + ("flattenOutput", Default::Member("OutputFlattening", "PRESERVEAPPEARANCE")), + ("fontSubsetThreshold", Default::Num(100.0)), + ("saveMultipleArtboards", Default::Bool(false)), +]; + +fn ai_starts() -> Vec<(&'static str, Data)> { + vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))] +} + +fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("EPSSaveOptions.{name}"); + match name { + "cmykPostScript" => { + p.insert("cmykPostScript".into(), json!(boolean(d, &what)?)); + } + "includeDocumentThumbnails" => { + p.insert("thumbnails".into(), json!(boolean(d, &what)?)); + } + "postScript" => { + let level = if member(d, "EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"], &what)? == "LEVEL2" { 2 } else { 3 }; + p.insert("level".into(), json!(level)); + } + "preview" => { + let (format, transparent) = match member(d, "EPSPreview", &["BWTIFF", "COLORTIFF", "TRANSPARENTCOLORTIFF", "None"], &what)? { + "BWTIFF" => ("tiffBw", None), + "COLORTIFF" => ("tiffColor", Some(false)), + "TRANSPARENTCOLORTIFF" => ("tiffColor", Some(true)), + _ => ("none", None), + }; + p.insert("previewFormat".into(), json!(format)); + if let Some(t) = transparent { + p.insert("transparentPreview".into(), json!(t)); + } + } + "overprint" => { + let keep = member(d, "PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"], &what)? == "PRESERVEPDFOVERPRINT"; + p.insert("overprints".into(), json!(if keep { "preserve" } else { "discard" })); + } + "compatibility" => compatibility("EPSSaveOptions", d)?, + _ => return Ok(false), + } + Ok(true) +} + +const EPS_KEPT: &[(&str, Default)] = &[ + ("artboardRange", Default::Text("")), + ("compatibleGradientPrinting", Default::Bool(false)), + ("embedAllFonts", Default::Bool(false)), + ("embedLinkedFiles", Default::Unset), + ("flattenOuput", Default::Unset), + ("saveMultipleArtboards", Default::Bool(false)), +]; + +fn eps_starts() -> Vec<(&'static str, Data)> { + vec![("postScript", text("EPSPostScriptLevelEnum.LEVEL2")), ("overprint", text("PDFOverprint.PRESERVEPDFOVERPRINT"))] +} + +fn pdf_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("PDFSaveOptions.{name}"); + match name { + "pDFPreset" => { + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > MAX_TEXT_BYTES { + return Err(HostError::Range(format!("{what} is too long"))); + } + p.insert("preset".into(), json!(s)); + } + "compatibility" => { + let version = match member(d, "PDFCompatibility", &["ACROBAT4", "ACROBAT5", "ACROBAT6", "ACROBAT7", "ACROBAT8"], &what)? { + "ACROBAT4" => "1.3", + "ACROBAT5" => "1.4", + "ACROBAT6" => "1.5", + "ACROBAT7" => "1.6", + _ => "1.7", + }; + p.insert("compatibility".into(), json!(version)); + } + "artboardRange" => range(d, &what, p)?, + "preserveEditability" => { + p.insert("preserveEditing".into(), json!(boolean(d, &what)?)); + } + "acrobatLayers" => { + p.insert("createLayers".into(), json!(boolean(d, &what)?)); + } + "compressArt" => { + p.insert("compression".into(), json!({"compressText": boolean(d, &what)?})); + } + _ => return Ok(false), + } + Ok(true) +} + +const PDF_KEPT: &[(&str, Default)] = &[ + ("bleedLink", Default::Bool(true)), + ("bleedOffsetRect", Default::Unset), + ("colorBars", Default::Bool(false)), + ("colorCompression", Default::Member("CompressionQuality", "None")), + ("colorConversionID", Default::Member("ColorConversion", "None")), + ("colorDestinationID", Default::Member("ColorDestination", "None")), + ("colorDownsampling", Default::Num(150.0)), + ("colorDownsamplingImageThreshold", Default::Num(225.0)), + ("colorDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("colorProfileID", Default::Member("ColorProfile", "None")), + ("colorTileSize", Default::Num(256.0)), + ("documentPassword", Default::Text("")), + ("enableAccess", Default::Bool(true)), + ("enableCopy", Default::Bool(true)), + ("enableCopyAccess", Default::Bool(true)), + ("enablePlainText", Default::Bool(false)), + ("flattenerOptions", Default::Unset), + ("flattenerPreset", Default::Unset), + ("fontSubsetThreshold", Default::Num(100.0)), + ("generateThumbnails", Default::Bool(true)), + ("grayscaleCompression", Default::Member("CompressionQuality", "None")), + ("grayscaleDownsampling", Default::Num(150.0)), + ("grayscaleDownsamplingImageThreshold", Default::Num(225.0)), + ("grayscaleDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("grayscaleTileSize", Default::Num(256.0)), + ("monochromeCompression", Default::Member("MonochromeCompression", "None")), + ("monochromeDownsampling", Default::Num(300.0)), + ("monochromeDownsamplingImageThreshold", Default::Num(450.0)), + ("monochromeDownsamplingMethod", Default::Member("DownsampleMethod", "NODOWNSAMPLE")), + ("offset", Default::Num(0.0)), + ("optimization", Default::Bool(false)), + ("outputCondition", Default::Unset), + ("outputConditionID", Default::Unset), + ("pageInformation", Default::Bool(false)), + ("pageMarksType", Default::Member("PageMarksTypes", "Roman")), + ("pDFAllowPrinting", Default::Member("PDFPrintAllowedEnum", "PRINT128HIGHRESOLUTION")), + ("pDFChangesAllowed", Default::Member("PDFChangesAllowedEnum", "CHANGE128ANYCHANGES")), + ("pDFXStandard", Default::Member("PDFXStandard", "PDFXNONE")), + ("pDFXStandardDescription", Default::Unset), + ("permissionPassword", Default::Text("")), + ("printerResolution", Default::Num(800.0)), + ("registrationMarks", Default::Bool(false)), + ("requireDocumentPassword", Default::Bool(false)), + ("requirePermissionPassword", Default::Bool(false)), + ("trapped", Default::Bool(false)), + ("trimMarks", Default::Bool(false)), + ("trimMarkWeight", Default::Member("PDFTrimMarkWeight", "TRIMMARKWEIGHT0125")), + ("viewAfterSaving", Default::Bool(false)), +]; + +fn pdf_starts() -> Vec<(&'static str, Data)> { + vec![ + ("compatibility", text("PDFCompatibility.ACROBAT5")), + ("artboardRange", text("")), + ("preserveEditability", Data::Bool(true)), + ("acrobatLayers", Data::Bool(false)), + ("compressArt", Data::Bool(true)), + ] +} + +const SAVE_CLASSES: &[(OptionClass, &str)] = &[ + (OptionClass { name: "IllustratorSaveOptions", map: ai_map, kept: AI_KEPT, starts: ai_starts }, "ai"), + (OptionClass { name: "EPSSaveOptions", map: eps_map, kept: EPS_KEPT, starts: eps_starts }, "eps"), + (OptionClass { name: "PDFSaveOptions", map: pdf_map, kept: PDF_KEPT, starts: pdf_starts }, "pdf"), +]; + +// ---- Export options ---- + +/// The raster options PNG24 and JPEG share: anti-aliasing, the clip to the artboard and the scale. +fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("{class}.{name}"); + match name { + "antiAliasing" => { + p.insert("antiAlias".into(), json!(if boolean(d, &what)? { "art" } else { "none" })); + } + "artBoardClipping" => { + p.insert("_clip".into(), json!(boolean(d, &what)?)); + } + "horizontalScale" | "verticalScale" => { + let n = match d { + Data::Number(n) if n.is_finite() => *n, + _ => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + if n <= 0.0 || n > MAX_SCALE_PERCENT { + return Err(HostError::Range(format!("{what} must be more than 0 and at most 776.19"))); + } + let key = if name == "horizontalScale" { "_h" } else { "_v" }; + p.insert(key.into(), json!(n)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + if name == "transparency" { + let clear = boolean(d, "ExportOptionsPNG24.transparency")?; + p.insert("background".into(), json!(if clear { "transparent" } else { "white" })); + return Ok(true); + } + raster_map("ExportOptionsPNG24", name, d, p) +} + +const PNG24_KEPT: &[(&str, Default)] = &[("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + +fn png24_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", Data::Bool(true)), + ("artBoardClipping", Data::Bool(false)), + ("horizontalScale", num(100.0)), + ("verticalScale", num(100.0)), + ("transparency", Data::Bool(true)), + ] +} + +fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + match name { + "qualitySetting" => { + p.insert("quality".into(), json!(whole_in(d, "ExportOptionsJPEG.qualitySetting", 0, 100)?)); + Ok(true) + } + "optimization" => { + let optimized = boolean(d, "ExportOptionsJPEG.optimization")?; + p.insert("method".into(), json!(if optimized { "optimized" } else { "baseline" })); + Ok(true) + } + _ => raster_map("ExportOptionsJPEG", name, d, p), + } +} + +const JPEG_KEPT: &[(&str, Default)] = + &[("blurAmount", Default::Num(0.0)), ("matte", Default::Bool(true)), ("matteColor", Default::Unset), ("saveAsHTML", Default::Bool(false))]; + +fn jpeg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", Data::Bool(true)), + ("horizontalScale", num(100.0)), + ("verticalScale", num(100.0)), + ("optimization", Data::Bool(true)), + ("qualitySetting", num(30.0)), + ] +} + +fn svg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportOptionsSVG.{name}"); + match name { + "coordinatePrecision" => { + p.insert("decimals".into(), json!(whole_in(d, &what, 1, 7)?)); + } + "embedRasterImages" => { + p.insert("images".into(), json!(if boolean(d, &what)? { "embed" } else { "link" })); + } + "compressed" => { + p.insert("_svgz".into(), json!(boolean(d, &what)?)); + } + "preserveEditability" => { + p.insert("preserveEditing".into(), json!(boolean(d, &what)?)); + } + "includeVariablesAndDatasets" => { + p.insert("variableData".into(), json!(boolean(d, &what)?)); + } + _ => return Ok(false), + } + Ok(true) +} + +const SVG_KEPT: &[(&str, Default)] = &[ + ("artboardRange", Default::Text("")), + ("cssProperties", Default::Member("SVGCSSPropertyLocation", "STYLEATTRIBUTES")), + ("documentEncoding", Default::Member("SVGDocumentEncoding", "ASCII")), + ("DTD", Default::Member("SVGDTDVersion", "SVG1_1")), + ("fontSubsetting", Default::Member("SVGFontSubsetting", "ALLGLYPHS")), + ("fontType", Default::Member("SVGFontType", "CEFFONT")), + ("includeFileInfo", Default::Bool(false)), + ("includeUnusedStyles", Default::Bool(false)), + ("optimizeForSVGViewer", Default::Bool(false)), + ("saveMultipleArtboards", Default::Bool(false)), + ("slices", Default::Bool(false)), + ("sVGAutoKerning", Default::Bool(false)), + ("sVGTextOnPath", Default::Bool(false)), +]; + +fn svg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("compressed", Data::Bool(false)), + ("coordinatePrecision", num(3.0)), + ("embedRasterImages", Data::Bool(false)), + ("includeVariablesAndDatasets", Data::Bool(false)), + ("preserveEditability", Data::Bool(false)), + ] +} + +const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts }; +const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts }; +const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts }; + +/// An `ExportType`: the format `document.export` writes, the extensions a file name may already +/// end with (the first is added), and its option class (`None`: no options are taken). +struct ExportKind { + format: &'static str, + extensions: &'static [&'static str], + options: Option<&'static OptionClass>, +} + +fn export_kind(d: &Data) -> std::result::Result { + let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m); + let raster = |format, extensions| ExportKind { format, extensions, options: None }; + Ok(match member(d, "ExportType", all, "exportType")? { + "PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) }, + "JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) }, + "SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) }, + "PNG8" => raster("png8", &["png"]), + "GIF" => raster("gif", &["gif"]), + "TIFF" => raster("tiff", &["tif", "tiff"]), + other => return Err(HostError::Error(format!("ExportType.{other} is not available yet"))), + }) +} + +/// The command's params for the options object `d` of `class`, read as the module's rules say. +fn options_params(class: &OptionClass, d: &Data) -> std::result::Result, HostError> { + let wrong = || HostError::Type(format!("the options must be an {} object", class.name)); + let Data::Object(items) = d else { return Err(wrong()) }; + if !items.iter().any(|(k, v)| k == "typename" && matches!(v, Data::String(s) if s == class.name)) { + return Err(wrong()); + } + // With a PDF preset named, an option still at a new object's default leaves the preset's value. + let preset = class.name == "PDFSaveOptions" && items.iter().any(|(k, v)| k == "pDFPreset" && matches!(v, Data::String(s) if !s.is_empty())); + let starts = if preset { (class.starts)() } else { Vec::new() }; + let mut p = Map::new(); + for (k, v) in items { + if k == "typename" || matches!(v, Data::Undefined) || starts.iter().any(|(n, s)| n == k && s == v) { + continue; + } + if (class.map)(k, v, &mut p)? { + continue; + } + match class.kept.iter().find(|(n, _)| n == k) { + Some((_, default)) if default.matches(v) => {} + Some(_) => return Err(not_available(class.name, k)), + None => {} + } + } + Ok(p) +} + +/// What `new Name()` gives for `class`: its `typename` and the defaults its help page gives for the +/// options mapped here. +fn fresh(class: &OptionClass) -> Data { + let mut items = vec![("typename".to_string(), text(class.name))]; + items.extend((class.starts)().into_iter().map(|(k, v)| (k.to_string(), v))); + Data::Object(items) +} + +/// The typename of an options object, when it has one. +fn typename(d: &Data) -> Option<&str> { + let Data::Object(items) = d else { return None }; + items.iter().find_map(|(k, v)| match (k.as_str(), v) { + ("typename", Data::String(s)) => Some(s.as_str()), + _ => None, + }) +} + +// ---- Files ---- + +/// The path of the `File` argument `d`, or a `TypeError` naming the method. +fn file_path<'a>(d: &'a Data, method: &str) -> std::result::Result<&'a str, HostError> { + vectorcraft_js::file_ref_path(d).ok_or_else(|| HostError::Type(format!("{method} needs a File"))) +} + +/// The error a refused path throws: the `File` error and the path. +fn refused(message: &str, path: &str) -> HostError { + HostError::Error(format!("{message}: {path}")) +} + +/// Runs `f` with the commands' reads and writes held to the script's own grants +/// ([`super::super::files::Disk::exact`]). +fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { + h.disk.borrow_mut().exact = true; + let r = f(); + h.disk.borrow_mut().exact = false; + r +} + +/// The path to give a command for the real path `real`. +fn plain(real: std::path::PathBuf) -> String { + crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() +} + +/// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options' +/// class names (`ai`, `eps`, `pdf`), or without options in the format of the path's extension. +fn doc_save_as(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_path(arg(a, 1), "saveAs")?; + let mut p = Map::new(); + let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)); + // Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options + // object of that format's class holds. + let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase()); + let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c)); + if let Some(o) = given_options.or(by_extension.as_ref()) { + let name = typename(o); + let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else { + return Err(HostError::Type("saveAs options must be IllustratorSaveOptions, EPSSaveOptions or PDFSaveOptions".into())); + }; + let q = options_params(class, o)?; + p.insert("format".into(), json!(format)); + if *format == "ai" { + p.extend(q); + } else if !q.is_empty() { + p.insert("options".into(), Value::Object(q)); + } + } + let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; + p.insert("path".into(), json!(plain(real))); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + Ok(Data::Undefined) +} + +/// `path` with the extension of `kind` added, unless its name already ends with one of them. +fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String { + let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions }; + let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_lowercase(); + match extensions.first() { + Some(first) if !extensions.iter().any(|e| name.ends_with(&format!(".{e}"))) => format!("{path}.{first}"), + _ => path.to_string(), + } +} + +/// `document.exportFile(file, exportType, options?)`: `document.export` of one file, which leaves +/// the document's path as it is. +fn doc_export_file(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let path = file_path(arg(a, 1), "exportFile")?; + let kind = export_kind(arg(a, 2))?; + // Without options, an export takes the defaults a new options object of its class holds. + let mut p = match given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) { + None => match kind.options { + Some(class) => options_params(class, &fresh(class))?, + None => Map::new(), + }, + Some(o) => match kind.options { + Some(class) => options_params(class, o)?, + None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))), + }, + }; + let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false); + let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false); + let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0)); + if (hs - vs).abs() > 1e-9 { + return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into())); + } + // A raster file has one pixel per point at 100%, whatever the document's raster effects resolution. + if kind.format != "svg" { + p.insert("scale".into(), json!(hs / 100.0)); + } + let format = if svgz { "svgz" } else { kind.format }; + p.insert("format".into(), json!(format)); + if kind.format == "svg" { + p.insert("useArtboards".into(), json!(false)); + } else if clip { + let artboard = super::with_doc(h, doc, |_, st| super::active_artboard(st)); + p.insert("artboard".into(), json!(artboard)); + } else { + p.insert("useArtboards".into(), json!(false)); + } + let named = with_extension(path, &kind, svgz); + let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; + p.insert("path".into(), json!(plain(real))); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + Ok(Data::Undefined) +} + +/// `app.open(file, documentColorSpace?, options?)`: `document.open` of the file, which becomes +/// the active document. → the document. +fn app_open(h: &Host, a: &[Data]) -> Answer { + let path = file_path(arg(a, 1), "open")?; + let mut p = Map::new(); + if let Some(d) = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)) { + let mode = if member(d, "DocumentColorSpace", &["CMYK", "RGB"], "documentColorSpace")? == "RGB" { "rgb" } else { "cmyk" }; + p.insert("colorMode".into(), json!(mode)); + } + if let Some(o) = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) { + let Data::Object(items) = o else { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())) }; + if typename(o).is_some_and(|t| t != "PDFFileOptions") { + return Err(HostError::Type("open's options must be a PDFFileOptions record".into())); + } + for (k, v) in items { + match k.as_str() { + "pageToOpen" => { + p.insert("page".into(), json!(whole_in(v, "PDFFileOptions.pageToOpen", 1, 1_000_000)?)); + } + "pDFCropToBox" => { + let boxes = ["PDFARTBOX", "PDFBLEEDBOX", "PDFBOUNDINGBOX", "PDFCROPBOX", "PDFMEDIABOX", "PDFTRIMBOX"]; + let crop = match member(v, "PDFBoxType", &boxes, "PDFFileOptions.pDFCropToBox")? { + "PDFARTBOX" => "art", + "PDFBLEEDBOX" => "bleed", + "PDFBOUNDINGBOX" => "bounding", + "PDFCROPBOX" => "crop", + "PDFMEDIABOX" => "media", + _ => "trim", + }; + p.insert("cropTo".into(), json!(crop)); + } + _ => {} + } + } + } + let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; + p.insert("path".into(), json!(plain(real))); + let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let index = match &r { + Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { + ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), + _ => None, + }), + _ => None, + }; + let s = h.session.borrow(); + let st = index.and_then(|i| s.documents().get(i)).or_else(|| s.active()).ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) +} + +fn app_interaction(h: &Host, _: &[Data]) -> Answer { + Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY })) +} + +fn app_set_interaction(h: &Host, a: &[Data]) -> Answer { + let quiet = member(arg(a, 1), "UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"], "userInteractionLevel")? == "DONTDISPLAYALERTS"; + h.dom.save_options.quiet.set(quiet); + Ok(Data::Undefined) +} + +/// The members these add to `Application`. +pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("open", method(l, app_open)), ("userInteractionLevel", property(l, app_interaction, app_set_interaction))]) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("saveAs", method(l, doc_save_as)), ("exportFile", method(l, doc_export_file))]) +} + +/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its +/// help page gives for the options mapped here. +pub(super) fn classes(link: &Link) -> Vec { + let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]); + all.map(|c| { + let l = link.clone(); + let f: HostFunction = Rc::new(move |_: Vec| { + current(&l)?.charge_call(64)?; + Ok(fresh(c)) + }); + HostClass { name: c.name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + }) + .collect() +} diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index c0694bbd81..40b1fe0465 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -115,6 +115,7 @@ pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many step pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing"; pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text"; pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; +pub(crate) const READ_ONLY: &str = "Script file is read-only"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; @@ -271,6 +272,9 @@ pub(crate) struct Disk { /// when they were last written to the grants file. kept: Vec<(std::path::PathBuf, bool, bool)>, recorded: usize, + /// While set, the gate of a command the script runs leaves out the files of the open documents + /// ([`Disk::gate`]): the command reads and writes only where the script's `File` objects may. + pub(crate) exact: bool, /// The write bits setting `readonly` cleared from each file in this run, by its device and /// inode, which a rename keeps, at most [`MAX_ENTRIES`] files: clearing `readonly` gives them back. #[cfg(unix)] @@ -324,6 +328,7 @@ impl Disk { ran_too_much: setup.engine_code.1, kept: Vec::new(), recorded: 0, + exact: false, #[cfg(unix)] cleared: HashMap::new(), }; @@ -457,6 +462,8 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, and the files of /// the open documents, `documents`. pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { + // A save, export or open of a `File` the script names reads and writes as its `File` would. + let documents = if self.exact { Vec::new() } else { documents }; crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } } @@ -676,6 +683,35 @@ impl Disk { } } + /// The real path a save or export of the document to `path` writes, as a `File` opened for + /// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, and a + /// read-only file is not written over. + pub(crate) fn save_target(&self, path: &str) -> Result { + let real = self.target(path, true)?; + match std::fs::metadata(&real) { + Ok(m) if !m.is_file() => Err(NOT_REGULAR), + Ok(m) if m.permissions().readonly() => Err(READ_ONLY), + _ => Ok(real), + } + } + + /// The real path of the file `path` that opening it as a document reads, as a `File` reads it + /// ([`ScriptScope::locate`]), or why it may not: it is not there, it is not a regular file, or + /// the script may not read it. + pub(crate) fn open_target(&self, path: &str) -> Result { + let p = self.checked(path)?; + let real = match self.scope.locate(p) { + Ok(real) => real, + Err(ScriptRead::Missing) => return Err(NOT_FOUND), + Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED), + Err(ScriptRead::Failed(_)) => return Err(READ_FAILED), + }; + if !real.is_file() { + return Err(NOT_REGULAR); + } + Ok(real) + } + /// Counts `n` more bytes written in the run, which ends past [`MAX_RUN_BYTES`]. fn charge_write(&mut self, n: usize) -> Result<(), HostError> { self.written = self.written.saturating_add(n); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..436d74cf75 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_save_open; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs new file mode 100644 index 0000000000..809fed0ef8 --- /dev/null +++ b/crates/engine/src/tests/script_save_open.rs @@ -0,0 +1,510 @@ +//! Saving, exporting and opening documents from a script: `Document.saveAs`, `Document.exportFile`, +//! `app.open`, their option classes and `app.userInteractionLevel`, and the file grants each path +//! goes through. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +const DENIED: &str = "Script file access denied"; + +/// A fresh folder for test `name`, by its real path, with `main` for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("outside")).unwrap(); + std::fs::canonicalize(&base).unwrap() +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn session(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + std::fs::write(&main, text.as_bytes()).unwrap(); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +fn logged(s: &mut Session, base: &Path, text: &str) -> Value { + run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"))["log"].clone() +} + +fn failure(s: &mut Session, base: &Path, text: &str) -> String { + run(s, base, text).map(|r| panic!("{text} ran: {r}")).unwrap_err().to_string() +} + +/// The script's data folder, where it may write. +fn data_folder(s: &mut Session, base: &Path) -> PathBuf { + PathBuf::from(logged(s, base, "vc.log(Folder.userData.fsName);")[0].as_str().unwrap()) +} + +fn quoted(p: &Path) -> String { + serde_json::to_string(&p.to_string_lossy()).unwrap() +} + +#[test] +fn save_as_export_file_and_open_write_and_read_where_the_script_may() { + let base = folder("happy"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + d.saveAs(new File(dir + '/a.svg'));\n\ + var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability]);\n\ + o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.someOtherName = 3;\n\ + o.colorCompression = 'CompressionQuality.None';\n\ + d.saveAs(new File(dir + '/b.pdf'), o); vc.log(d.name);\n\ + var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 200; p.artBoardClipping = true;\n\ + d.exportFile(new File(dir + '/c'), ExportType.PNG24, p);\n\ + d.exportFile(new File(dir + '/e.JPG'), ExportType.JPEG);\n\ + var v = new ExportOptionsSVG(); v.compressed = true; v.coordinatePrecision = 2;\n\ + d.exportFile(new File(dir + '/f'), ExportType.SVG, v); vc.log(d.name);\n\ + var g = app.open(new File(dir + '/a.svg'));\n\ + vc.log([g.typename, app.documents.length, app.activeDocument.name === g.name, g.name]);\n\ + var u = [app.userInteractionLevel]; app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; u.push(app.userInteractionLevel); vc.log(u);" + ), + ); + assert_eq!(out[0], json!(["PDFSaveOptions", "PDFCompatibility.ACROBAT5", true])); + assert_eq!(out[1], json!("b.pdf"), "saveAs gives the document the new file"); + assert_eq!(out[2], json!("b.pdf"), "exportFile leaves the document's file as it is"); + assert_eq!(out[3], json!(["Document", 2, true, "a.svg"])); + assert_eq!(out[4], json!(["UserInteractionLevel.DISPLAYALERTS", "UserInteractionLevel.DONTDISPLAYALERTS"])); + assert!(std::fs::read_to_string(dir.join("a.svg")).unwrap().contains(" = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != central).collect(); + boards.sort(); + assert!(central.is_file() && boards.len() == 2, "the central file and a file per artboard: {boards:?}"); + let board = boards.pop().unwrap(); + std::fs::remove_file(¢ral).unwrap(); + let mut perms = std::fs::metadata(&board).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&board, perms.clone()).unwrap(); + let e = failure(&mut s, &base, &save); + assert!(e.contains(DENIED), "{e}"); + assert!(!central.exists(), "the central file is not written when an artboard's file may not be"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&board, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// Every path goes through the script's file grants, as a `File` opened for reading or writing. +#[test] +fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { + let base = folder("refused"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(base.join("outside/secret.svg"), "").unwrap(); + std::fs::write(base.join("settings/Script Grants.json"), "{}").unwrap(); + std::fs::write(dir.join("kept.svg"), "kept").unwrap(); + let mut perms = std::fs::metadata(dir.join("kept.svg")).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let undo = s.active().unwrap().history.undo.len(); + let outside = quoted(&base.join("outside/x.svg")); + let grants = quoted(&base.join("settings/Script Grants.json")); + let kept = quoted(&dir.join("kept.svg")); + let secret = quoted(&base.join("outside/secret.svg")); + let cases = [ + format!("app.activeDocument.saveAs(new File({outside}));"), + format!("app.activeDocument.exportFile(new File({outside}), ExportType.PNG24);"), + format!("app.activeDocument.saveAs(new File({grants}));"), + format!("app.open(new File({secret}));"), + format!("app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; app.activeDocument.saveAs(new File({outside}));"), + ]; + for case in &cases { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(DENIED), "{case}: {e}"); + } + let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({kept}));")); + assert!(e.contains("Script file is read-only"), "{e}"); + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir))); + assert!(e.contains("Script file") && !e.contains("ran"), "a folder is not saved over: {e}"); + assert_eq!(std::fs::read_to_string(dir.join("kept.svg")).unwrap(), "kept"); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), "{}"); + assert!(!base.join("outside/x.svg").exists() && !base.join("outside/x.svg.png").exists()); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().path, None, "a refused save leaves the document's file as it is"); + assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step"); + let mut perms = std::fs::metadata(dir.join("kept.svg")).unwrap().permissions(); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// The file of an open document is not written or read through a script method unless the +/// script's grants take it, though `vc.run`'s commands may use it. +#[test] +fn an_open_documents_file_is_not_saved_over_without_a_grant() { + let base = folder("opendoc"); + let mut s = session(&base); + let path = base.join("outside/open.svg"); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap(); + let before = std::fs::read(&path).unwrap(); + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&path))); + assert!(e.contains(DENIED), "{e}"); + let e = failure(&mut s, &base, &format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&path))); + assert!(e.contains(DENIED), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), before); + let _ = std::fs::remove_dir_all(base); +} + +/// A file `open` reads besides the one it names, here an SVG's linked image, is read only where +/// the script's grants allow, though it is an open document's file. +#[test] +fn open_reads_linked_files_only_where_the_script_may() { + let base = folder("linked"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let linked = base.join("outside/linked.svg"); + std::fs::write(&linked, "").unwrap(); + s.execute("document.open", &json!({"path": linked.to_string_lossy()})).unwrap(); + assert!(s.active().unwrap().path.is_some(), "the linked file is an open document's file"); + let href = linked.to_string_lossy().replace('\\', "/"); + std::fs::write( + dir.join("page.svg"), + format!(""), + ) + .unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("page.svg")))); + assert_eq!(s.documents().len(), 2); + let ims = |s: &Session| { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((im.width, im.height, im.link.as_ref().map(|l| (l.modified.is_some(), l.hash.is_some())))); + } + }); + out + }; + let kinds = |s: &Session| { + let mut out = vec![]; + s.active().unwrap().doc.walk(|n| out.push(format!("{:?}", n.kind).chars().take(12).collect::())); + out + }; + assert_eq!(ims(&s), vec![(64, 64, Some((false, false)))], "the linked file is a placeholder: {:?}", kinds(&s)); + // Opened by the app, a copy of the file reads its image. + std::fs::copy(dir.join("page.svg"), dir.join("copy.svg")).unwrap(); + s.execute("document.open", &json!({"path": dir.join("copy.svg").to_string_lossy()})).unwrap(); + assert!(ims(&s).is_empty() && kinds(&s).iter().any(|k| k.starts_with("Path")), "{:?}", kinds(&s)); + let _ = std::fs::remove_dir_all(base); +} + +/// An SVG export with `embedRasterImages` false writes the document's embedded image beside the +/// SVG, and when that file may not be written, the SVG is not written either. +#[test] +fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() { + let base = folder("svgimages"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/pic.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap(); + let export = + format!("Folder.userData; app.activeDocument.exportFile(new File({}), ExportType.SVG, new ExportOptionsSVG());", quoted(&dir.join("a.svg"))); + logged(&mut s, &base, &export); + let svg = dir.join("a.svg"); + let mut images: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect(); + assert_eq!(images.len(), 1, "the embedded image is written beside the SVG: {images:?}"); + let image = images.remove(0); + std::fs::remove_file(&svg).unwrap(); + let mut perms = std::fs::metadata(&image).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&image, perms.clone()).unwrap(); + let e = failure(&mut s, &base, &export); + assert!(e.contains(DENIED), "{e}"); + assert!(!svg.exists(), "the SVG is not written when its image may not be"); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&image, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + +/// A link inside a granted folder that leads out of it is followed and refused. +#[cfg(unix)] +#[test] +fn a_link_out_of_the_granted_folder_is_refused() { + let base = folder("link"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::os::unix::fs::symlink(base.join("outside"), dir.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("outside/target.svg"), dir.join("file.svg")).unwrap(); + std::fs::write(base.join("outside/read.svg"), "").unwrap(); + std::os::unix::fs::symlink(base.join("outside/read.svg"), dir.join("read.svg")).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for name in ["away/x.svg", "file.svg"] { + let e = failure(&mut s, &base, &format!("app.activeDocument.saveAs(new File({}));", quoted(&dir.join(name)))); + assert!(e.contains(DENIED), "{name}: {e}"); + } + let e = failure(&mut s, &base, &format!("app.open(new File({}));", quoted(&dir.join("read.svg")))); + assert!(e.contains(DENIED), "{e}"); + assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1, "nothing is written outside"); + assert_eq!(s.documents().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// Bad arguments throw before anything is written or opened. +#[test] +fn bad_arguments_are_refused_with_an_error() { + let base = folder("bad"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let f = format!("new File({})", quoted(&dir.join("x.svg"))); + let huge = "a".repeat(5000); + let cases: Vec<(String, &str)> = vec![ + ("app.activeDocument.saveAs('x.svg');".into(), "saveAs needs a File"), + (format!("app.activeDocument.saveAs({{'\\u0000fileRef': {}}});", quoted(&dir.join("x.svg"))), "is not plain data"), + (format!("app.activeDocument.saveAs({f}, {{typename: 'Nope'}});"), "saveAs options must be"), + (format!("app.activeDocument.saveAs({f}, new ExportOptionsSVG());"), "saveAs options must be"), + (format!("var o = new IllustratorSaveOptions(); o.compressed = 'yes'; app.activeDocument.saveAs({f}, o);"), "must be true or false"), + ( + format!("var o = new IllustratorSaveOptions(); o.compatibility = Compatibility.ILLUSTRATOR8; app.activeDocument.saveAs({f}, o);"), + "is not available yet", + ), + ( + format!("var o = new PDFSaveOptions(); o.trimMarks = true; app.activeDocument.saveAs({f}, o);"), + "PDFSaveOptions.trimMarks is not available yet", + ), + ( + format!("var o = new PDFSaveOptions(); o.colorCompression = 'Unrelated.None'; app.activeDocument.saveAs({f}, o);"), + "PDFSaveOptions.colorCompression is not available yet", + ), + (format!("var o = new PDFSaveOptions(); o.pDFPreset = '{huge}'; app.activeDocument.saveAs({f}, o);"), "too long"), + (format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"), + (format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"), + (format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"), + (format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"), + ( + format!( + "var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 1e9; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "at most", + ), + ( + format!("var p = new ExportOptionsPNG24(); p.horizontalScale = 50; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"), + "not available yet", + ), + ( + format!("var p = new ExportOptionsJPEG(); p.qualitySetting = 101; app.activeDocument.exportFile({f}, ExportType.JPEG, p);"), + "from 0 to 100", + ), + (format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"), + (format!("app.open({f}, 'RGB');"), "DocumentColorSpace"), + (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), + (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), + (format!("app.open({f}, undefined, 5);"), "PDFFileOptions"), + ("app.userInteractionLevel = 'quiet';".into(), "UserInteractionLevel"), + (format!("app.open({});", quoted(&dir.join("x.svg"))), "open needs a File"), + ]; + for (case, wanted) in &cases { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(wanted), "{case}: {e}"); + } + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&dir.join("missing.svg")))); + assert!(e.contains(crate::script::files::NOT_FOUND), "{e}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().path, None); + let _ = std::fs::remove_dir_all(base); +} + +/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a +/// plain object throw a `TypeError`, and a `File` whose hidden path property a script set keeps its +/// own path, so nothing is written or opened at the path the script put there. +#[test] +fn a_forged_file_is_refused() { + let base = folder("forged"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("real.svg"), "").unwrap(); + std::fs::write(base.join("outside/secret.svg"), "").unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let (x, real) = (quoted(&dir.join("x.svg")), quoted(&dir.join("real.svg"))); + let (out, secret) = (quoted(&base.join("outside/x.svg")), quoted(&base.join("outside/secret.svg"))); + let calls = |f: &str, read: &str| { + [format!("app.activeDocument.saveAs({f});"), format!("app.activeDocument.exportFile({f}, ExportType.SVG);"), format!("app.open({read});")] + }; + for made in ["Object.create(File.prototype)", "{}"] { + let make = |p: &str| format!("(function () {{ var f = {made}; f.__vcPath = {p}; return f; }})()"); + for case in calls(&make(&x), &make(&real)) { + let text = format!("Folder.userData; try {{ {case} vc.log('ran'); }} catch (e) {{ vc.log([e.name, e.message]); }}"); + let log = logged(&mut s, &base, &text); + assert_eq!(log[0][0], json!("TypeError"), "{case}: {log}"); + assert!(log[0][1].as_str().unwrap().contains("needs a File"), "{case}: {log}"); + } + } + let moved = |from: &str, to: &str| format!("(function () {{ var f = new File({from}); f.__vcPath = {to}; return f; }})()"); + for case in calls(&moved(&out, &x), &moved(&secret, &real)) { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(DENIED), "{case}: {e}"); + } + assert!(!dir.join("x.svg").exists() && !dir.join("x.svg.svg").exists(), "nothing is written at the forged path"); + assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1); + assert_eq!(s.documents().len(), 1, "nothing is opened"); + assert_eq!(s.active().unwrap().path, None); + let _ = std::fs::remove_dir_all(base); +} + +/// A document from an earlier run is stale, and saving it throws. +#[test] +fn a_stale_document_is_not_saved() { + let base = folder("stale"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + run(&mut s, &base, "#targetengine keep\nvar held = app.activeDocument;").unwrap(); + let e = failure(&mut s, &base, &format!("#targetengine keep\nFolder.userData; held.saveAs(new File({}));", quoted(&dir.join("x.svg")))); + assert!(e.contains("Stale document"), "{e}"); + assert!(!dir.join("x.svg").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// `open` applies the page and crop box of its options to a PDF. +#[test] +fn open_takes_the_page_and_crop_box_of_its_options() { + let base = folder("pdf"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + let pdf = dir.join("two.pdf"); + s.execute("file.saveAs", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap(); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX}});\n\ + vc.log(g.documentColorSpace);", + quoted(&pdf) + ), + ); + assert_eq!(out, json!(["DocumentColorSpace.CMYK"])); + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 3}});", quoted(&pdf))); + assert!(!e.is_empty(), "a page the file does not have"); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1, "one page"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index c962bf9679..e46fd9f77d 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -7,8 +7,10 @@ //! `File` and `new Folder(path)` always a `Folder`, while `File(path)` gives a `Folder` when the //! host's `stat` says the path is a folder, and `Folder(path)` a `File` when it is a file. Two //! objects for one path are different objects. An object keeps its path in the host's platform -//! form, its `error` text, the id of the file it has open (or -1), the encoding set before `open` -//! and its line feed, in properties that are not enumerable; every name the getters give comes from +//! form in an internal slot that only the classes' own methods set ([`Class::FsEntry`]), so an +//! object a script makes with `Object.create(File.prototype)` is not a `File`. It keeps its `error` +//! text, the id of the file it has open (or -1), the encoding set before `open` and its line feed +//! in properties that are not enumerable; every name the getters give comes from //! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's //! `current`. //! @@ -47,7 +49,57 @@ impl Classes { } } -const PATH: &str = "__vcPath"; +/// The one key of the [`crate::Data`] object that stands for a `File` given to a member of a host +/// class ([`crate::HostClass`]), with the file's path in the host's platform form as its value. A +/// plain object a script made that carries the key is refused. +pub const FILE_REF_KEY: &str = "\u{0}fileRef"; + +/// The path of the `File` that `d` stands for ([`FILE_REF_KEY`]). +pub fn file_ref_path(d: &crate::Data) -> Option<&str> { + let crate::Data::Object(items) = d else { return None }; + match items.as_slice() { + [(k, crate::Data::String(path))] if k == FILE_REF_KEY => Some(path), + _ => None, + } +} + +impl Interp { + /// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is + /// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads + /// it; `None` for any other object, one made with `Object.create(File.prototype)` included. + pub(crate) fn file_ref_of(&self, id: ObjId) -> JsResult> { + let Some(c) = &self.files else { return Ok(None) }; + let o = self.object(id)?; + if o.proto != Some(c.file_proto) { + return Ok(None); + } + Ok(match &o.class { + Class::FsEntry(s) => Some(crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(s.to_rust_string()))])), + _ => None, + }) + } +} + +/// The path of `o` when the `File` or `Folder` class made it. +fn own_path(i: &Interp, o: ObjId) -> JsResult> { + Ok(match &i.object(o)?.class { + Class::FsEntry(s) => Some(Value::String(s.clone())), + _ => None, + }) +} + +/// Sets the path of the `File` or `Folder` `o` to `fs`, a path the host gave. +fn set_path(i: &mut Interp, o: ObjId, fs: Value) -> JsResult<()> { + let Value::String(s) = fs else { return Err(i.type_error("File: the host gave no path")) }; + i.rooted(&[Value::Object(o), Value::String(s.clone())], |i| i.reserve_heap(string_bytes(s.len())))?; + if let Some(ob) = i.heap.object_mut(o) + && let Class::FsEntry(path) = &mut ob.class + { + *path = s; + } + Ok(()) +} + const ERROR: &str = "__vcError"; const HANDLE: &str = "__vcHandle"; const RUN: &str = "__vcRun"; @@ -103,7 +155,7 @@ fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> /// `Folder`. fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value)> { if let Some(o) = this.as_object() - && let path @ Value::String(_) = slot(i, o, PATH)? + && let Some(path) = own_path(i, o)? { return Ok((o, path)); } @@ -114,7 +166,7 @@ fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value /// `Folder`, or `String(x)`, which may hold URI escapes. fn path_text(i: &mut Interp, x: &Value) -> JsResult<(Value, bool)> { if let Some(o) = x.as_object() - && let path @ Value::String(_) = slot(i, o, PATH)? + && let Some(path) = own_path(i, o)? { return Ok((path, true)); } @@ -143,12 +195,12 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult JsResult { + let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) }; let line_feed = host_value(i, "lineFeed")?; - i.rooted(&[fs.clone(), line_feed.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 6 * PROP_BYTES)?; - let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[fs, line_feed.clone()], |i| { + i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?; + let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto))); i.rooted(&[Value::Object(o)], |i| { - set_slot(i, o, PATH, fs.clone())?; set_slot(i, o, ERROR, Value::str(""))?; set_slot(i, o, HANDLE, Value::Number(-1.0))?; set_slot(i, o, RUN, Value::Number(-1.0))?; @@ -393,7 +445,7 @@ fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } let p = parse(i, &arg(args, 0))?; let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; - set_slot(i, o, PATH, fs)?; + set_path(i, o, fs)?; Ok(Value::Bool(true)) } @@ -482,7 +534,7 @@ fn rename(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult), /// An object of a class a host defined ([`crate::host_classes`]). Host(crate::host_classes::HostObj), + /// A `File` or `Folder` ([`crate::file_classes`]) and its path in the host's platform form, + /// which only the classes' own methods set. + FsEntry(Str), } /// What an XML value is. @@ -314,7 +317,7 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary | Class::ForIn(_) | Class::Host(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::FsEntry(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", @@ -648,7 +651,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = BOUND_ARG_BYTES * args.len(); } Class::Arguments(map) => work.push(map.env.0), - Class::String(s) => strings.add(s), + Class::String(s) | Class::FsEntry(s) => strings.add(s), Class::RegExp(re) => { if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) { strings.bytes += re.heap_bytes(); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index f34c9cff8e..a639dbd0cb 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -261,13 +261,21 @@ impl Interp { if r.ancestors.len() >= r.limits.depth { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } + // A `File` reads as its path ([`crate::FILE_REF_KEY`]). + if r.hosted + && let Some(file) = self.file_ref_of(id)? + { + let len = crate::file_ref_path(&file).map_or(0, str::len); + self.charge_reading(r, len.saturating_mul(3).saturating_add(2))?; + return Ok(file); + } 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())); } 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), - Class::Ordinary => { + Class::Ordinary | Class::FsEntry(_) => { let o = self.object(id)?; if o.props.len() > r.limits.entries { return Err(self.data_error(r, ErrorType::Range, "has too many entries")); @@ -313,7 +321,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && name == crate::HOST_REF_KEY { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..45f6aa61e4 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -81,6 +81,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; +pub use file_classes::{FILE_REF_KEY, file_ref_path}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..5e020a2116 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6607,6 +6607,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written No s’ha pogut escriure el fitxer de l’script @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi +@msg Script file is read-only El fitxer de l’script és només de lectura @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..a0ae87170c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5392,6 +5392,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file could not be written Soubor skriptu nelze zapsat @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis +@msg Script file is read-only Soubor skriptu je jen pro čtení @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..a068797076 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -87,6 +87,7 @@ @msg Script file could not be written Scriptfilen kunne ikke skrives @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning +@msg Script file is read-only Scriptfilen er skrivebeskyttet @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..ad2653ea36 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4968,6 +4968,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file could not be written Skriptdatei konnte nicht geschrieben werden @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet +@msg Script file is read-only Skriptdatei ist schreibgeschützt @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..3ead7c9a10 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2805,6 +2805,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή +@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..8003e265c2 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5079,6 +5079,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file could not be written No se pudo escribir el archivo del script @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura +@msg Script file is read-only El archivo del script es de solo lectura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..d8933598d0 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5320,6 +5320,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten +@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..70e88ea0de 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5038,6 +5038,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file could not be written Le fichier du script n’a pas pu être écrit @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture +@msg Script file is read-only Le fichier du script est en lecture seule @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..d12d3d8a3b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7754,6 +7754,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है +@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..51a731132b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5910,6 +5910,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file could not be written A parancsfájl fájlját nem sikerült írni @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva +@msg Script file is read-only A parancsfájl fájlja csak olvasható @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..7e041bfecb 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8748,6 +8748,7 @@ breakText Glyphs Glif @msg Script file could not be written File skrip tidak dapat ditulis @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis +@msg Script file is read-only File skrip hanya dapat dibaca @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..cc67a9be3a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5106,6 +5106,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Impossibile scrivere il file dello script @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura +@msg Script file is read-only Il file dello script è di sola lettura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..2bd2dad0b2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5941,6 +5941,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file could not be written スクリプトのファイルを書き込めませんでした @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません +@msg Script file is read-only スクリプトのファイルは読み取り専用です @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..6625e82912 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8602,6 +8602,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის +@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..6cc76d1ef5 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5870,6 +5870,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 +@msg Script file is read-only 스크립트 파일이 읽기 전용입니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..9cec4dc19c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -89,6 +89,7 @@ @msg Script file could not be written Het scriptbestand kon niet worden geschreven @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven +@msg Script file is read-only Het scriptbestand is alleen-lezen @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..82f4003b2e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5211,6 +5211,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written Nie można zapisać pliku skryptu @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu +@msg Script file is read-only Plik skryptu jest tylko do odczytu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..99e822eb99 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6250,6 +6250,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Não foi possível gravar o arquivo do script @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação +@msg Script file is read-only O arquivo do script é somente leitura @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..132428a948 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5101,6 +5101,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file could not be written Не удалось записать файл скрипта @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи +@msg Script file is read-only Файл скрипта доступен только для чтения @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..3398eaf74f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4977,6 +4977,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file could not be written Skriptets fil kunde inte skrivas @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning +@msg Script file is read-only Skriptets fil är skrivskyddad @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..b70ea0e97e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4813,6 +4813,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file could not be written Betiğin dosyası yazılamadı @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil +@msg Script file is read-only Betiğin dosyası salt okunur @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..9dabba9916 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5090,6 +5090,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file could not be written Не вдалося записати файл скрипту @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису +@msg Script file is read-only Файл скрипту доступний лише для читання @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..cc9ec45896 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5600,6 +5600,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file could not be written Không thể ghi tệp của tập lệnh @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi +@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..11e409f42e 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5597,6 +5597,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 无法写入脚本的文件 @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 +@msg Script file is read-only 脚本的文件为只读 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..287c85cfeb 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2952,6 +2952,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 無法寫入指令碼的檔案 @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 +@msg Script file is read-only 指令碼的檔案為唯讀 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..3ead9da179 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2680,6 +2680,42 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members 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 path's fill, are not defined yet and read as `undefined`. +- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. + `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. + `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` + (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). + `file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the + format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, + https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/); + without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and + `exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and + `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`, + `postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to + `ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF. + `exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()` + and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, + https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), + with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, more than 0 and at + most 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and + `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and + `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s + `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with + `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of + each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, + `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. + VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the + command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open + document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is + read-only`; and the files a command reads or writes besides the one named, such as an SVG's linked files, are + read and written only where the script's folders allow. `userInteractionLevel` does not change what a command + does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the + format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with + `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the + visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and + when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws + an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help + pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default + keeps the preset's value. A bad value throws an error before anything is written. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..0f5208319d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +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, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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 d14830b6b7f1060c9f0eceb9dc3cbe83c3d601a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:23:24 -0800 Subject: [PATCH 02/20] Scripts: saveAs and exportFile refuse a file open for writing and scales under 1% A save or export to a file that a File object holds open for writing throws "Script file is open for writing", and a command the script runs does not write such a file besides the one named (an SVG's images), so the bytes the File writes at the end of the run do not replace the output. horizontalScale and verticalScale take 1 to 776.19, since a raster export writes at least 0.01 pixels per point. The script checker reports a document's saveAs and exportFile as file writes, and the host name check lists the save, export and open names, option classes and enumerations. --- crates/engine/src/file_access.rs | 26 ++++++-- crates/engine/src/script/dom/save_open.rs | 7 +- crates/engine/src/script/files.rs | 14 ++-- crates/engine/src/tests/script_save_open.rs | 66 ++++++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 29 ++++++-- crates/scriptcheck/src/analyze/features.rs | 12 +++- crates/scriptcheck/src/catalog.rs | 3 + crates/scriptcheck/src/tests.rs | 28 ++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 11 ++-- 34 files changed, 198 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 4769146ad8..afab0e95b0 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -284,6 +284,9 @@ pub(crate) struct ScriptGate { pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, + /// The real paths of the files the script's `File` objects hold open for writing, which a + /// command does not write: the run's end would write the objects' bytes over them. + pub(crate) held: Vec, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } @@ -312,7 +315,8 @@ impl ScriptGate { }; // A read-only file is not written over, also where a rename could replace it. let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); - !read_only && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))) + let held = matches!(access, Access::Write) && self.held.contains(&real); + !read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real))) }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -920,8 +924,13 @@ mod tests { #[test] fn a_narrowed_scope_keeps_the_script_gates_of_both() { let (base, _) = folders("narrowed-gate"); - let gate = - |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &str| ScriptGate { + read: ScriptScope::of_folder(&base.join(dir)), + write: ScriptScope::default(), + documents: vec![], + held: vec![], + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let reads = |saved: ScopeHandle, gate_here: Option| { let narrowed = match gate_here { @@ -944,7 +953,8 @@ mod tests { #[test] fn a_scope_narrowed_several_times_keeps_every_gate() { let (base, _) = folders("narrowed-thrice"); - let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = + |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], held: vec![], also: None }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); @@ -964,7 +974,13 @@ mod tests { let (base, _) = folders("gate-read-only"); let out = base.join("out/kept.svg"); std::fs::write(&out, "").unwrap(); - let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::of_folder(&base.join("out")), documents: vec![], also: None }; + let gate = ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::of_folder(&base.join("out")), + documents: vec![], + held: vec![], + also: None, + }; let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg"))); let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok())); assert_eq!(check(&kept), (true, true)); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index ebdebc4c10..c76ae0f44e 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -48,6 +48,9 @@ use super::{ /// The most a scale factor of an export takes, in percent. pub const MAX_SCALE_PERCENT: f64 = 776.19; +/// The least a scale factor of a raster export takes, in percent: `document.export` writes at least +/// 0.01 pixels per point. +pub const MIN_SCALE_PERCENT: f64 = 1.0; /// What the run keeps for these members: whether `userInteractionLevel` is `DONTDISPLAYALERTS`. #[derive(Default)] @@ -363,8 +366,8 @@ fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map) -> Data::Number(n) if n.is_finite() => *n, _ => return Err(HostError::Type(format!("{what} must be a finite number"))), }; - if n <= 0.0 || n > MAX_SCALE_PERCENT { - return Err(HostError::Range(format!("{what} must be more than 0 and at most 776.19"))); + if !(MIN_SCALE_PERCENT..=MAX_SCALE_PERCENT).contains(&n) { + return Err(HostError::Range(format!("{what} must be at least 1 and at most 776.19"))); } let key = if name == "horizontalScale" { "_h" } else { "_v" }; p.insert(key.into(), json!(n)); diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 40b1fe0465..7886210567 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -116,6 +116,7 @@ pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing"; pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text"; pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; pub(crate) const READ_ONLY: &str = "Script file is read-only"; +pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; @@ -460,11 +461,12 @@ impl Disk { } /// The gate for a command the script runs: the places it reads and writes now, and the files of - /// the open documents, `documents`. + /// the open documents, `documents`, but not the files its `File` objects hold open for writing. pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { // A save, export or open of a `File` the script names reads and writes as its `File` would. let documents = if self.exact { Vec::new() } else { documents }; - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } + let held = self.open.values().filter_map(|o| o.target.clone()).collect(); + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, also: None } } /// The files written since this was last asked, to name in the report. @@ -684,10 +686,14 @@ impl Disk { } /// The real path a save or export of the document to `path` writes, as a `File` opened for - /// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, and a - /// read-only file is not written over. + /// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, a + /// read-only file is not written over, and neither is a file a `File` object holds open for + /// writing, whose bytes the run's end would write over the saved file. pub(crate) fn save_target(&self, path: &str) -> Result { let real = self.target(path, true)?; + if self.open.values().any(|o| o.target.as_deref() == Some(real.as_path())) { + return Err(OPEN_FOR_WRITING); + } match std::fs::metadata(&real) { Ok(m) if !m.is_file() => Err(NOT_REGULAR), Ok(m) if m.permissions().readonly() => Err(READ_ONLY), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 809fed0ef8..8518f14365 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -271,6 +271,32 @@ fn an_open_documents_file_is_not_saved_over_without_a_grant() { let _ = std::fs::remove_dir_all(base); } +/// A save or export to a file a `File` object holds open for writing throws, so the object's bytes +/// written at the end of the run do not replace the saved document. +#[test] +fn a_file_open_for_writing_is_not_saved_over() { + let base = folder("openhandle"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (name, call) in + [("a.svg", "app.activeDocument.saveAs(new File(p));"), ("b.png", "app.activeDocument.exportFile(new File(p), ExportType.PNG24);")] + { + let p = quoted(&dir.join(name)); + let log = logged( + &mut s, + &base, + &format!( + "Folder.userData; var p = {p}, w = new File(p); w.open('w'); w.write('pending');\ntry {{ {call} vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}" + ), + ); + assert!(log[0].as_str().unwrap().contains(crate::script::files::OPEN_FOR_WRITING), "{name}: {log}"); + assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), "pending", "{name}: the File's own bytes"); + assert_eq!(s.active().unwrap().path, None, "{name}: the document's file is unchanged"); + } + let _ = std::fs::remove_dir_all(base); +} + /// A file `open` reads besides the one it names, here an SVG's linked image, is read only where /// the script's grants allow, though it is an open document's file. #[test] @@ -282,7 +308,7 @@ fn open_reads_linked_files_only_where_the_script_may() { std::fs::write(&linked, "").unwrap(); s.execute("document.open", &json!({"path": linked.to_string_lossy()})).unwrap(); assert!(s.active().unwrap().path.is_some(), "the linked file is an open document's file"); - let href = linked.to_string_lossy().replace('\\', "/"); + let href = linked.to_string_lossy().replace('\\', "/").replace('&', "&").replace('<', "<").replace('\'', "'"); std::fs::write( dir.join("page.svg"), format!(""), @@ -343,6 +369,38 @@ fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() { let _ = std::fs::remove_dir_all(base); } +/// An export does not write a file it writes besides the one named, here an SVG's image, while a +/// `File` object holds it open for writing, and so writes nothing. +#[test] +fn an_svg_export_does_not_write_an_image_a_file_holds_open() { + let base = folder("svgheld"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pic = base.join("outside/pic.png"); + std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap(); + let svg = dir.join("a.svg"); + let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG, new ExportOptionsSVG());", quoted(&svg)); + logged(&mut s, &base, &format!("Folder.userData; {export}")); + let mut images: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect(); + assert_eq!(images.len(), 1, "the embedded image is written beside the SVG: {images:?}"); + let image = images.remove(0); + std::fs::remove_file(&svg).unwrap(); + let log = logged( + &mut s, + &base, + &format!( + "Folder.userData; var w = new File({}); w.open('w'); w.write('pending');\ntry {{ {export} vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}", + quoted(&image) + ), + ); + assert!(log[0].as_str().unwrap().contains(DENIED), "{log}"); + assert!(!svg.exists(), "the SVG is not written when its image may not be"); + assert_eq!(std::fs::read_to_string(&image).unwrap(), "pending", "the File's own bytes"); + let _ = std::fs::remove_dir_all(base); +} + /// A link inside a granted folder that leads out of it is followed and refused. #[cfg(unix)] #[test] @@ -404,6 +462,12 @@ fn bad_arguments_are_refused_with_an_error() { ), "at most", ), + ( + format!( + "var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 0.5; app.activeDocument.exportFile({f}, ExportType.PNG24, p);" + ), + "at least 1", + ), ( format!("var p = new ExportOptionsPNG24(); p.horizontalScale = 50; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"), "not available yet", diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..26b476a0b6 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -37,12 +37,14 @@ 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.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), + ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.saveAs` and `close` throw "not available yet". +/// documents; `Document.close` throws "not available yet". `app.open` reads the file it is given. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -81,7 +83,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + open selection typename userInteractionLevel userInteractionLevel=", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), @@ -90,7 +92,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + rulerUnits selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), @@ -121,12 +123,27 @@ const INSIDE: &[(&str, &str)] = &[ ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + // The enumerations of saving, exporting and opening. + ("", "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint UserInteractionLevel"), + ( + "Compatibility.", + "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ + ILLUSTRATOR19 ILLUSTRATOR8 ILLUSTRATOR9 JAPANESEVERSION3", + ), + ("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"), + ("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"), + ("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"), + ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), + ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), + ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), + ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), ]; -/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. +/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`, +/// the page item types and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ + ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..354a0540aa 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -287,6 +287,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; + // `doc['saveAs'](f)`: a document method named by a string literal in brackets. + if is(h0, "]") + && is(h2, "[") + && let Some(name) = h1.filter(|s| s.kind == T::Str) + && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + return; + } let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { @@ -301,7 +311,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..ee5b63dfb2 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] = &["exportFile", "saveAs"]; + // 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..12e5527811 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,34 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// A document's `saveAs` and `exportFile` write the file they are given; `app.open` only reads one. +#[test] +fn save_as_and_export_file_write_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = app.open(f);\n", + "d.saveAs(f);\n", + "app.activeDocument.exportFile(f, ExportType.PNG24);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + +/// `saveAs` and `exportFile` called with their names as string literals in brackets write the file +/// too; reading the method without calling it does not. +#[test] +fn save_as_and_export_file_in_brackets_write_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "app.activeDocument['open'](f);\n", + "app.activeDocument[\"saveAs\"](f);\n", + "var d = app.activeDocument; d['exportFile'] (f, ExportType.SVG);\n", + "var n = d['saveAs'];\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); +} + /// 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/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5e020a2116..4cb24ffa76 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6608,6 +6608,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi @msg Script file is read-only El fitxer de l’script és només de lectura +@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a0ae87170c..4ac10d6ac7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5393,6 +5393,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis @msg Script file is read-only Soubor skriptu je jen pro čtení +@msg Script file is open for writing Soubor skriptu je otevřený pro zápis @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index a068797076..5aab6605f6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -88,6 +88,7 @@ @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning @msg Script file is read-only Scriptfilen er skrivebeskyttet +@msg Script file is open for writing Scriptfilen er åben for skrivning @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ad2653ea36..a0872671f8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4969,6 +4969,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet @msg Script file is read-only Skriptdatei ist schreibgeschützt +@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3ead7c9a10..db00e18a27 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2806,6 +2806,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή @msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση +@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8003e265c2..28dd4a176c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5080,6 +5080,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura @msg Script file is read-only El archivo del script es de solo lectura +@msg Script file is open for writing El archivo del script está abierto para escritura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d8933598d0..a56f4feca6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5321,6 +5321,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten @msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa +@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 70e88ea0de..52ce992d66 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5039,6 +5039,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture @msg Script file is read-only Le fichier du script est en lecture seule +@msg Script file is open for writing Le fichier du script est ouvert en écriture @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index d12d3d8a3b..111037fda0 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7755,6 +7755,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है @msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है +@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 51a731132b..78093bf132 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5911,6 +5911,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva @msg Script file is read-only A parancsfájl fájlja csak olvasható +@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7e041bfecb..5badf608d7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8749,6 +8749,7 @@ breakText Glyphs Glif @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis @msg Script file is read-only File skrip hanya dapat dibaca +@msg Script file is open for writing File skrip sedang dibuka untuk ditulis @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cc67a9be3a..9b6018956e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5107,6 +5107,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura @msg Script file is read-only Il file dello script è di sola lettura +@msg Script file is open for writing Il file dello script è aperto in scrittura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 2bd2dad0b2..348f7aa3f3 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5942,6 +5942,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません @msg Script file is read-only スクリプトのファイルは読み取り専用です +@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 6625e82912..50a7c83e6d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8603,6 +8603,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის @msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია +@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 6cc76d1ef5..0db12b4e59 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5871,6 +5871,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 @msg Script file is read-only 스크립트 파일이 읽기 전용입니다 +@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9cec4dc19c..929dc790fe 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -90,6 +90,7 @@ @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven @msg Script file is read-only Het scriptbestand is alleen-lezen +@msg Script file is open for writing Het scriptbestand is geopend voor schrijven @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 82f4003b2e..1f14688dd1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5212,6 +5212,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu @msg Script file is read-only Plik skryptu jest tylko do odczytu +@msg Script file is open for writing Plik skryptu jest otwarty do zapisu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 99e822eb99..a70f1c64a6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6251,6 +6251,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação @msg Script file is read-only O arquivo do script é somente leitura +@msg Script file is open for writing O arquivo do script está aberto para gravação @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 132428a948..1ffaea5dab 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5102,6 +5102,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи @msg Script file is read-only Файл скрипта доступен только для чтения +@msg Script file is open for writing Файл скрипта открыт для записи @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 3398eaf74f..efb575f716 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4978,6 +4978,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning @msg Script file is read-only Skriptets fil är skrivskyddad +@msg Script file is open for writing Skriptets fil är öppen för skrivning @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b70ea0e97e..e353434aaa 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4814,6 +4814,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil @msg Script file is read-only Betiğin dosyası salt okunur +@msg Script file is open for writing Betiğin dosyası yazmak için açık @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 9dabba9916..7e3b137acc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5091,6 +5091,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису @msg Script file is read-only Файл скрипту доступний лише для читання +@msg Script file is open for writing Файл скрипту відкрито для запису @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index cc9ec45896..9af45922ab 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5601,6 +5601,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi @msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc +@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 11e409f42e..dc6577be86 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5598,6 +5598,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 @msg Script file is read-only 脚本的文件为只读 +@msg Script file is open for writing 脚本的文件已以写入方式打开 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 287c85cfeb..a97d0185e1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2953,6 +2953,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 @msg Script file is read-only 指令碼的檔案為唯讀 +@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 diff --git a/docs/mcp.md b/docs/mcp.md index 3ead9da179..acb6c3317f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,7 +2558,8 @@ 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`, + File object's `length`, `hidden` or `readonly` counts too, and so does a document's `saveAs` or `exportFile`), + `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, @@ -2695,8 +2696,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()` and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), - with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, more than 0 and at - most 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and + with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to + 776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with @@ -2706,7 +2707,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is - read-only`; and the files a command reads or writes besides the one named, such as an SVG's linked files, are + read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs` + and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the + files a command reads or writes besides the one named, such as an SVG's linked files, are read and written only where the script's folders allow. `userInteractionLevel` does not change what a command does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with From f31cb42fd8ed8ceaa094d980e010883e1560ee72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:49:59 -0800 Subject: [PATCH 03/20] Scripts: unlisted save, export and open options throw, and an object's own saveAs is not a file write - saveAs, exportFile and app.open throw " has no option " for a property their option class's help page does not list, instead of leaving it out. An undefined property is still left out, and PDFFileOptions also takes its read-only typename and parent. - The script checker no longer reports a file write for saveAs or exportFile called on a variable holding the script's own object literal that defines that method, with `.` or in brackets. It reports it again once the method is assigned or deleted, the object is indexed with a computed key, or another name may hold the object. - The read-only file test checks the open-document grant on its own, with no folder scope that also covers the file. --- crates/engine/src/file_access.rs | 7 ++- crates/engine/src/script/dom/save_open.rs | 22 +++++-- crates/engine/src/tests/script_save_open.rs | 15 ++++- crates/scriptcheck/src/analyze.rs | 54 ++++++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 63 ++++++++++++++++++++- crates/scriptcheck/src/tests.rs | 51 +++++++++++++++++ docs/mcp.md | 5 +- 7 files changed, 203 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 9e05d92ce7..0eeed498e2 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -992,14 +992,17 @@ mod tests { }; let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg"))); let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok())); + // The open document's file is the only grant: no folder scope covers it. + let documents = ScriptGate { write: ScriptScope::default(), documents: vec![kept.clone()], ..gate.clone() }; + let document_write = || with_script_gate(documents.clone(), || check_write(&kept).is_ok()); assert_eq!(check(&kept), (true, true)); + assert!(document_write(), "an open document's file is written"); let mut perms = std::fs::metadata(&out).unwrap().permissions(); perms.set_readonly(true); std::fs::set_permissions(&out, perms.clone()).unwrap(); assert_eq!(check(&kept), (false, true), "a read-only file is read but not written"); assert!(check(&fresh).0, "a new file next to it is written"); - let documents = ScriptGate { documents: vec![kept.clone()], ..gate.clone() }; - assert!(!with_script_gate(documents, || check_write(&kept).is_ok()), "also when it is an open document's file"); + assert!(!document_write(), "also when it is an open document's file"); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); std::fs::set_permissions(&out, perms).unwrap(); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index c76ae0f44e..f54c2f3f0b 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -27,10 +27,12 @@ //! and when one of those files may not be written, none of them is. //! - An option the classes here map is applied; a listed option that is not mapped is accepted at //! the default its help page gives and throws an error that says it is not available yet at any -//! other value; a property the help pages do not list is left out. With `pDFPreset` named, a -//! `PDFSaveOptions` option still at a new object's default keeps the preset's value. +//! other value; a property the help pages do not list throws an error that names it, unless it is +//! `undefined`. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default +//! keeps the preset's value. //! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: -//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. +//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property +//! but `typename` and `parent` throws the same error, unless it is `undefined`. //! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The //! commands a script runs never show a dialog, so the level does not change what they do, and it //! never allows a file the script's grants do not. @@ -131,6 +133,11 @@ fn not_available(class: &str, name: &str) -> HostError { HostError::Error(format!("{class}.{name} is not available yet")) } +/// The error a property that the help page of `class` does not list throws. +fn not_an_option(class: &str, name: &str) -> HostError { + HostError::Error(format!("{class} has no option {name}")) +} + fn whole_in(d: &Data, what: &str, lo: u64, hi: u64) -> std::result::Result { match d { Data::Number(n) => { @@ -522,7 +529,7 @@ fn options_params(class: &OptionClass, d: &Data) -> std::result::Result {} Some(_) => return Err(not_available(class.name, k)), - None => {} + None => return Err(not_an_option(class.name, k)), } } Ok(p) @@ -670,6 +677,9 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())); } for (k, v) in items { + if matches!(v, Data::Undefined) { + continue; + } match k.as_str() { "pageToOpen" => { p.insert("page".into(), json!(whole_in(v, "PDFFileOptions.pageToOpen", 1, 1_000_000)?)); @@ -686,7 +696,9 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { }; p.insert("cropTo".into(), json!(crop)); } - _ => {} + // The read-only members the help page lists. + "typename" | "parent" => {} + _ => return Err(not_an_option("PDFFileOptions", k)), } } } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..9eabe077de 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -64,7 +64,7 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ d.saveAs(new File(dir + '/a.svg'));\n\ var o = new PDFSaveOptions(); vc.log([o.typename, o.compatibility, o.preserveEditability]);\n\ - o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.someOtherName = 3;\n\ + o.compatibility = PDFCompatibility.ACROBAT7; o.viewAfterSaving = false; o.pDFXStandardDescription = undefined;\n\ o.colorCompression = 'CompressionQuality.None';\n\ d.saveAs(new File(dir + '/b.pdf'), o); vc.log(d.name);\n\ var p = new ExportOptionsPNG24(); p.horizontalScale = p.verticalScale = 200; p.artBoardClipping = true;\n\ @@ -481,6 +481,12 @@ fn bad_arguments_are_refused_with_an_error() { (format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"), (format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"), (format!("app.open({f}, undefined, 5);"), "PDFFileOptions"), + (format!("var o = new PDFSaveOptions(); o.trimMark = true; app.activeDocument.saveAs({f}, o);"), "PDFSaveOptions has no option trimMark"), + ( + format!("var p = new ExportOptionsPNG24(); p.transparancy = false; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"), + "ExportOptionsPNG24 has no option transparancy", + ), + (format!("app.open({f}, undefined, {{pageToOpne: 2}});"), "PDFFileOptions has no option pageToOpne"), ("app.userInteractionLevel = 'quiet';".into(), "UserInteractionLevel"), (format!("app.open({});", quoted(&dir.join("x.svg"))), "open needs a File"), ]; @@ -560,7 +566,7 @@ fn open_takes_the_page_and_crop_box_of_its_options() { &mut s, &base, &format!( - "Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX}});\n\ + "Folder.userData; var g = app.open(new File({}), DocumentColorSpace.CMYK, {{pageToOpen: 2, pDFCropToBox: PDFBoxType.PDFMEDIABOX, typename: 'PDFFileOptions', later: undefined}});\n\ vc.log(g.documentColorSpace);", quoted(&pdf) ), @@ -570,5 +576,10 @@ fn open_takes_the_page_and_crop_box_of_its_options() { assert!(!e.is_empty(), "a page the file does not have"); assert_eq!(s.documents().len(), 2); assert_eq!(s.active().unwrap().doc.artboards.len(), 1, "one page"); + // Options left undefined are left out: the file opens as it does without options. + let undefined = format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: undefined, pDFCropToBox: undefined}});", quoted(&pdf)); + logged(&mut s, &base, &undefined); + assert_eq!(s.documents().len(), 3); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 5d01cc8438..6c3177f498 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -495,6 +495,8 @@ struct Saved { shadowed: Option, /// It was a platform name the script had a meaning of its own for. own: bool, + /// What it held in [`Analyzer::writers`], 0 for nothing. + writer: u8, } /// The open brackets and their lines, up to [`crate::Limits::nesting`]; the brackets past that are @@ -566,6 +568,16 @@ struct Analyzer<'s, 'a, 'l> { maybe_files: HashSet, /// `maybe_files` ran out of room: no variable counts as holding a Folder object. maybe_files_full: bool, + /// The variables holding an object literal of the script's own that defines a method named as a + /// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit + /// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing. + writers: HashMap, + /// The object literals being assigned to a variable, the innermost last, each with the bracket + /// depth inside its `{`, up to [`crate::Limits::nesting`] of them. + objects: Vec<(String, usize)>, + /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver + /// that is not such a variable. + index_receiver: u8, /// The platform names ([`platform_name`]) the script declares or assigns a meaning of its own /// for: they no longer stand for the platform's objects. own_names: HashSet, @@ -637,6 +649,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { folders: known.folders.clone(), maybe_files: known.files.difference(&known.folders).cloned().collect(), maybe_files_full: false, + writers: HashMap::new(), + objects: vec![], + index_receiver: 0, own_names: HashSet::new(), scopes: vec![], declared, @@ -742,6 +757,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.group_step(&t, started, before); self.paren_step(&t, before); self.assignment(&t, started); + self.object_key(&t); self.features(&t); self.newer(&t); self.module_check(&t); @@ -841,6 +857,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn bind(&mut self, name: String, path: String) { self.files.remove(&name); self.folders.remove(&name); + self.writers.remove(&name); if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) { self.bound.insert(name, path); } @@ -850,6 +867,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn hold_file(&mut self, name: String, folder: bool) { self.bound.remove(&name); self.folders.remove(&name); + self.writers.remove(&name); if !folder && !self.maybe_files.contains(&name) { if self.acc.room(self.maybe_files.len()) { self.maybe_files.insert(name.clone()); @@ -973,6 +991,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { local: false, shadowed, own: self.own_names.contains(name), + writer: self.writers.get(name).copied().unwrap_or(0), } } @@ -1007,6 +1026,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { self.own_names.remove(&name); } + if saved.writer != 0 { + self.writers.insert(name.clone(), saved.writer); + } else { + self.writers.remove(&name); + } if let Some(hidden) = saved.shadowed && let Some(i) = catalog::DOM_ROOTS.iter().position(|r| *r == name) && let Some(s) = self.shadowed.get_mut(i) @@ -1056,6 +1080,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.bound.remove(name); self.files.remove(name); self.folders.remove(name); + self.writers.remove(name); self.hide_root(name); } @@ -1249,6 +1274,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { local: false, shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), own: platform_name(name), + writer: 0, }; let outside = std::mem::replace(&mut c.saved, empty); if let Some(scope) = self.scopes.last_mut() { @@ -1272,6 +1298,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.start_value(a.name, Operand::Done(Held::File { folder: false })); } else if !a.after_new && t.is("(") { self.start_group(a.name); + } else if !a.after_new && t.is("{") { + // An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]). + self.unbind(&a.name); + if self.objects.len() < self.acc.limits.nesting { + self.objects.push((a.name, self.depth())); + } } else { self.unbind(&a.name); } @@ -1310,6 +1342,28 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// `t` in an object literal assigned to a variable: a `:` directly inside its braces after a key + /// that names a document method writing a file (`{saveAs: …}`, `{'exportFile': …}`) makes the + /// variable one of [`Analyzer::writers`]. A closing brace ends the literals it closes. + fn object_key(&mut self, t: &Sig<'s>) { + let depth = self.depth(); + while self.objects.pop_if(|(_, d)| *d > depth).is_some() {} + if !t.is(":") { + return; + } + let [h0, h1, ..] = self.h; + let Some(name) = self.objects.last().filter(|(_, d)| *d == depth).map(|(n, _)| n.clone()) else { return }; + let key = match h0 { + Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text), + Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)), + _ => return, + }; + let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; + if (is(h1, "{") || is(h1, ",")) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { + *self.writers.entry(name).or_insert(0) |= 1 << i; + } + } + /// The variable that `t` changes to a number or a string, nothing the check follows, and whether /// the change waits for the value on the right. `name += …` and the other compound assignments /// (ECMA-262 3rd edition, section 11.13.2) store their result after that value is read, so the diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7eb89a1fbe..d17a580560 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -84,6 +84,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } } + self.writer_use(t); match t.kind { T::Ident => self.name(t, line), T::Punct => self.punct(t, line), @@ -272,6 +273,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default(); self.setter(&name, h2, h3, line); } + // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. + "[" => self.index_receiver = self.writer_bits(h0, h1), "(" => self.call(line), // `Name.prototype["+"] = …` defines an operator. "=" => { @@ -292,8 +295,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") && is(h2, "[") - && let Some(name) = h1.filter(|s| s.kind == T::Str) - && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + && let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) + && catalog::DOM_FILE_WRITES.contains(&method.as_str()) + && !Self::defines(self.index_receiver, &method) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -313,7 +317,9 @@ 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)) || catalog::DOM_FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) + || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n)) + { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { @@ -336,6 +342,57 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// The methods that `receiver`, which `before` comes before, defines when it is a variable holding + /// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name; + /// 0 for anything else. A receiver the check does not follow may be a document. + fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { + match receiver { + Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), + _ => 0, + } + } + + /// A variable of [`Analyzer::writers`] used before `t` in any way but a member (`local.name`, + /// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or + /// `exportFile` is assigned: another name may hold its object, or its methods may change, so its + /// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`, + /// `local[k] = w`, `delete local.saveAs`). + fn writer_use(&mut self, t: &Sig<'s>) { + let [h0, h1, h2, h3] = self.h; + let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); + let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); + let key = t.is(":") && (is(h1, "{") || is(h1, ",")); + let escaped = if word(h0, "delete") { + // `delete local…` + writer(Some(*t), h0) + } else if let Some(name) = writer(h0, h1) { + // `local` followed by anything but a member, its own assignment or an object key's `:`. + (!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name) + } else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) { + // `local.saveAs = …` + writer(h2, h3) + } else if is(h0, "[") { + // `local[k]` with a key that is not a string literal. + writer(h1, h2).filter(|_| t.kind != T::Str) + } else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) { + // `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) + } else { + None + }; + if let Some(name) = escaped { + self.writers.remove(name); + } + } + + /// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called. + fn defines(bits: u8, method: &str) -> bool { + catalog::DOM_FILE_WRITES.iter().position(|m| *m == method).is_some_and(|i| bits & (1 << i) != 0) + } + /// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object /// (not a property of the same name), or a File or Folder object made in place or held in /// grouping parentheses ([`Sig::file`]). diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index e985fa3d0f..9148f0e93f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -558,6 +558,57 @@ fn save_as_and_export_file_in_brackets_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write +/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one +/// assigned something else since, and for a method the literal does not define, they write the file. +#[test] +fn the_scripts_own_save_as_writes_no_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var local = {saveAs: function () {}, 'n': 1};\n", + "local.saveAs(f);\n", + "local['saveAs'](f);\n", + "app.activeDocument.saveAs(f);\n", + "local.exportFile(f);\n", + "other.saveAs(f);\n", + "local = app.activeDocument;\n", + "local.saveAs(f);\n", + "var t = {x: 1, a: ok ? saveAs : 0, 'exportFile': function () {}};\n", + "t['exportFile'](f);\n", + "t.saveAs(f);\n", + "var activeDocument = {saveAs: function () {}};\n", + "app.activeDocument['saveAs'](f);\n", + "app.activeDocument.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 6, 7, 9, 12, 14, 15][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[5, 6, 7, 9, 12, 14, 15][..])]); +} + +/// Once the script replaces or deletes such a method, indexes the object with a computed key, or +/// lets another name hold the object, its `saveAs` may write a file again. +#[test] +fn a_changed_or_shared_own_save_as_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}, b = {saveAs: function () {}}, c = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}}, e = {saveAs: function () {}}, g = {saveAs: function () {}};\n", + "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", + "a.saveAs = app.activeDocument.saveAs;\n", + "b['saveAs'] = w;\n", + "c[k] = w;\n", + "delete d.saveAs;\n", + "var h = e;\n", + "use(g);\n", + "a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + "d.saveAs(f);\n", + "e.saveAs(f);\n", + "g['saveAs'](f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16][..])); +} + /// 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 4e00790a15..5dd133dc00 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2726,8 +2726,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws - an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`; properties the help - pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default + an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help + pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and + `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. From b82dddc71da4b3b4a9508a2add57df9665bbf1a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:54:03 -0800 Subject: [PATCH 04/20] Docs: G6 and M13 list Document.saveAs, Document.exportFile and app.open --- docs/gaps.md | 3 ++- docs/roadmap.md | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..cecbd9c4c4 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + documents, each document's selection and its page items, and save, export and open documents with + `Document.saveAs`, `Document.exportFile` and `app.open`. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..40c4518f52 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,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, and save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`; the rest of the script document model (layers, artboards, paths, type and the other classes) 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 3a80afcb37c0a9236ba3a7c342c734e9b98a2911 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:59:25 -0800 Subject: [PATCH 05/20] Scripts: only a function expression makes an object's saveAs its own The script checker treats a saveAs or exportFile key of the script's own object literal as the script's own method only when its value is a function expression. A key holding another value, such as a document's method, is still reported as a file write when called, and so is a key whose last value in the literal is not a function expression. --- crates/scriptcheck/src/analyze.rs | 23 ++++++++++++++++------- crates/scriptcheck/src/tests.rs | 8 ++++++-- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 6c3177f498..dae8816eb1 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1342,24 +1342,33 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// `t` in an object literal assigned to a variable: a `:` directly inside its braces after a key - /// that names a document method writing a file (`{saveAs: …}`, `{'exportFile': …}`) makes the - /// variable one of [`Analyzer::writers`]. A closing brace ends the literals it closes. + /// `t` in an object literal assigned to a variable: a function expression directly inside its + /// braces as the value of a key that names a document method writing a file + /// (`{saveAs: function …}`, `{'exportFile': function …}`) makes the variable one of + /// [`Analyzer::writers`], and any other value of that key (`{saveAs: d.saveAs}`) takes the method + /// out again. A closing brace ends the literals it closes. fn object_key(&mut self, t: &Sig<'s>) { let depth = self.depth(); while self.objects.pop_if(|(_, d)| *d > depth).is_some() {} - if !t.is(":") { + let [h0, h1, h2, _] = self.h; + if !is(h0, ":") || !(is(h2, "{") || is(h2, ",")) { return; } - let [h0, h1, ..] = self.h; let Some(name) = self.objects.last().filter(|(_, d)| *d == depth).map(|(n, _)| n.clone()) else { return }; - let key = match h0 { + let key = match h1 { Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text), Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)), _ => return, }; let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; - if (is(h1, "{") || is(h1, ",")) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { + if !t.word("function") { + let left = self.writers.get(&name).map_or(0, |bits| bits & !(1 << i)); + if left == 0 { + self.writers.remove(&name); + } else { + self.writers.insert(name, left); + } + } else if self.writers.contains_key(&name) || self.acc.room(self.writers.len()) { *self.writers.entry(name).or_insert(0) |= 1 << i; } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 9148f0e93f..8d6bac9fa0 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -585,7 +585,8 @@ fn the_scripts_own_save_as_writes_no_file() { } /// Once the script replaces or deletes such a method, indexes the object with a computed key, or -/// lets another name hold the object, its `saveAs` may write a file again. +/// lets another name hold the object, its `saveAs` may write a file again, and so may a `saveAs` key +/// whose last value in the literal is not a function expression. #[test] fn a_changed_or_shared_own_save_as_writes_a_file() { let r = report(concat!( @@ -605,8 +606,11 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "d.saveAs(f);\n", "e.saveAs(f);\n", "g['saveAs'](f);\n", + "var m = {saveAs: d.saveAs}, n = {saveAs: function () {}, saveAs: d.saveAs};\n", + "m.saveAs(f);\n", + "n.saveAs(f);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19][..])); } /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing From 5f444df2957c0abdad17d6b37ab7063104c7b322 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:48:26 -0800 Subject: [PATCH 06/20] Save: a refused file ends a save of several files after the writer refuses it When the file access in force refuses one of the files a save writes, the save gives that file to its writer for the error, as before, and then returns the error even when the writer did not refuse it, so the other files are not written. --- crates/engine/src/cmd/fileio/save.rs | 2 + crates/engine/src/tests/script_save_open.rs | 41 +++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 94187808c6..550b52f414 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1078,6 +1078,8 @@ impl SaveJob { && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) { write(p, bytes)?; + // A writer that does not check the file access writes none of the others. + return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 9eabe077de..126c7c3947 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -207,6 +207,47 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { let _ = std::fs::remove_dir_all(base); } +/// When the writer a save is given does not check the file access itself, a save of several files +/// still writes none of them after the refused one. +#[test] +fn a_refused_file_stops_a_save_whose_writer_does_not_check() { + use crate::cmd::fileio::{SaveMode, save_job, save_plan}; + use crate::file_access::{ScriptGate, ScriptScope, with_script_gate}; + let base = folder("unchecked"); + let dir = base.join("outside"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let params = json!({"path": dir.join("a.eps").to_string_lossy(), "format": "eps", "useArtboards": true}); + let plan = save_plan(&s, SaveMode::SaveAs, ¶ms).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::of_folder(&dir), documents: vec![], held: vec![], also: None }; + let (mut refused, mut written) = (None, vec![]); + let make_read_only = |paths: &[&str]| { + let last = paths.last().map(|p| p.to_string()).unwrap(); + std::fs::write(&last, b"").unwrap(); + let mut perms = std::fs::metadata(&last).unwrap().permissions(); + perms.set_readonly(true); + std::fs::set_permissions(&last, perms).unwrap(); + refused = Some(last); + None + }; + let r = with_script_gate(gate, || { + job.write_unless(make_read_only, |p, _| { + written.push(p.to_string()); + Ok(()) + }) + }); + assert!(r.is_err(), "{r:?}"); + let refused = refused.unwrap(); + assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + let mut perms = std::fs::metadata(&refused).unwrap().permissions(); + #[allow(clippy::permissions_set_readonly_false)] + perms.set_readonly(false); + std::fs::set_permissions(&refused, perms).unwrap(); + let _ = std::fs::remove_dir_all(base); +} + /// Every path goes through the script's file grants, as a `File` opened for reading or writing. #[test] fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { From c4edd76fc8b929b5dd86ddfb29d01e3197dc1d27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:00:50 -0800 Subject: [PATCH 07/20] Scripts: only a whole var value makes an object's saveAs the script's own The checker treats `x.saveAs(f)` as the script's own method only when `x` was declared by a `var` statement, directly in a function body or the global code, whose first name takes an object literal with a `saveAs` or `exportFile` function as its whole value. The name counts from the end of the statement. - A literal given in a branch (`if (c) var e = {...}`), one the value goes on from (`{...} && doc`), one given by an assignment or to a later name of the statement, and a call inside the literal keep reporting the write. - A function that gives an outer variable another value removes the exemption after the function body. --- crates/scriptcheck/src/analyze.rs | 76 +++++++++++++++++++++++-------- crates/scriptcheck/src/tests.rs | 35 ++++++++++++-- 2 files changed, 88 insertions(+), 23 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index dae8816eb1..9056752744 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -266,6 +266,20 @@ struct Assign { after_new: bool, } +/// `name = {`: an object literal assigned to a variable. +struct ObjectValue { + name: String, + /// The bracket depth inside its `{`. + depth: usize, + /// The document methods writing a file that it defines with a function expression, a bit each + /// ([`Analyzer::writers`]). + bits: u8, + /// It is the value of the first name a `var` statement declares, and the statement is directly + /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or + /// a loop's parentheses: only then does the variable hold `bits` after it. + whole: bool, +} + /// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it /// is a Folder object whatever the path names: [`Operand::file_step`]). enum Held { @@ -572,9 +586,12 @@ struct Analyzer<'s, 'a, 'l> { /// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit /// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing. writers: HashMap, - /// The object literals being assigned to a variable, the innermost last, each with the bracket - /// depth inside its `{`, up to [`crate::Limits::nesting`] of them. - objects: Vec<(String, usize)>, + /// The object literals being assigned to a variable, the innermost last, up to + /// [`crate::Limits::nesting`] of them. + objects: Vec, + /// An object literal whose `}` the last token was, with the methods it defines: the variable + /// holds them when the next token ends the `var` statement's value. + closed: Option<(String, u8)>, /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, @@ -651,6 +668,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { maybe_files_full: false, writers: HashMap::new(), objects: vec![], + closed: None, index_receiver: 0, own_names: HashSet::new(), scopes: vec![], @@ -1026,8 +1044,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { self.own_names.remove(&name); } - if saved.writer != 0 { - self.writers.insert(name.clone(), saved.writer); + // An outer variable the body assigned keeps only the methods it still has: the body may have + // given it another value. + let writer = if saved.local { saved.writer } else { saved.writer & self.writers.get(&name).copied().unwrap_or(0) }; + if writer != 0 { + self.writers.insert(name.clone(), writer); } else { self.writers.remove(&name); } @@ -1301,8 +1322,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if !a.after_new && t.is("{") { // An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]). self.unbind(&a.name); + let [_, _, declaration, before] = self.h; + let depth = self.depth(); + 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")); + let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { - self.objects.push((a.name, self.depth())); + self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole }); } } else { self.unbind(&a.name); @@ -1344,32 +1372,40 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `t` in an object literal assigned to a variable: a function expression directly inside its /// braces as the value of a key that names a document method writing a file - /// (`{saveAs: function …}`, `{'exportFile': function …}`) makes the variable one of - /// [`Analyzer::writers`], and any other value of that key (`{saveAs: d.saveAs}`) takes the method - /// out again. A closing brace ends the literals it closes. + /// (`{saveAs: function …}`, `{'exportFile': function …}`) counts the method for the literal, and + /// any other value of that key (`{saveAs: d.saveAs}`) takes it out again. A closing brace ends + /// the literals it closes. The variable of a [`ObjectValue::whole`] literal joins + /// [`Analyzer::writers`] only when the token after its `}` ends the value (`;`, `,` or a line + /// break), so a call inside the literal, and a value that goes on (`{…} && d`), see the variable + /// as it was. fn object_key(&mut self, t: &Sig<'s>) { + if let Some((name, bits)) = self.closed.take() + && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) + { + self.writers.insert(name, bits); + } let depth = self.depth(); - while self.objects.pop_if(|(_, d)| *d > depth).is_some() {} + while let Some(o) = self.objects.pop_if(|o| o.depth > depth) { + if o.whole && o.bits != 0 && o.depth == depth.saturating_add(1) { + self.closed = Some((o.name, o.bits)); + } + } let [h0, h1, h2, _] = self.h; if !is(h0, ":") || !(is(h2, "{") || is(h2, ",")) { return; } - let Some(name) = self.objects.last().filter(|(_, d)| *d == depth).map(|(n, _)| n.clone()) else { return }; let key = match h1 { Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text), Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)), _ => return, }; let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; - if !t.word("function") { - let left = self.writers.get(&name).map_or(0, |bits| bits & !(1 << i)); - if left == 0 { - self.writers.remove(&name); - } else { - self.writers.insert(name, left); - } - } else if self.writers.contains_key(&name) || self.acc.room(self.writers.len()) { - *self.writers.entry(name).or_insert(0) |= 1 << i; + let Some(o) = self.objects.last_mut().filter(|o| o.depth == depth) else { return }; + if t.word("function") { + o.bits |= 1 << i; + } else { + o.bits &= !(1 << i); } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 8d6bac9fa0..8140371f93 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -591,8 +591,8 @@ fn the_scripts_own_save_as_writes_no_file() { fn a_changed_or_shared_own_save_as_writes_a_file() { let r = report(concat!( "var f = new File(p);\n", - "var a = {saveAs: function () {}}, b = {saveAs: function () {}}, c = {saveAs: function () {}};\n", - "var d = {saveAs: function () {}}, e = {saveAs: function () {}}, g = {saveAs: function () {}};\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", "a.saveAs = app.activeDocument.saveAs;\n", "b['saveAs'] = w;\n", @@ -606,13 +606,42 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "d.saveAs(f);\n", "e.saveAs(f);\n", "g['saveAs'](f);\n", - "var m = {saveAs: d.saveAs}, n = {saveAs: function () {}, saveAs: d.saveAs};\n", + "var m = {saveAs: d.saveAs}; var n = {saveAs: function () {}, saveAs: d.saveAs};\n", "m.saveAs(f);\n", "n.saveAs(f);\n", )); assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19][..])); } +/// 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 +/// or to a later name of the statement, a call inside the literal, and a variable a function gave +/// another value keep reporting the write. +#[test] +fn only_a_whole_var_value_makes_save_as_the_scripts_own() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}};\n", + "function choose() { d = null; d = app.activeDocument; }\n", + "d.saveAs(f);\n", + "var e = app.activeDocument;\n", + "if (flag) var e = {saveAs: function () {}};\n", + "e.saveAs(f);\n", + "if (flag) { var e2 = {saveAs: function () {}}; }\n", + "e2.saveAs(f);\n", + "var g = {saveAs: function () {}} && app.activeDocument;\n", + "g.saveAs(f);\n", + "var h = app.activeDocument;\n", + "h = {saveAs: function () {}, value: h.saveAs(f)};\n", + "var k = {saveAs: function () {}, value: k.saveAs(f)};\n", + "k.saveAs(f);\n", + "var x = 1, y = {saveAs: function () {}};\n", + "y.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); +} + /// 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] From ff4fc193f8e438256a720b52932613f179e4ab6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:08:00 -0800 Subject: [PATCH 08/20] Scripts: a later saveAs value in brackets ends the exemption A literal such as `{saveAs: function () {}, saveAs: (doc.saveAs)}` kept the first key's exemption, because the value's opening bracket had already raised the depth when the key was read. The key is now read at the depth outside that bracket, so the later value replaces the function and `n['saveAs'](f)` is reported as a file write. --- crates/scriptcheck/src/analyze.rs | 4 +++- crates/scriptcheck/src/tests.rs | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 9056752744..bb10272e62 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1401,7 +1401,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { _ => return, }; let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; - let Some(o) = self.objects.last_mut().filter(|o| o.depth == depth) else { return }; + // A value that starts with a bracket has opened it already: the key is at the depth outside it. + let at = if t.is("(") || t.is("[") || t.is("{") { depth.saturating_sub(1) } else { depth }; + let Some(o) = self.objects.last_mut().filter(|o| o.depth == at) else { return }; if t.word("function") { o.bits |= 1 << i; } else { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 8140371f93..bc03f6ab07 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -609,8 +609,11 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "var m = {saveAs: d.saveAs}; var n = {saveAs: function () {}, saveAs: d.saveAs};\n", "m.saveAs(f);\n", "n.saveAs(f);\n", + "var q = {saveAs: function () {}, saveAs: (d.saveAs)}; var s = {saveAs: function () {}, saveAs: [w][0]};\n", + "q['saveAs'](f);\n", + "s.saveAs(f);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); } /// Only a `var` statement directly in a function body or the global code that gives its first name From 9034e0d6d8b20307614dcab0b28e4d6a691a17d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:20:43 -0800 Subject: [PATCH 09/20] Scripts: a saveAs value that goes on after the function body writes a file The script checker treats a saveAs or exportFile key of the script's own object literal as the script's own method only when the key's whole value is one function expression: `function`, an optional name, the parameters and the body, followed by `,` or the literal's closing brace. A value that goes on after the body, such as `function () {} && doc.saveAs`, a call of the function or a conditional, leaves the method reported as a file write. The variable takes the literal's methods before the token after the literal closes a function body, so a literal given to the body's own variable on the body's last line no longer hides a save on the outer variable of the same name. --- crates/scriptcheck/src/analyze.rs | 92 ++++++++++++++++++++++++------- crates/scriptcheck/src/tests.rs | 27 +++++++++ 2 files changed, 98 insertions(+), 21 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index bb10272e62..0e355d94f2 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -271,13 +271,58 @@ struct ObjectValue { name: String, /// The bracket depth inside its `{`. depth: usize, - /// The document methods writing a file that it defines with a function expression, a bit each - /// ([`Analyzer::writers`]). + /// The document methods writing a file that it defines with a single function expression as the + /// key's whole value, a bit each ([`Analyzer::writers`]). bits: u8, /// It is the value of the first name a `var` statement declares, and the statement is directly /// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or /// a loop's parentheses: only then does the variable hold `bits` after it. whole: bool, + /// The bit of the method whose value is being read, and how far that value has been read. + value: Option<(u8, Value)>, +} + +/// How far the value of an object literal's key that names a document method writing a file has been +/// read, by the tokens directly inside the literal's braces. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Value { + /// `function`. + Function, + /// The function expression's name. + Name, + /// The `(` of its parameters. + Params, + /// The `{` of its body: the value is the function expression when `,` or the literal's `}` comes + /// next. + Body, + /// Anything else, or anything after the body. + Other, +} + +impl ObjectValue { + /// `t`, a token directly inside the literal's braces: a `,` or the closing `}` ends the value + /// being read, and gives the literal the method only when the value is a single function + /// expression (`function () {} && d.saveAs`, `function () {}(f)` and `function () {}.call` give + /// it nothing). + fn step(&mut self, t: &Sig) { + let Some((bit, value)) = self.value else { return }; + if t.is(",") || t.is("}") { + if value == Value::Body { + self.bits |= bit; + } else { + self.bits &= !bit; + } + self.value = None; + return; + } + let next = match value { + Value::Function if t.kind == T::Ident => Value::Name, + Value::Function | Value::Name if t.is("(") => Value::Params, + Value::Params if t.is("{") => Value::Body, + _ => Value::Other, + }; + self.value = Some((bit, next)); + } } /// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it @@ -753,6 +798,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or // closes a function body. self.settle_groups(&t); + self.settle_literal(&t); // A line break ends a `var` statement when it is outside the statement's brackets, and the // tokens on either side of it don't go on with the expression. if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(self.h[0]) && !goes_on_with(&t) { @@ -775,7 +821,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.group_step(&t, started, before); self.paren_step(&t, before); self.assignment(&t, started); - self.object_key(&t); + self.object_key(&t, before); self.features(&t); self.newer(&t); self.module_check(&t); @@ -1330,7 +1376,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { || (declaration.is_some_and(|d| d.nl) && !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 }); + self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); } } else { self.unbind(&a.name); @@ -1370,21 +1416,30 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// `t` in an object literal assigned to a variable: a function expression directly inside its - /// braces as the value of a key that names a document method writing a file - /// (`{saveAs: function …}`, `{'exportFile': function …}`) counts the method for the literal, and - /// any other value of that key (`{saveAs: d.saveAs}`) takes it out again. A closing brace ends - /// the literals it closes. The variable of a [`ObjectValue::whole`] literal joins - /// [`Analyzer::writers`] only when the token after its `}` ends the value (`;`, `,` or a line - /// break), so a call inside the literal, and a value that goes on (`{…} && d`), see the variable - /// as it was. - fn object_key(&mut self, t: &Sig<'s>) { + /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins + /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` + /// closes a function body, so a literal given to the body's own variable stays inside the body. + fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); } + } + + /// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single + /// function expression directly inside its braces as the whole value of a key that names a + /// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`) + /// counts the method for the literal, and any other value of that key (`{saveAs: d.saveAs}`, + /// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing + /// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the + /// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on + /// (`{…} && d`), see the variable as it was. + fn object_key(&mut self, t: &Sig<'s>, before: usize) { + if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) { + o.step(t); + } let depth = self.depth(); while let Some(o) = self.objects.pop_if(|o| o.depth > depth) { if o.whole && o.bits != 0 && o.depth == depth.saturating_add(1) { @@ -1401,14 +1456,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { _ => return, }; let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return }; - // A value that starts with a bracket has opened it already: the key is at the depth outside it. - let at = if t.is("(") || t.is("[") || t.is("{") { depth.saturating_sub(1) } else { depth }; - let Some(o) = self.objects.last_mut().filter(|o| o.depth == at) else { return }; - if t.word("function") { - o.bits |= 1 << i; - } else { - o.bits &= !(1 << i); - } + // A value that starts with a bracket has opened it already: the key is at the depth before it. + let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) else { return }; + o.value = Some((1 << i, if t.word("function") { Value::Function } else { Value::Other })); } /// The variable that `t` changes to a number or a string, nothing the check follows, and whether diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index bc03f6ab07..76d78f822b 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -645,6 +645,33 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +/// A `saveAs` key's value is a method of the script's own only when the whole value is one function +/// expression: a value that goes on after the function's body, and a literal inside another, leave +/// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body +/// leaves the outer variable as it was. +#[test] +fn a_value_that_goes_on_after_the_function_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {} && app.activeDocument.saveAs};\n", + "var b = {saveAs: function () {}(f), n: 1};\n", + "var c = {saveAs: function () {} ? x : y};\n", + "var e = {saveAs: function () {}.call};\n", + "var k = {exportFile: function w(x) { return x; }, saveAs: function () {}};\n", + "var m = {o: {saveAs: function () {}}};\n", + "var q = app.activeDocument; function r() { var q = {saveAs: function () {}}\n", + "}\n", + "a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + "e.saveAs(f);\n", + "k.saveAs(f); k.exportFile(f);\n", + "m.saveAs(f);\n", + "q.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 15, 16][..])); +} + /// 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] From e8a0aa6ba444a89c622056f5f8d95f911556f3e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 19:01:40 -0800 Subject: [PATCH 10/20] Scripts: documents give their file, folder and saved state, close, and save several artboards - Document.fullName is a File for the document's file, and Document.path a Folder for its folder. A document without a file has a fullName of a File for its name in Folder.current and a path of "". Both throw `Script file access denied` with the document's name when the automation read roots do not allow the file. - Document.saved reads whether the document has unsaved changes. Setting it runs the new command document.setSaved, which records the document as saved or as changed without saving it and adds no undo step. - Document.close(saveOptions) closes a document without unsaved changes with any SaveOptions value. With unsaved changes, SaveOptions.DONOTSAVECHANGES closes it without them, and SaveOptions.SAVECHANGES saves them first with file.saveAs, in the format the file's extension names and after the write-access check saveAs makes, and throws for a document without a file (a converted or recovered one included). SaveOptions.PROMPTTOSAVECHANGES, the default, throws, since a script cannot show the prompt. - The script checker reports SaveOptions.SAVECHANGES under filesWritten wherever the script reads it. - A pDFPreset in square brackets, such as [Smallest File Size], names the built-in preset of the name inside them. - artboardRange takes a whole number from 1 as well as a string; any other number throws. - With saveMultipleArtboards true, a .ai or EPS save also writes each artboard of the range to a file of its own. Without it the range is not used, but text that is not a range of artboard numbers throws. Document page: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ --- crates/engine/src/cmd/edit.rs | 29 ++ crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/save_open.rs | 240 +++++++++++++++- crates/engine/src/tests/script_save_open.rs | 257 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 18 +- crates/js/src/file_classes.rs | 31 +++ crates/js/src/host.rs | 10 +- crates/js/src/lib.rs | 2 +- crates/scriptcheck/src/analyze/features.rs | 17 ++ crates/scriptcheck/src/catalog.rs | 6 + crates/scriptcheck/src/tests.rs | 19 ++ docs/gaps.md | 3 +- docs/mcp.md | 40 ++- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 15 files changed, 649 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccee814d90..81c201d95f 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -39,6 +39,15 @@ pub fn specs() -> Vec { has_doc, doc_move ), + cmd!( + "document.setSaved", + "Set Saved State", + [], + None, + "{index?: the document (default: the current one), saved: true or false} records the document as saved (true: Close asks nothing until the next edit) or as having unsaved changes (false), without saving it or adding an undo step; a document already in that state is left as it is", + has_doc, + doc_set_saved + ), cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect), cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node), cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find), @@ -257,6 +266,26 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result { if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) } } +fn doc_set_saved(s: &mut Session, p: &Value) -> Result { + const C: &str = "document.setSaved"; + let i = opt_u64(p, C, "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?; + let saved = match p.get("saved") { + None | Some(Value::Null) => return Err(bad(C, "missing `saved`: true or false")), + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad(C, "`saved` must be true or false")), + }; + let uid = s.documents().get(i).map(|d| d.uid).ok_or_else(|| bad(C, "no such document"))?; + let st = s.document_mut(uid).ok_or_else(|| bad(C, "no such document"))?; + if st.is_dirty() == saved { + if saved { + st.mark_saved(); + } else { + st.mark_unsaved(); + } + } + ok() +} + fn doc_move(s: &mut Session, p: &Value) -> Result { let n = s.documents().len(); let from = match p.get("from") { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8e6c46e87d..e4a3e3a638 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1865,7 +1865,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "close"] + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer"] .into_iter() .map(|m| later(l, "Document", m)), ); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index f54c2f3f0b..b2c9a56378 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -1,5 +1,6 @@ //! Saving, exporting and opening documents in the script object model: `Document.saveAs`, -//! `Document.exportFile`, `app.open` and `app.userInteractionLevel`, with the option classes the +//! `Document.exportFile`, `Document.fullName`, `Document.path`, `Document.saved`, +//! `Document.close`, `app.open` and `app.userInteractionLevel`, with the option classes the //! help pages , //! , //! , @@ -29,7 +30,25 @@ //! the default its help page gives and throws an error that says it is not available yet at any //! other value; a property the help pages do not list throws an error that names it, unless it is //! `undefined`. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default -//! keeps the preset's value. +//! keeps the preset's value. A `pDFPreset` in square brackets names the built-in preset of the +//! name inside them; the default preset's name and `[PDF/X-4:2008]` name VectorCraft Default and +//! PDF/X-4:2010. +//! - `artboardRange` is a string, or a number read as `String(number)`. With +//! `saveMultipleArtboards` true, a `.ai` save also writes each artboard of the range (all when it +//! is empty) to a file of its own, `-.ai`. An EPS save of a range of two or +//! more artboards writes the file at the path and `_.eps` for each of them, and an EPS +//! save of one artboard writes only the file at the path, holding that artboard. Without +//! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of +//! artboard numbers throws. +//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no +//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. +//! `fullName` and `path` of a document whose file the automation read roots do not allow throw +//! `Script file access denied`. Setting `Document.saved` runs `document.setSaved`. +//! - `Document.close` with unsaved changes closes without them with +//! `SaveOptions.DONOTSAVECHANGES`, and saves them to the document's file first with +//! `SaveOptions.SAVECHANGES`, which throws for a document that has no file (a converted or +//! recovered one included). `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws, since a +//! script cannot show the prompt. //! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: //! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property //! but `typename` and `parent` throws the same error, unless it is `undefined`. @@ -44,8 +63,8 @@ use serde_json::{Map, Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; use super::{ - Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, given, method, named, num, on_doc, property, - text, this_doc, whole, + Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, get, given, method, named, num, on_doc, + property, text, this_doc, whole, }; /// The most a scale factor of an export takes, in percent. @@ -86,6 +105,7 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]), ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), + ("SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"]), ]; const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; @@ -165,9 +185,17 @@ fn compatibility(class: &str, d: &Data) -> std::result::Result<(), HostError> { } } -/// An artboard range: a string, given to the command as `range` unless it is empty. +/// An artboard range: a string, or a whole number from 1 read as `String(number)` reads it, given to +/// the command as `range` unless it is empty. Any other number throws. fn range(d: &Data, what: &str, p: &mut Map) -> std::result::Result<(), HostError> { - let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + let s = match d { + Data::String(s) => s.clone(), + Data::Number(n) => { + whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?; + vectorcraft_js::number_to_string(*n) + } + _ => return Err(HostError::Type(format!("{what} must be a string or a number"))), + }; if s.len() > MAX_TEXT_BYTES { return Err(HostError::Range(format!("{what} is too long"))); } @@ -189,17 +217,76 @@ fn ai_map(name: &str, d: &Data, p: &mut Map) -> std::result::Resu compatibility("IllustratorSaveOptions", d)?; None } + "artboardRange" | "saveMultipleArtboards" => return artboards_map("IllustratorSaveOptions", name, d, p), _ => return Ok(false), }; Ok(true) } +/// `artboardRange` and `saveMultipleArtboards` of a `.ai` or EPS save, as `range` and +/// [`MULTIPLE`] until [`artboard_files`] reads them together. +fn artboards_map(class: &str, name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("{class}.{name}"); + if name == "artboardRange" { + range(d, &what, p)?; + } else { + p.insert(MULTIPLE.into(), json!(boolean(d, &what)?)); + } + Ok(true) +} + +/// The key [`artboards_map`] keeps `saveMultipleArtboards` under. +const MULTIPLE: &str = "_multiple"; + +/// The params of a `.ai` (`format` `ai`) or EPS save for `saveMultipleArtboards` and +/// `artboardRange`: with `saveMultipleArtboards` true, the range (all when it is empty) goes to +/// `separateArtboards` of a `.ai` save or `useArtboards` of an EPS save, which write the artboards' +/// files; otherwise the range is not used, as the help pages say, but one that is not written as a +/// range ([`written_as_range`]) still throws. +fn artboard_files(format: &str, q: &mut Map) -> std::result::Result<(), HostError> { + let multiple = q.remove(MULTIPLE).and_then(|v| v.as_bool()).unwrap_or(false); + if !multiple { + if let Some(Value::String(r)) = q.remove("range") + && !r.trim().eq_ignore_ascii_case("all") + && !written_as_range(&r) + { + return Err(HostError::Range(format!("artboardRange `{r}` is not a range of artboard numbers"))); + } + } else if format == "ai" { + q.insert("separateArtboards".into(), json!(true)); + } else { + q.insert("useArtboards".into(), json!(true)); + } + Ok(()) +} + +/// Whether `r` is written as an artboard range, whatever artboards a document has: parts separated +/// by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out +/// and the first no greater than the second. +fn written_as_range(r: &str) -> bool { + // A number of digits alone, from 1; past `u64` it counts as the largest. + let num = |t: &str| -> Option> { + let t = t.trim(); + if t.is_empty() { + return Some(None); + } + let n = t.bytes().all(|b| b.is_ascii_digit()).then(|| t.parse::().unwrap_or(u64::MAX))?; + (n >= 1).then_some(Some(n)) + }; + r.split(',').map(str::trim).filter(|p| !p.is_empty()).all(|part| match part.replace('\u{2013}', "-").split_once('-') { + Some((a, b)) => match (num(a), num(b)) { + (Some(Some(a)), Some(Some(b))) => a <= b, + (Some(a), Some(b)) => a.is_some() || b.is_some(), + _ => false, + }, + None => matches!(num(part), Some(Some(_))), + }) +} + const AI_KEPT: &[(&str, Default)] = &[ - ("artboardRange", Default::Text("")), ("embedLinkedFiles", Default::Bool(false)), ("flattenOutput", Default::Member("OutputFlattening", "PRESERVEAPPEARANCE")), ("fontSubsetThreshold", Default::Num(100.0)), - ("saveMultipleArtboards", Default::Bool(false)), ]; fn ai_starts() -> Vec<(&'static str, Data)> { @@ -236,18 +323,17 @@ fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Res p.insert("overprints".into(), json!(if keep { "preserve" } else { "discard" })); } "compatibility" => compatibility("EPSSaveOptions", d)?, + "artboardRange" | "saveMultipleArtboards" => return artboards_map("EPSSaveOptions", name, d, p), _ => return Ok(false), } Ok(true) } const EPS_KEPT: &[(&str, Default)] = &[ - ("artboardRange", Default::Text("")), ("compatibleGradientPrinting", Default::Bool(false)), ("embedAllFonts", Default::Bool(false)), ("embedLinkedFiles", Default::Unset), ("flattenOuput", Default::Unset), - ("saveMultipleArtboards", Default::Bool(false)), ]; fn eps_starts() -> Vec<(&'static str, Data)> { @@ -578,6 +664,29 @@ fn plain(real: std::path::PathBuf) -> String { crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() } +/// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the +/// preset each one names here. +const PRESET_ALIASES: &[(&str, &str)] = &[ + ("Illustrator Default", vectorcraft_pdf::DEFAULT_PRESET), // brand-ok: the preset name scripts use + ("PDF/X-4:2008", "PDF/X-4:2010"), +]; + +/// A `pDFPreset` in square brackets (`[Smallest File Size]`) names the built-in preset of the name +/// inside the brackets, or the one [`PRESET_ALIASES`] gives for it. A preset the name already +/// names, a saved preset called `[Name]` included, is left as it is, and any other name is left for +/// the save to refuse. +fn builtin_preset_name(h: &Host, q: &mut Map) { + let Some(name) = q.get("preset").and_then(Value::as_str) else { return }; + let s = h.session.borrow(); + if crate::cmd::fileio::pdf::find_preset(name, &s.prefs.pdf_presets).is_some() { + return; + } + let Some(inside) = name.trim().strip_prefix('[').and_then(|n| n.strip_suffix(']')) else { return }; + let inside = PRESET_ALIASES.iter().find(|(alias, _)| alias.eq_ignore_ascii_case(inside.trim())).map_or(inside, |(_, to)| to); + let Some(builtin) = vectorcraft_pdf::builtin_preset(inside) else { return }; + q.insert("preset".into(), json!(builtin.name)); +} + /// `document.saveAs(file, options?)`: `file.saveAs` on the document, in the format the options' /// class names (`ai`, `eps`, `pdf`), or without options in the format of the path's extension. fn doc_save_as(h: &Host, a: &[Data]) -> Answer { @@ -594,7 +703,12 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else { return Err(HostError::Type("saveAs options must be IllustratorSaveOptions, EPSSaveOptions or PDFSaveOptions".into())); }; - let q = options_params(class, o)?; + let mut q = options_params(class, o)?; + if *format == "pdf" { + builtin_preset_name(h, &mut q); + } else { + artboard_files(format, &mut q)?; + } p.insert("format".into(), json!(format)); if *format == "ai" { p.extend(q); @@ -717,6 +831,101 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { Ok(doc_ref(h, st.uid)) } +/// The document's file, `None` for a document that has none, or `Script file access denied` with +/// the document's name when the automation read roots do not allow the file to be named +/// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them. +fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { + match st.path.as_deref() { + Some(p) if crate::file_access::check_read(p).is_err() => { + Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title()))) + } + p => Ok(p), + } +} + +/// `document.fullName`: a `File` for the document's file, or, for a document that has none, a +/// `File` for its name in `Folder.current`. +fn doc_full_name(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + super::with_doc(h, doc, |_, st| { + Ok(match shown_file(st)? { + Some(p) => vectorcraft_js::file_ref(p), + None => vectorcraft_js::file_ref(&st.title()), + }) + }) +} + +/// `document.path`: a `Folder` for the folder of the document's file, or an empty string for a +/// document that has none. +fn doc_path(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let folder = super::with_doc(h, doc, |_, st| { + Ok(shown_file(st)?.and_then(|p| { + let parent = std::path::Path::new(p).parent()?.to_string_lossy().into_owned(); + (!parent.is_empty()).then_some(parent) + })) + })?; + Ok(folder.map_or_else(|| text(""), |f| vectorcraft_js::folder_ref(&f))) +} + +/// `document.saved`: whether the document has no changes since it was opened or last saved. +fn doc_saved(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(Data::Bool(super::with_doc(h, doc, |_, st| !st.is_dirty()))) +} + +/// `document.saved = value`: `document.setSaved`, which records the document as saved or as having +/// unsaved changes without saving it. +fn doc_set_saved(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let saved = boolean(arg(a, 1), "Document.saved")?; + command(h, "document.setSaved", &json!({"index": doc.index, "saved": saved}))?; + Ok(Data::Undefined) +} + +/// The error `close` gives for a document with unsaved changes with +/// `SaveOptions.PROMPTTOSAVECHANGES`. +const UNSAVED_CHANGES: &str = + "the document has unsaved changes: save them first, or close with SaveOptions.SAVECHANGES or SaveOptions.DONOTSAVECHANGES"; + +/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes that has +/// no file to save to. +const NO_FILE_TO_SAVE: &str = + "the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + +/// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved +/// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES` +/// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with +/// `file.saveAs` in the format its extension names, after the write-access check `saveAs` makes of +/// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] +/// for a document that has no file, a converted or recovered one included; and +/// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script +/// cannot show the prompt. +fn doc_close(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let how = match given(arg(a, 1)).filter(|d| !matches!(d, Data::Null)) { + Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, + None => "PROMPTTOSAVECHANGES", + }; + let (dirty, file) = super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered))); + if dirty { + match how { + "DONOTSAVECHANGES" => {} + "SAVECHANGES" => { + let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + // A refusal names the document, as `fullName` does when the read roots hide its file. + let name = super::with_doc(h, doc, |_, st| st.title()); + let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; + let p = json!({"path": plain(real)}); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; + } + _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), + } + } + command(h, "file.close", &json!({"index": doc.index}))?; + Ok(Data::Undefined) +} + fn app_interaction(h: &Host, _: &[Data]) -> Answer { Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY })) } @@ -734,7 +943,14 @@ pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> { /// The members these add to `Document`. pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { - named(vec![("saveAs", method(l, doc_save_as)), ("exportFile", method(l, doc_export_file))]) + named(vec![ + ("saveAs", method(l, doc_save_as)), + ("exportFile", method(l, doc_export_file)), + ("fullName", get(l, doc_full_name)), + ("path", get(l, doc_path)), + ("saved", property(l, doc_saved, doc_set_saved)), + ("close", method(l, doc_close)), + ]) } /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 126c7c3947..4389838807 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -477,6 +477,7 @@ fn bad_arguments_are_refused_with_an_error() { let cases: Vec<(String, &str)> = vec![ ("app.activeDocument.saveAs('x.svg');".into(), "saveAs needs a File"), (format!("app.activeDocument.saveAs({{'\\u0000fileRef': {}}});", quoted(&dir.join("x.svg"))), "is not plain data"), + (format!("app.activeDocument.saveAs({{'\\u0000folderRef': {}}});", quoted(&dir)), "is not plain data"), (format!("app.activeDocument.saveAs({f}, {{typename: 'Nope'}});"), "saveAs options must be"), (format!("app.activeDocument.saveAs({f}, new ExportOptionsSVG());"), "saveAs options must be"), (format!("var o = new IllustratorSaveOptions(); o.compressed = 'yes'; app.activeDocument.saveAs({f}, o);"), "must be true or false"), @@ -624,3 +625,259 @@ fn open_takes_the_page_and_crop_box_of_its_options() { assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages"); let _ = std::fs::remove_dir_all(base); } + +/// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its +/// changes, and `close` with `SaveOptions.DONOTSAVECHANGES` closes it. +#[test] +fn full_name_path_saved_and_close_follow_the_documents_file() { + let base = folder("fullname"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.log([d.fullName instanceof File, d.fullName.name === d.name, d.fullName.fsName === new File(d.name).fsName, d.path === '', d.saved]);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); vc.log(d.saved);\n\ + d.saveAs(new File(dir + '/a.svg'));\n\ + vc.log([d.fullName instanceof File, d.fullName.fsName, d.fullName.name, d.path instanceof Folder, d.path.fsName, d.saved]);\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); vc.log(d.saved);\n\ + var e = ''; try {{ d.close(); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);\n\ + var before = new File(dir + '/a.svg').length; d.close(SaveOptions.SAVECHANGES);\n\ + vc.log([app.documents.length, new File(dir + '/a.svg').length > before]);\n\ + var n = app.documents.add(DocumentColorSpace.RGB, 200, 100); vc.run('shape.rectangle', {{x: 10, y: 10, width: 5, height: 5}});\n\ + e = ''; try {{ n.close(SaveOptions.SAVECHANGES); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);\n\ + n.close(SaveOptions.DONOTSAVECHANGES); vc.log(app.documents.length);" + ), + ); + assert_eq!(out[0], json!([true, true, true, true, true]), "an untouched document that has no file"); + assert_eq!(out[1], json!(false), "an edit leaves changes to save"); + let file = dir.join("a.svg"); + assert_eq!( + out[2], + json!([true, file.to_string_lossy(), "a.svg", true, dir.to_string_lossy(), true]), + "after saveAs the document's file and folder" + ); + assert_eq!(out[3], json!(false)); + assert!(out[4][0].as_str().unwrap().contains("unsaved changes"), "{}", out[4]); + assert_eq!(out[4][1], json!(1), "without SaveOptions the document stays open"); + assert_eq!(out[5], json!([0, true]), "SAVECHANGES saves the edit to the document's file and closes it"); + assert!(out[6][0].as_str().unwrap().contains("no file to save"), "{}", out[6]); + assert_eq!(out[6][1], json!(1), "SAVECHANGES without a file leaves the document open"); + assert_eq!(out[7], json!(0)); + assert!(s.documents().is_empty()); + let e = failure(&mut s, &base, "app.documents.add(); app.activeDocument.close('DONOTSAVECHANGES');"); + assert!(e.contains("SaveOptions"), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument. +#[test] +fn a_document_without_unsaved_changes_closes_with_any_save_options() { + let base = folder("closeclean"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File(dir + '/a.svg'));\n\ + var e = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.log([d.saved, e.saved, app.documents.length]);\n\ + d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);\n\ + e.close(); vc.log(app.documents.length);" + ), + ); + assert_eq!(out, json!([[true, true, 2], 1, 0])); + let _ = std::fs::remove_dir_all(base); +} + +/// Setting `Document.saved` records the document's saved state without saving it: `true` lets +/// `close()` close a document with edits, and `false` makes an untouched one ask. +#[test] +fn setting_saved_records_the_saved_state() { + let base = folder("setsaved"); + let mut s = session(&base); + data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + "var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 20});\n\ + vc.log(d.saved); d.saved = true; vc.log(d.saved); d.close(); vc.log(app.documents.length);\n\ + var e = app.documents.add(DocumentColorSpace.RGB, 200, 100); vc.log(e.saved); e.saved = false; vc.log(e.saved);\n\ + var m = ''; try { e.close(); } catch (x) { m = String(x); } vc.log([m, app.documents.length]);\n\ + m = ''; try { e.saved = 'yes'; } catch (x) { m = String(x); } vc.log(m);", + ); + assert_eq!(out[0], json!(false), "an edit leaves changes to save"); + assert_eq!(out[1], json!(true)); + assert_eq!(out[2], json!(0), "close() closes a document set as saved"); + assert_eq!(out[3], json!(true)); + assert_eq!(out[4], json!(false)); + assert!(out[5][0].as_str().unwrap().contains("unsaved changes"), "{}", out[5]); + assert_eq!(out[5][1], json!(1), "a document set as unsaved stays open"); + assert!(out[6].as_str().unwrap().contains("true or false"), "{}", out[6]); + assert!(s.active().unwrap().is_dirty(), "the state stays after the run"); + let _ = std::fs::remove_dir_all(base); +} + +/// With automation read roots that leave out the document's file, `fullName` and `path` throw +/// instead of naming another file. +#[test] +fn full_name_and_path_leave_out_a_file_outside_the_read_roots() { + let base = folder("fullnameroots"); + let mut s = session(&base); + data_folder(&mut s, &base); + let file = base.join("outside/hidden.svg"); + s.execute("file.new", &json!({})).unwrap(); + s.execute("document.save", &json!({"path": file.to_string_lossy()})).unwrap(); + let query = "var d = app.activeDocument; vc.log([d.fullName.name, d.fullName.fsName, d.path === '' ? '' : d.path.fsName]);"; + let out = logged(&mut s, &base, query); + let outside = base.join("outside"); + assert_eq!(out[0], json!(["hidden.svg", file.to_string_lossy(), outside.to_string_lossy()]), "no read roots: the whole path"); + let roots = crate::file_access::AutomationRoots::new(&[&base.join("main"), &base.join("settings")], &[&base.join("settings")]).unwrap().unwrap(); + let hidden = "var d = app.activeDocument, r = [];\n\ + try { r.push(d.fullName.fsName); } catch (e) { r.push(e.message); }\n\ + try { r.push(String(d.path)); } catch (e) { r.push(e.message); }\n\ + vc.log(r);"; + let out = crate::file_access::confine(Some(&roots), || logged(&mut s, &base, hidden)); + for m in out[0].as_array().unwrap() { + let m = m.as_str().unwrap(); + assert!(m.starts_with(DENIED) && m.ends_with("hidden.svg"), "{m}"); + assert!(!m.contains("outside"), "the folder outside the read roots is not named: {m}"); + } + let before = std::fs::read(&file).unwrap(); + let e = failure( + &mut s, + &base, + "vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 20}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(e.contains(DENIED) && !e.contains("outside"), "SAVECHANGES does not write a file the script may not: {e}"); + assert_eq!(std::fs::read(&file).unwrap(), before, "the file is left as it was"); + assert_eq!(s.documents().len(), 1, "the document stays open"); + let _ = std::fs::remove_dir_all(base); +} + +/// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name +/// that is not a preset either way is refused. +#[test] +fn a_bracketed_pdf_preset_names_the_built_in_preset() { + let base = folder("brackets"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new PDFSaveOptions(); o.pDFPreset = '[Smallest File Size]'; d.saveAs(new File(dir + '/small.pdf'), o);\n\ + o.pDFPreset = '[Illustrator Default]'; d.saveAs(new File(dir + '/default.pdf'), o);\n\ + o.pDFPreset = '[PDF/X-4:2008]'; d.saveAs(new File(dir + '/x4.pdf'), o);" + ), + ); + let small = std::fs::read(dir.join("small.pdf")).unwrap(); + assert!(String::from_utf8_lossy(&small[..200.min(small.len())]).contains("/Linearized 1"), "Smallest File Size writes a linearized file"); + assert!(dir.join("default.pdf").is_file()); + let x4 = String::from_utf8_lossy(&std::fs::read(dir.join("x4.pdf")).unwrap()).into_owned(); + assert!(x4.contains("PDF/X-4"), "the PDF/X-4 preset writes a PDF/X-4 file"); + for bad in ["[Nope]", "[Basic Default]", "[Ilustrator Default]"] { + let e = failure( + &mut s, + &base, + &format!("Folder.userData; var o = new PDFSaveOptions(); o.pDFPreset = '{bad}'; app.activeDocument.saveAs(new File({d} + '/n.pdf'), o);"), + ); + assert!(e.contains("unknown PDF preset"), "{bad}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// A number given as `artboardRange` is read as `String(number)` reads it. +#[test] +fn a_number_artboard_range_names_that_artboard() { + let base = folder("rangenumber"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + var o = new PDFSaveOptions(); o.artboardRange = 2; d.saveAs(new File(dir + '/two.pdf'), o);" + ), + ); + let pdf = vectorcraft_pdf::import(&std::fs::read(dir.join("two.pdf")).unwrap()).unwrap(); + assert_eq!(pdf.artboards.len(), 1, "one page"); + let r = pdf.artboards[0].rect; + assert!((r.width() - 60.0).abs() < 0.01 && (r.height() - 80.0).abs() < 0.01, "the second artboard: {r:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// With `saveMultipleArtboards`, a `.ai` or EPS save also writes a file for each artboard of +/// `artboardRange`; without it the range is not used, and only a value that is not written as a +/// range throws. +#[test] +fn save_multiple_artboards_writes_a_file_per_artboard() { + let base = folder("multiple"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let names = |sub: &str| { + let mut v: Vec = std::fs::read_dir(dir.join(sub)).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + v.sort(); + v + }; + logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var names = ['ai', 'eps', 'aione', 'epsone', 'aioff'];\n\ + for (var i = 0; i < names.length; i++) new Folder(dir + '/' + names[i]).create();\n\ + var a = new IllustratorSaveOptions(); a.saveMultipleArtboards = true; d.saveAs(new File(dir + '/ai/a.ai'), a);\n\ + var e = new EPSSaveOptions(); e.saveMultipleArtboards = true; d.saveAs(new File(dir + '/eps/a.eps'), e);\n\ + a.artboardRange = '2'; d.saveAs(new File(dir + '/aione/a.ai'), a);\n\ + e.artboardRange = 2; d.saveAs(new File(dir + '/epsone/a.eps'), e);\n\ + a.saveMultipleArtboards = false; d.saveAs(new File(dir + '/aioff/a.ai'), a);" + ), + ); + assert_eq!(names("ai"), ["a-Artboard-1.ai", "a-Artboard-2.ai", "a.ai"], "the file and one for each of the two artboards"); + assert_eq!(names("eps"), ["a.eps", "a_Artboard-1.eps", "a_Artboard-2.eps"], "the central file and one for each of the two artboards"); + assert_eq!(names("aione"), ["a-Artboard-2.ai", "a.ai"], "the file and one for artboard 2"); + assert_eq!(names("epsone"), ["a.eps"], "one artboard: its file alone"); + let eps = String::from_utf8_lossy(&std::fs::read(dir.join("epsone/a.eps")).unwrap()).into_owned(); + let bbox = eps.lines().find(|l| l.starts_with("%%BoundingBox:")).unwrap_or_default(); + assert_eq!(bbox.split_whitespace().skip(1).collect::>(), ["0", "0", "60", "80"], "the file holds artboard 2: {bbox}"); + assert_eq!(names("aioff"), ["a.ai"], "without saveMultipleArtboards the range is not used"); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var a = new IllustratorSaveOptions(); a.artboardRange = 3; \ + app.activeDocument.saveAs(new File({d} + '/aioff/c.ai'), a);" + ), + ); + assert!(dir.join("aioff/c.ai").is_file(), "a range past the document's artboards is not used and does not stop the save"); + for bad in ["'abc'", "'0-'", "'3-1'", "'-'", "-1", "2.5", "0"] { + let e = failure( + &mut s, + &base, + &format!( + "Folder.userData; var a = new IllustratorSaveOptions(); a.artboardRange = {bad}; \ + app.activeDocument.saveAs(new File({d} + '/aioff/b.ai'), a);" + ), + ); + assert!(e.contains("range"), "{bad}: {e}"); + } + assert!(!dir.join("aioff/b.ai").exists(), "a bad range writes nothing"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index a0794be35c..d20c3ab3e6 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,12 +39,15 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. The document model (`app`, its classes and the enumerations) acts on the open -/// documents; `Document.close` throws "not available yet". `app.open` reads the file it is given. +/// documents; `Document.close` closes a document, and saves it to its own file only when it is given +/// `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and +/// `Document.path` only name its file and folder. `app.open` reads the file it is given. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), @@ -98,9 +101,9 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + "activeLayer activeLayer= artboards artboards= close constructor convertCoordinate documentColorSpace fullName \ + groupItems groupItems= height layers layers= name pageItems parent path pathItems pathItems= rulerOrigin rulerOrigin= \ + rulerUnits saved saved= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), ("Layer.", "prototype"), @@ -132,7 +135,11 @@ const INSIDE: &[(&str, &str)] = &[ ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), // The enumerations of saving, exporting and opening. - ("", "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint UserInteractionLevel"), + ( + "", + "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint SaveOptions \ + UserInteractionLevel", + ), ( "Compatibility.", "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ @@ -144,6 +151,7 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"), ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), + ("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), ]; diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f4f2064812..8083e6f46c 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -54,6 +54,11 @@ impl Classes { /// plain object a script made that carries the key is refused. pub const FILE_REF_KEY: &str = "\u{0}fileRef"; +/// The one key of the [`crate::Data`] object a host gives for a `Folder`, with the folder's path in +/// the host's platform form as its value. A plain object a script made that carries the key is +/// refused. +pub const FOLDER_REF_KEY: &str = "\u{0}folderRef"; + /// The path of the `File` that `d` stands for ([`FILE_REF_KEY`]). pub fn file_ref_path(d: &crate::Data) -> Option<&str> { let crate::Data::Object(items) = d else { return None }; @@ -63,7 +68,33 @@ pub fn file_ref_path(d: &crate::Data) -> Option<&str> { } } +/// What a host gives for a `File` at `path`, in the host's platform form: the script receives a +/// `File` object for it. +pub fn file_ref(path: &str) -> crate::Data { + crate::Data::Object(vec![(FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) +} + +/// What a host gives for a `Folder` at `path`, in the host's platform form: the script receives a +/// `Folder` object for it. +pub fn folder_ref(path: &str) -> crate::Data { + crate::Data::Object(vec![(FOLDER_REF_KEY.to_string(), crate::Data::String(path.to_string()))]) +} + impl Interp { + /// A new `File` (or, with `folder`, a `Folder`) for `path`, a path in the host's platform form + /// that a host gave ([`file_ref`], [`folder_ref`]). The host's `parse` reads it from + /// `Folder.current`, as it reads the path of `new File()`, so a relative path names a file there. + pub(crate) fn write_fs_ref(&mut self, path: &str, folder: bool) -> JsResult { + let c = classes(self)?; + let proto = if folder { c.folder_proto } else { c.file_proto }; + let text = Value::str(path); + let fs = self.rooted(std::slice::from_ref(&text), |i| { + let p = parse_text(i, text.clone(), true)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs")) + })?; + instance(self, proto, fs) + } + /// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is /// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads /// it; `None` for any other object, one made with `Object.create(File.prototype)` included. diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index a639dbd0cb..76a36d25c6 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -321,7 +321,7 @@ impl Interp { self.use_fuel()?; self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?; let name = String::from_utf16_lossy(&k); - if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) { + if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY || name == crate::FOLDER_REF_KEY) { return Err(self.data_error(r, ErrorType::Type, "is not plain data")); } r.path.push(Step::Name(k)); @@ -345,6 +345,14 @@ impl Interp { if depth > self.data_limits.depth { return Err(self.throw(ErrorType::Range, "a host value is nested too deep")); } + // A host member's `File` or `Folder` ([`crate::file_ref`], [`crate::folder_ref`]). + if self.write_hosted + && let Data::Object(items) = &d + && let [(k, Data::String(path))] = items.as_slice() + && (k == crate::FILE_REF_KEY || k == crate::FOLDER_REF_KEY) + { + return self.write_fs_ref(path, k == crate::FOLDER_REF_KEY); + } Ok(match d { Data::Undefined => Value::Undefined, Data::Null => Value::Null, diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 45f6aa61e4..9d32e92b26 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -81,7 +81,7 @@ pub use ast::{ }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; -pub use file_classes::{FILE_REF_KEY, file_ref_path}; +pub use file_classes::{FILE_REF_KEY, FOLDER_REF_KEY, file_ref, file_ref_path, folder_ref}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index d17a580560..492bf4eb19 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -130,6 +130,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// `SaveOptions.SAVECHANGES` read at `line`: a `Document.close` given it saves the document to + /// its own file, and the value may reach `close` through a variable or an argument. + fn save_changes(&mut self, line: Option) { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + } + /// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes. fn file_setter(&mut self, line: Option) { self.acc.feature(FeatureId::FileWrite, line); @@ -200,6 +207,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) { self.acc.feature(FeatureId::FilePlaces, line); } + if n == catalog::SAVE_CHANGES { + self.save_changes(line); + } if n == catalog::ON_DRAW { self.acc.feature(FeatureId::ScriptuiDrawing, line); } @@ -419,6 +429,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if t.text.contains(catalog::ACTION_TEXT) { self.acc.feature(FeatureId::Actions, line); } + // `SaveOptions['SAVECHANGES']`, or the value written as the string `"SaveOptions.SAVECHANGES"`. + let value = unquote(t.text, 32); + if value == catalog::SAVE_CHANGES + || value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) + { + self.save_changes(line); + } let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!==")); if compares && word(h1, "typename") && is(h2, ".") { let name = unquote(t.text, self.acc.limits.echo.saturating_add(1)); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index a73dd557d6..7ed0a20efd 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -77,6 +77,12 @@ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", " // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +// The save option of `Document.close` that saves the document to its own file: +// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and +// https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ (SaveOptions). +pub(crate) const SAVE_CHANGES: &str = "SAVECHANGES"; +pub(crate) const SAVE_OPTIONS: &str = "SaveOptions"; + // 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 76d78f822b..1596b37eed 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -543,6 +543,25 @@ fn save_as_and_export_file_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in +/// brackets, as a string or through a variable; closing without it, and the other save options, +/// write nothing. +#[test] +fn closing_with_save_changes_writes_a_file() { + let r = report(concat!( + "app.activeDocument.close();\n", + "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);\n", + "app.activeDocument.close(SaveOptions.PROMPTTOSAVECHANGES);\n", + "app.activeDocument.close(SaveOptions.SAVECHANGES);\n", + "var how = SaveOptions['SAVECHANGES'];\n", + "documents[0].close(how);\n", + "documents[1].close('SaveOptions.SAVECHANGES');\n", + "var w = new Window('dialog'); w.close(1);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 7][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 7][..])]); +} + /// `saveAs` and `exportFile` called with their names as string literals in brackets write the file /// too; reading the method without calling it does not. #[test] diff --git a/docs/gaps.md b/docs/gaps.md index cecbd9c4c4..46a4d063b5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -810,7 +810,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, and save, export and open documents with - `Document.saveAs`, `Document.exportFile` and `app.open`. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + `Document.saveAs`, `Document.exportFile` and `app.open`, read a document's `fullName`, `path` and `saved`, and + close it with `Document.close`. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 5dd133dc00..ed7af26ab5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2562,7 +2562,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, - `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, on any object that may be a File object; only `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out; a - document's `saveAs` or `exportFile` counts too), `filesOpened` (files opened in other apps), `network`, + document's `saveAs` or `exportFile` counts too, and so does `SaveOptions.SAVECHANGES` wherever the script reads it, + since `close` given it saves the document to its file), `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, @@ -2700,9 +2701,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/); without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and `exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and - `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`, - `postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to + `compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`), `saveMultipleArtboards` and `artboardRange` of `.ai`; + `cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint`, `compatibility`, + `saveMultipleArtboards` and `artboardRange` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to `ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF. + As the `.ai` and EPS help pages say, `artboardRange` is used only with `saveMultipleArtboards` true, and an + empty range means every artboard. `Document.fullName` is a `File` for the document's file, `Document.saved` is + true when the document has no unsaved changes and can be set, and `Document.close(saveOptions?)` closes the + document with the given `SaveOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()` and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/), @@ -2713,7 +2719,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, - `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. + `EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as + `"ExportType.PNG24"`. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is @@ -2729,7 +2736,26 @@ app through the global object `vc`, and writes to the Script Console and runs ot an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default - keeps the preset's value. A bad value throws an error before anything is written. + keeps the preset's value. A `pDFPreset` in square brackets, such as `[Smallest File Size]`, names the built-in + preset of the name inside them; the default preset's name in brackets names VectorCraft Default, and + `[PDF/X-4:2008]` names PDF/X-4:2010. Any other name throws `unknown PDF preset`. `artboardRange` takes + a whole number from 1 as well as a string, read as `String(number)` reads it; any other number throws. With `saveMultipleArtboards` true, a `.ai` range + (every artboard when it is empty) goes to `file.saveAs`'s `separateArtboards`, which also writes each of its + artboards to `-.ai`, and an EPS range goes to `useArtboards`, which writes + `_.eps` for each of two or more artboards beside the file at the path, and for one artboard + writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS + `artboardRange` is not checked against the document's artboards, but one that is not written as a range of + artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's + file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of + `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw + `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved + without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an + undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; + `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format its extension + names and after the same write-access check of the path as `saveAs`, and throws an error + and leaves the document open when the document has no file (a converted or recovered document included); and + `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. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -8998,7 +9024,9 @@ document. With no document open they fail with "no document open". `document.act the current one. `document.move {from?, to}` reorders open documents the way dragging a document tab along the tab strip does: `from` defaults to the current document, `to` is the destination index, documents between them shift by one, the current document stays current, and each document keeps its own view (#5663). It is an engine command, so headless and -remote `command_list` both list it. `file.close {index}` on a document other than the current one leaves the current +remote `command_list` both list it. `document.setSaved {index?, saved}` records a document as saved (`true`) or as +having unsaved changes (`false`) without saving it and without an undo step; a script's `Document.saved = value` runs +it. `file.close {index}` on a document other than the current one leaves the current document current, and its tool keeps its state; closing the current document makes the document in the next tab current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first, to ask whether to save it. diff --git a/docs/roadmap.md b/docs/roadmap.md index 40c4518f52..2ea3d51b15 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,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, and save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`; 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, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, type and the other classes) 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 123604eaec..aaf9712151 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 - 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, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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 3ef4b97983b1b021bcdc74617287d6adbfcd89a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 21:58:26 -0800 Subject: [PATCH 11/20] Scripts: closing with SAVECHANGES keeps the document's format, and an empty artboardRange is refused Document.close(SaveOptions.SAVECHANGES) now saves in the format the document was last saved in, so a PDF saved to a file whose extension names another format stays a PDF. An artboardRange with no parts, such as ',' or ' , ', now throws, as a range used for the save does. --- crates/engine/src/script/dom/save_open.rs | 29 ++++++++++++--------- crates/engine/src/tests/script_save_open.rs | 25 +++++++++++++++++- docs/mcp.md | 4 +-- 3 files changed, 42 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index b2c9a56378..d94122c702 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -260,8 +260,8 @@ fn artboard_files(format: &str, q: &mut Map) -> std::result::Resu Ok(()) } -/// Whether `r` is written as an artboard range, whatever artboards a document has: parts separated -/// by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out +/// Whether `r` is written as an artboard range, whatever artboards a document has: one or more +/// parts separated by commas, each a number from 1, or two of them joined by `-` or `–` with either one left out /// and the first no greater than the second. fn written_as_range(r: &str) -> bool { // A number of digits alone, from 1; past `u64` it counts as the largest. @@ -273,14 +273,16 @@ fn written_as_range(r: &str) -> bool { let n = t.bytes().all(|b| b.is_ascii_digit()).then(|| t.parse::().unwrap_or(u64::MAX))?; (n >= 1).then_some(Some(n)) }; - r.split(',').map(str::trim).filter(|p| !p.is_empty()).all(|part| match part.replace('\u{2013}', "-").split_once('-') { - Some((a, b)) => match (num(a), num(b)) { - (Some(Some(a)), Some(Some(b))) => a <= b, - (Some(a), Some(b)) => a.is_some() || b.is_some(), - _ => false, - }, - None => matches!(num(part), Some(Some(_))), - }) + let mut parts = r.split(',').map(str::trim).filter(|p| !p.is_empty()).peekable(); + parts.peek().is_some() + && parts.all(|part| match part.replace('\u{2013}', "-").split_once('-') { + Some((a, b)) => match (num(a), num(b)) { + (Some(Some(a)), Some(Some(b))) => a <= b, + (Some(a), Some(b)) => a.is_some() || b.is_some(), + _ => false, + }, + None => matches!(num(part), Some(Some(_))), + }) } const AI_KEPT: &[(&str, Default)] = &[ @@ -896,7 +898,7 @@ const NO_FILE_TO_SAVE: &str = /// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved /// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES` /// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with -/// `file.saveAs` in the format its extension names, after the write-access check `saveAs` makes of +/// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of /// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] /// for a document that has no file, a converted or recovered one included; and /// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script @@ -907,7 +909,8 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, None => "PROMPTTOSAVECHANGES", }; - let (dirty, file) = super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered))); + let (dirty, file, format) = + super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format)); if dirty { match how { "DONOTSAVECHANGES" => {} @@ -916,7 +919,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; - let p = json!({"path": plain(real)}); + let p = json!({"path": plain(real), "format": format}); exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 4389838807..478f68855b 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -696,6 +696,29 @@ fn a_document_without_unsaved_changes_closes_with_any_save_options() { let _ = std::fs::remove_dir_all(base); } +/// `close(SaveOptions.SAVECHANGES)` saves in the format the document was last saved in, not the +/// one its file's extension names. +#[test] +fn closing_with_save_changes_keeps_the_documents_format() { + let base = folder("closeformat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);" + ), + ); + let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default(); + assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format"); + assert!(s.documents().is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// Setting `Document.saved` records the document's saved state without saving it: `true` lets /// `close()` close a document with edits, and `false` makes an untouched one ask. #[test] @@ -867,7 +890,7 @@ fn save_multiple_artboards_writes_a_file_per_artboard() { ), ); assert!(dir.join("aioff/c.ai").is_file(), "a range past the document's artboards is not used and does not stop the save"); - for bad in ["'abc'", "'0-'", "'3-1'", "'-'", "-1", "2.5", "0"] { + for bad in ["'abc'", "'0-'", "'3-1'", "'-'", "','", "' , '", "-1", "2.5", "0"] { let e = failure( &mut s, &base, diff --git a/docs/mcp.md b/docs/mcp.md index ed7af26ab5..c7757d4464 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2751,8 +2751,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; - `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format its extension - names and after the same write-access check of the path as `saveAs`, and throws an error + `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document + was last saved in and after the same write-access check of the path as `saveAs`, and throws an error and leaves the document open when the document has no file (a converted or recovered document included); and `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. From 9c12aceb6966474b23fbfbf05a02cf2f35df0cf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:20:46 -0800 Subject: [PATCH 12/20] Scripts: format the merged object class list in heap.rs --- crates/js/src/heap.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index b7b0dd4a63..64f16c12a2 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -337,13 +337,9 @@ impl Class { Class::XmlFilter(_) => "Object", Class::Math => "Math", Class::Json => "JSON", - Class::Ordinary - | Class::ForIn(_) - | Class::Host(_) - | Class::FsEntry(_) - | Class::Symbol(_) - | Class::Iterator(_) - | Class::IterRecord(_) => "Object", + Class::Ordinary | Class::ForIn(_) | Class::Host(_) | Class::FsEntry(_) | Class::Symbol(_) | Class::Iterator(_) | Class::IterRecord(_) => { + "Object" + } Class::Array { .. } => "Array", Class::Function(_) => "Function", Class::Error(_) => "Error", From e2b33969dc64d57f4edc7c012fe41dba921375dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:48:56 -0800 Subject: [PATCH 13/20] Scripts: the plugin gate test sets held, and catalogs keep main's rows The merge with main added a ScriptGate initializer in the plugin tests that predates the held field. The two script save errors are added in English only; their translations go through craft-i18n. --- crates/engine/src/tests/plugins.rs | 1 + crates/ui-egui/src/i18n/ca.tsv | 2 -- crates/ui-egui/src/i18n/cs.tsv | 2 -- crates/ui-egui/src/i18n/da.tsv | 2 -- crates/ui-egui/src/i18n/de.tsv | 2 -- crates/ui-egui/src/i18n/el.tsv | 2 -- crates/ui-egui/src/i18n/es.tsv | 2 -- crates/ui-egui/src/i18n/fi.tsv | 2 -- crates/ui-egui/src/i18n/fr.tsv | 2 -- crates/ui-egui/src/i18n/hi.tsv | 2 -- crates/ui-egui/src/i18n/hu.tsv | 2 -- crates/ui-egui/src/i18n/id.tsv | 2 -- crates/ui-egui/src/i18n/it.tsv | 2 -- crates/ui-egui/src/i18n/ja.tsv | 2 -- crates/ui-egui/src/i18n/ka.tsv | 2 -- crates/ui-egui/src/i18n/ko.tsv | 2 -- crates/ui-egui/src/i18n/nl.tsv | 2 -- crates/ui-egui/src/i18n/pl.tsv | 2 -- crates/ui-egui/src/i18n/pt-br.tsv | 2 -- crates/ui-egui/src/i18n/ru.tsv | 2 -- crates/ui-egui/src/i18n/sv.tsv | 2 -- crates/ui-egui/src/i18n/tr.tsv | 2 -- crates/ui-egui/src/i18n/uk.tsv | 2 -- crates/ui-egui/src/i18n/vi.tsv | 2 -- crates/ui-egui/src/i18n/zh-hans.tsv | 2 -- crates/ui-egui/src/i18n/zh-hant.tsv | 2 -- 26 files changed, 1 insertion(+), 50 deletions(-) diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 0a255fb3a3..fc3586756f 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2202,6 +2202,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t read: ScriptScope::of_folder(&inside), write: ScriptScope::default(), documents: vec![], + held: vec![], linked: Default::default(), also: None, }; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 70b0e70d00..87f76147b6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6631,8 +6631,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written No s’ha pogut escriure el fitxer de l’script @msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui @msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi -@msg Script file is read-only El fitxer de l’script és només de lectura -@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi @msg Script file name is already in use El nom del fitxer de l’script ja està en ús @msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta @msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f67e75d6f1..13129a99a0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5416,8 +5416,6 @@ liquify-list-end {0}, {1} {0} a {1} @msg Script file could not be written Soubor skriptu nelze zapsat @msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví @msg Script file is not open for writing Soubor skriptu není otevřený pro zápis -@msg Script file is read-only Soubor skriptu je jen pro čtení -@msg Script file is open for writing Soubor skriptu je otevřený pro zápis @msg Script file name is already in use Název souboru skriptu se už používá @msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky @msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 18030993dc..94df1eb83e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -88,8 +88,6 @@ @msg Script file could not be written Scriptfilen kunne ikke skrives @msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person @msg Script file is not open for writing Scriptfilen er ikke åben for skrivning -@msg Script file is read-only Scriptfilen er skrivebeskyttet -@msg Script file is open for writing Scriptfilen er åben for skrivning @msg Script file name is already in use Scriptfilens navn er allerede i brug @msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe @msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 61ccfe0721..0fb57437c4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4995,8 +4995,6 @@ liquify-list-end {0}, {1} {0} und {1} @msg Script file could not be written Skriptdatei konnte nicht geschrieben werden @msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet @msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet -@msg Script file is read-only Skriptdatei ist schreibgeschützt -@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet @msg Script file name is already in use Name der Skriptdatei wird bereits verwendet @msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein @msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index dcbd2fd5c3..3bd10eceb1 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2825,8 +2825,6 @@ liquify-list-end {0}, {1} {0} και {1} @msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου @msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει @msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή -@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση -@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή @msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη @msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο @msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 37e1a3bd42..7e71c1c191 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5103,8 +5103,6 @@ liquify-list-end {0}, {1} {0}, {1} @msg Script file could not be written No se pudo escribir el archivo del script @msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda @msg Script file is not open for writing El archivo del script no está abierto para escritura -@msg Script file is read-only El archivo del script es de solo lectura -@msg Script file is open for writing El archivo del script está abierto para escritura @msg Script file name is already in use El nombre del archivo del script ya está en uso @msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta @msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 064d7d6da9..cc6e0d2fd2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5344,8 +5344,6 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa @msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö @msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten -@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa -@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten @msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä @msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota @msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3afc56aa93..6bcf110355 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5062,8 +5062,6 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script file could not be written Le fichier du script n’a pas pu être écrit @msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre @msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture -@msg Script file is read-only Le fichier du script est en lecture seule -@msg Script file is open for writing Le fichier du script est ouvert en écriture @msg Script file name is already in use Le nom du fichier du script est déjà utilisé @msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier @msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 567cf5740c..986e007efc 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7793,8 +7793,6 @@ liquify-list-end {0}, {1} {0} और {1} @msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी @msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है @msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है -@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है -@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d7b576514a..ec8a60deaf 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5937,8 +5937,6 @@ liquify-list-end {0}, {1} {0} és {1} @msg Script file could not be written A parancsfájl fájlját nem sikerült írni @msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia @msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva -@msg Script file is read-only A parancsfájl fájlja csak olvasható -@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva @msg Script file name is already in use A parancsfájl fájljának neve már használatban van @msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen @msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 8445293d26..3b3069e023 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8815,8 +8815,6 @@ breakText Glyphs Glif @msg Script file could not be written File skrip tidak dapat ditulis @msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya @msg Script file is not open for writing File skrip tidak dibuka untuk ditulis -@msg Script file is read-only File skrip hanya dapat dibaca -@msg Script file is open for writing File skrip sedang dibuka untuk ditulis @msg Script file name is already in use Nama file skrip sudah digunakan @msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder @msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 94715f0eff..8e7959999c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5133,8 +5133,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Impossibile scrivere il file dello script @msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda @msg Script file is not open for writing Il file dello script non è aperto in scrittura -@msg Script file is read-only Il file dello script è di sola lettura -@msg Script file is open for writing Il file dello script è aperto in scrittura @msg Script file name is already in use Il nome del file dello script è già in uso @msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella @msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c6e123c242..d14fc0f723 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5968,8 +5968,6 @@ liquify-list-end {0}, {1} {0}、{1} @msg Script file could not be written スクリプトのファイルを書き込めませんでした @msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です @msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません -@msg Script file is read-only スクリプトのファイルは読み取り専用です -@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています @msg Script file name is already in use スクリプトのファイル名はすでに使用されています @msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください @msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 47cabd5226..1991d156eb 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -8638,8 +8638,6 @@ liquify-list-end {0}, {1} {0} და {1} @msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა @msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს @msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის -@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია -@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია @msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება @msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე @msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 0e2f433152..005f8284ea 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5897,8 +5897,6 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 @msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 @msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 -@msg Script file is read-only 스크립트 파일이 읽기 전용입니다 -@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다 @msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 @msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 @msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index e9293a7be3..731173eea6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -90,8 +90,6 @@ @msg Script file could not be written Het scriptbestand kon niet worden geschreven @msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord @msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven -@msg Script file is read-only Het scriptbestand is alleen-lezen -@msg Script file is open for writing Het scriptbestand is geopend voor schrijven @msg Script file name is already in use De naam van het scriptbestand is al in gebruik @msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn @msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index e97c78e081..9152459071 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5235,8 +5235,6 @@ liquify-list-end {0}, {1} {0} i {1} @msg Script file could not be written Nie można zapisać pliku skryptu @msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie @msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu -@msg Script file is read-only Plik skryptu jest tylko do odczytu -@msg Script file is open for writing Plik skryptu jest otwarty do zapisu @msg Script file name is already in use Nazwa pliku skryptu jest już używana @msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu @msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 87f2ac800b..b49b217c8f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6280,8 +6280,6 @@ liquify-list-end {0}, {1} {0} e {1} @msg Script file could not be written Não foi possível gravar o arquivo do script @msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las @msg Script file is not open for writing O arquivo do script não está aberto para gravação -@msg Script file is read-only O arquivo do script é somente leitura -@msg Script file is open for writing O arquivo do script está aberto para gravação @msg Script file name is already in use O nome do arquivo do script já está em uso @msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta @msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index decd022096..eec9216b69 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5128,8 +5128,6 @@ liquify-list-end {0}, {1} {0} и {1} @msg Script file could not be written Не удалось записать файл скрипта @msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек @msg Script file is not open for writing Файл скрипта не открыт для записи -@msg Script file is read-only Файл скрипта доступен только для чтения -@msg Script file is open for writing Файл скрипта открыт для записи @msg Script file name is already in use Имя файла скрипта уже используется @msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки @msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f014e5d79e..a4184199a4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5001,8 +5001,6 @@ liquify-list-end {0}, {1} {0} och {1} @msg Script file could not be written Skriptets fil kunde inte skrivas @msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem @msg Script file is not open for writing Skriptets fil är inte öppen för skrivning -@msg Script file is read-only Skriptets fil är skrivskyddad -@msg Script file is open for writing Skriptets fil är öppen för skrivning @msg Script file name is already in use Namnet på skriptets fil används redan @msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp @msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 78997530b9..6f1d616aca 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4831,8 +4831,6 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Script file could not be written Betiğin dosyası yazılamadı @msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir @msg Script file is not open for writing Betiğin dosyası yazmak için açık değil -@msg Script file is read-only Betiğin dosyası salt okunur -@msg Script file is open for writing Betiğin dosyası yazmak için açık @msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor @msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır @msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f13fd4a094..89c20c44a5 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5117,8 +5117,6 @@ liquify-list-end {0}, {1} {0} і {1} @msg Script file could not be written Не вдалося записати файл скрипту @msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина @msg Script file is not open for writing Файл скрипту не відкрито для запису -@msg Script file is read-only Файл скрипту доступний лише для читання -@msg Script file is open for writing Файл скрипту відкрито для запису @msg Script file name is already in use Ім’я файлу скрипту вже використовується @msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки @msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 407e46823f..d358d49544 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5627,8 +5627,6 @@ liquify-list-end {0}, {1} {0} và {1} @msg Script file could not be written Không thể ghi tệp của tập lệnh @msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời @msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi -@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc -@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi @msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng @msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục @msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3c2d9eedda..c48a32148a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5624,8 +5624,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 无法写入脚本的文件 @msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 @msg Script file is not open for writing 脚本的文件未以写入方式打开 -@msg Script file is read-only 脚本的文件为只读 -@msg Script file is open for writing 脚本的文件已以写入方式打开 @msg Script file name is already in use 脚本的文件名已被使用 @msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 @msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d79d239334..58c451afd6 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2968,8 +2968,6 @@ liquify-list-end {0}, {1} {0}和{1} @msg Script file could not be written 無法寫入指令碼的檔案 @msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 @msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 -@msg Script file is read-only 指令碼的檔案為唯讀 -@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟 @msg Script file name is already in use 指令碼的檔案名稱已在使用中 @msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 @msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 From 39c5e98a3ef9eeb0174af54c19ca11d068438bc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 03:15:09 -0800 Subject: [PATCH 14/20] Scripts: refuse unsafe close saves and refused multi-file writes up front - A save of several files whose file access refuses one of them returns the refusal before any file goes to the writer, so a writer that does not check the file access writes nothing. - close(SaveOptions.SAVECHANGES) throws before writing, and leaves the document open, when the document's last save named some of its artboards, since saving with those options again could leave changes out of the file. - The script check no longer treats an object literal's saveAs or exportFile as the script's own when a function body assigns the variable without declaring it, or when the script assigns it as a property of this (the global object in global code and in a function called without a receiver). - The close-with-SAVECHANGES format test reads the saved PDF and checks that it holds the change made after the first save. - docs/mcp.md limits the "none of them is written" sentence for SVG linked images to refusals found before the first write, and documents the new close refusal. --- crates/engine/src/cmd/fileio/save.rs | 11 +++--- crates/engine/src/script/dom/save_open.rs | 26 +++++++++++-- crates/engine/src/tests/script_save_open.rs | 43 ++++++++++++++++++++- crates/scriptcheck/src/analyze.rs | 39 +++++++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 17 +++++++- crates/scriptcheck/src/tests.rs | 40 +++++++++++++++++++ docs/mcp.md | 6 ++- 7 files changed, 168 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cf00d4194a..7c185352a0 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,15 +1071,14 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. A refused file is not handed to `write`, so a writer that does not check the + // file access writes none of the files; the error is the file access's own refusal, as + // the writers that check it give. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) { - write(p, bytes)?; - // A writer that does not check the file access writes none of the others. - return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); + return Err(refused); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 6400b32f73..8d282ce7bb 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -896,12 +896,29 @@ const UNSAVED_CHANGES: &str = const NO_FILE_TO_SAVE: &str = "the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; +/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose +/// last save named some of its artboards: saving with those options again could leave changes out. +const SAVES_SOME_ARTBOARDS: &str = + "the document was last saved with some of its artboards named: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + +/// Whether the options `st` was last saved with name artboards (`artboard`, `artboards`, or a +/// `range` other than all of them), so that a save with them may write only some of the artboards. +fn picks_artboards(st: &crate::doc_state::DocState) -> bool { + let options = crate::cmd::fileio::remembered_save_options(st); + crate::cmd::fileio::ARTBOARD_PARAMS.iter().any(|k| match options.get(*k) { + None | Some(Value::Null) => false, + Some(Value::String(r)) if *k == "range" => !(r.trim().is_empty() || r.trim().eq_ignore_ascii_case("all")), + Some(_) => true, + }) +} + /// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved /// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES` /// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with /// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of /// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] -/// for a document that has no file, a converted or recovered one included; and +/// for a document that has no file, a converted or recovered one included, and +/// [`SAVES_SOME_ARTBOARDS`] before writing when the document's last save named some of its artboards; and /// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script /// cannot show the prompt. fn doc_close(h: &Host, a: &[Data]) -> Answer { @@ -910,13 +927,16 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, None => "PROMPTTOSAVECHANGES", }; - let (dirty, file, format) = - super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format)); + let (dirty, file, format, picked) = + super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format, picks_artboards(st))); if dirty { match how { "DONOTSAVECHANGES" => {} "SAVECHANGES" => { let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + if picked { + return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into())); + } // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index a3f937a244..9ce5c2f820 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -208,7 +208,7 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { } /// When the writer a save is given does not check the file access itself, a save of several files -/// still writes none of them after the refused one. +/// whose file access refuses one of them hands none of them to the writer. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -247,7 +247,7 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { }); assert!(r.is_err(), "{r:?}"); let refused = refused.unwrap(); - assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + assert_eq!(written, Vec::::new(), "no file went to the writer, the refused one ({refused}) included"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); @@ -722,10 +722,49 @@ fn closing_with_save_changes_keeps_the_documents_format() { ); let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default(); assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format"); + let pdf = vectorcraft_pdf::import(&bytes).unwrap(); + let mut sizes = vec![]; + for l in &pdf.layers { + l.walk(&mut |n| sizes.extend(n.geometric_bounds().map(|b| (b.width(), b.height())))); + } + let near = |(w, h): (f64, f64), (x, y): (f64, f64)| (w - x).abs() < 0.01 && (h - y).abs() < 0.01; + assert!(sizes.iter().any(|&s| near(s, (5.0, 5.0))), "the file holds the rectangle drawn after the first save: {sizes:?}"); + assert!(sizes.iter().any(|&s| near(s, (50.0, 20.0))), "and the first one: {sizes:?}"); assert!(s.documents().is_empty()); let _ = std::fs::remove_dir_all(base); } +/// `close(SaveOptions.SAVECHANGES)` on a document whose last save named some of its artboards +/// throws before writing and leaves the document open, so no change is left out of its file. +#[test] +fn closing_with_save_changes_refuses_a_save_of_some_artboards() { + let base = folder("closerange"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + var o = new PDFSaveOptions(); o.artboardRange = '2'; d.saveAs(new File({d} + '/r.pdf'), o);\n\ + vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}});\n\ + var e = ''; try {{ d.close(SaveOptions.SAVECHANGES); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);" + ), + ); + assert!(out[0][0].as_str().unwrap().contains("some of its artboards"), "{}", out[0]); + assert_eq!(out[0][1], json!(1), "the document stays open"); + let pdf = vectorcraft_pdf::import(&std::fs::read(dir.join("r.pdf")).unwrap()).unwrap(); + let mut drawn = 0; + for l in &pdf.layers { + l.walk(&mut |n| drawn += usize::from(n.geometric_bounds().is_some_and(|b| (b.width() - 5.0).abs() < 0.01))); + } + assert_eq!(drawn, 0, "the file is left as the first save wrote it"); + assert!(s.active().unwrap().is_dirty(), "the change is still unsaved"); + let _ = std::fs::remove_dir_all(base); +} + /// Setting `Document.saved` records the document's saved state without saving it: `true` lets /// `close()` close a document with edits, and `false` makes an untouched one ask. #[test] diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 8765501507..7a596f5633 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -647,6 +647,12 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The variables that may get another value when code read elsewhere runs: assigned inside a + /// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]). + /// None of them joins [`Analyzer::writers`]. + later: HashSet, + /// `later` ran out of room: no variable joins [`Analyzer::writers`]. + later_full: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -727,6 +733,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + later: HashSet::new(), + later_full: false, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1417,9 +1425,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // A name after `.`, `..`, `.@`, `::` or `@` is a property's or an attribute's; any other // name before `=` is a variable, at the start of a statement or inside an expression. if !member_mark(h1) && !is(h1, "@") { + if !self.scopes.is_empty() && !self.declared_in_body(name.text) { + self.reassigned_later(name.text); + } self.assign = Some(Assign { name: name.text.to_string(), after_new: false }); } } + if let Some((name, _)) = self.updated(t) + && !self.scopes.is_empty() + && !self.declared_in_body(name) + { + self.reassigned_later(name); + } match self.updated(t) { // The value on the right is read at this depth, and the name holds nothing the check // follows once that value ends ([`Analyzer::settle_groups`]). @@ -1435,12 +1452,34 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.later_full + && !self.later.contains(&name) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); } } + /// `name` may get another value when code read elsewhere runs: a function body assigns it without + /// declaring it, and the function may be called before or after any line, or it is assigned as a + /// property of `this`. Its object literal's methods are no longer known, now or later. + fn reassigned_later(&mut self, name: &str) { + self.writers.remove(name); + if !self.later.contains(name) { + if self.acc.room(self.later.len()) { + self.later.insert(name.to_string()); + } else { + self.later_full = true; + } + } + } + + /// Whether `name` is declared in a function body this token is inside (`var name`, `function + /// name`, a parameter). + fn declared_in_body(&self, name: &str) -> bool { + self.scopes.iter().any(|s| s.saved.get(name).is_some_and(|v| v.local)) + } + /// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single /// function expression directly inside its braces as the whole value of a key that names a /// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 48303c173e..9a99338da4 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -376,9 +376,24 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `local[k] = w`, `delete local.saveAs`). fn writer_use(&mut self, t: &Sig<'s>) { let [h0, h1, h2, h3] = self.h; - let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); let key = t.is(":") && (is(h1, "{") || is(h1, ",")); + // `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a + // 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") { + h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) + } else if is(h0, "]") && is(h2, "[") && word(h3, "this") { + h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64)) + } else { + None + }; + if let Some(name) = global { + self.reassigned_later(&name); + } + } + let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let escaped = if word(h0, "delete") { // `delete local…` writer(Some(*t), h0) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 1524d4d7ae..422679f803 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -664,6 +664,46 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +/// A function body read before the literal that assigns its variable without declaring it may run +/// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the +/// name assigns its own variable. +#[test] +fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { + let r = report(concat!( + "var f = new File(p);\n", + "function choose() { d = app.activeDocument; }\n", + "var d = {saveAs: function () {}};\n", + "choose(); d.saveAs(f);\n", + "function bump() { e++; }\n", + "var e = {saveAs: function () {}};\n", + "e.saveAs(f);\n", + "function own() { var g; g = app.activeDocument; }\n", + "var g = {saveAs: function () {}};\n", + "g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); +} + +/// Assigning a property of `this`, the global object in the global code and in a function called +/// without a receiver, may give the global variable of that name another value, before or after +/// its literal. +#[test] +fn assigning_a_property_of_this_keeps_save_as_writing() { + let r = report(concat!( + "var f = new File(p);\n", + "var d = {saveAs: function () {}};\n", + "this.d = app.activeDocument;\n", + "d.saveAs(f);\n", + "function swap() { this['e'] = app.activeDocument; }\n", + "var e = {saveAs: function () {}};\n", + "swap(); e.saveAs(f);\n", + "var g = {saveAs: function () {}};\n", + "this.other = 1;\n", + "g.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); +} + /// A `saveAs` key's value is a method of the script's own only when the whole value is one function /// expression: a value that goes on after the function's body, and a literal inside another, leave /// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body diff --git a/docs/mcp.md b/docs/mcp.md index 5c2c05d8fe..c3794b55b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2935,7 +2935,8 @@ other files through `$`: format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with `compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and - when one of those files may not be written, none of them is. A listed option that is not mapped is accepted at its help page's default, and any other value throws + when the script's folders refuse one of those files, none of them is written; a write that fails once the + first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and `parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default @@ -2956,7 +2957,8 @@ other files through `$`: undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document was last saved in and after the same write-access check of the path as `saveAs`, and throws an error - and leaves the document open when the document has no file (a converted or recovered document included); and + and leaves the document open when the document has no file (a converted or recovered document included) or when + its last save named some of its artboards, without writing anything; and `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. - `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/) From 043650d79453475332245a48cc49ff5055e5a583 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:21:56 -0800 Subject: [PATCH 15/20] Scripts: tighten save, open and close edge cases - saveAs picks the encoder from the requested name, so a link to a file of another format writes the format the name asks for. - fullName, path and close(SaveOptions.SAVECHANGES) resolve a relative saved path against the working directory. - close(SAVECHANGES) accepts an artboard range that covers every artboard and keeps the document open when the save would drop artboards. - app.open keeps the requested file name, rejects a file over 128 MiB before reading it, applies the requested color space to plug-in imports, and rejects PDF options for files that are not PDF content; null PDF options keep their defaults. - Explicit null options throw; assigning the current Document.saved value runs no command; Document.path reflects as Folder or string. - An implicit multi-file save names no refused path in its error. - The script checker counts SAVECHANGES only on SaveOptions and keeps write warnings for receivers that evaluated code can rebind. --- crates/engine/src/cmd/fileio.rs | 3 + crates/engine/src/cmd/fileio/access.rs | 31 +- crates/engine/src/cmd/fileio/load.rs | 8 +- crates/engine/src/cmd/fileio/save.rs | 10 +- crates/engine/src/cmd/fileio/svg.rs | 2 +- crates/engine/src/script/dom.rs | 4 +- crates/engine/src/script/dom/save_open.rs | 80 +++-- crates/engine/src/tests/script_save_open.rs | 351 ++++++++++++++++++++ crates/engine/tests/plugin_import.rs | 33 ++ crates/scriptcheck/src/analyze.rs | 4 +- crates/scriptcheck/src/analyze/features.rs | 17 +- crates/scriptcheck/src/tests.rs | 52 +++ docs/mcp.md | 15 +- 13 files changed, 563 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 5f66067142..51d7590f35 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -125,6 +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 use svg::options_map as svg_options; /// Atomic file writes (a temporary file renamed over the target: a failed write never damages the /// file it replaces), for the apps' own writers too. @@ -141,6 +142,8 @@ mod formats; #[cfg(not(target_arch = "wasm32"))] pub(crate) use access::list_dir; +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE}; pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder}; pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with}; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 8ca1fedcd7..84b8bc1a4f 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -267,14 +267,43 @@ pub(crate) fn may_write(path: &str) -> Result<()> { crate::file_access::check_write(path).map_err(EngineError::Other) } +/// The most a file read during a script command holds, the limit an importer reads. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES; +/// The error of a file past [`SCRIPT_OPEN_MAX_BYTES`]. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB"; + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_file(path: &str) -> Result> { + use std::io::Read; may_read(path)?; // A device or pipe may never end: only a regular file is read to its end. if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() { return Err(EngineError::Other(format!("{path}: not a file"))); } - std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + if crate::file_access::in_script_command() { + let max = SCRIPT_OPEN_MAX_BYTES; + let read = || -> std::io::Result> { + let file = std::fs::File::open(path)?; + let meta = file.metadata()?; + if !meta.is_file() { + return Err(std::io::Error::other("not a file")); + } + if meta.len() > max as u64 { + return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE)); + } + let mut bytes = Vec::new(); + file.take(max as u64 + 1).read_to_end(&mut bytes)?; + if bytes.len() > max { + return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE)); + } + Ok(bytes) + }; + read().map_err(|e| EngineError::Other(format!("{path}: {e}"))) + } else { + std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + } } /// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 4f11935db0..e426bd5a23 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -818,7 +818,7 @@ pub fn read_for_open_asking( (linked_pages(name, bytes, path.as_deref(), &opts)?, None) } else { match super::importer::pick(name, bytes, p)? { - Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None), + Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode), // The color mode `p` asks for converts the colors after the policies did, through the // profiles the document keeps. None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode), @@ -1096,6 +1096,12 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result { 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); + if !pdf { + return Err(bad("document.open", "PDF open options require a PDF file")); + } + } // A relative path is the file in the working directory: its folder is where relative links // are found (a bare file name has no folder of its own). let path = src.path.map(super::absolute_path); diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 7c185352a0..af84199414 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,7 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + redact_paths: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +964,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option 1 - && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) + && let Some(refused) = files + .iter() + .find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })) { return Err(refused); } @@ -1240,9 +1243,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; + let mut job = save_job(s, plan)?; let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + job.redact_paths = !given; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 066c6fc63f..e5ecc858dc 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -172,7 +172,7 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option Option { +pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option { let n = doc.artboards.len(); let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing); (n > 1 && !preserved).then(|| { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index f50dbad41d..6cbf460954 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2751,9 +2751,7 @@ fn classes(link: &Link) -> Vec { ("toString", method(l, doc_to_string), returns("string", &[])), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer"] - .into_iter() - .map(|m| later(l, "Document", m)), + ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)), ); document.extend(save_open::document_members(l)); document.extend(variables::document_members(l)); diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 8654d46d7e..bf49aae883 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -43,7 +43,8 @@ //! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no //! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. //! `fullName` and `path` of a document whose file the automation read roots do not allow throw -//! `Script file access denied`. Setting `Document.saved` runs `document.setSaved`. +//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`. +//! Assigning its current value runs no command. //! - `Document.close` with unsaved changes closes without them with //! `SaveOptions.DONOTSAVECHANGES`, and saves them to the document's file first with //! `SaveOptions.SAVECHANGES`, which throws for a document that has no file (a converted or @@ -52,6 +53,9 @@ //! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record: //! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property //! but `typename` and `parent` throws the same error, unless it is `undefined`. +//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files. +//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte. +//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error. //! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The //! commands a script runs never show a dialog, so the level does not change what they do, and it //! never allows a file the script's grants do not. @@ -696,7 +700,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let path = file_path(arg(a, 1), "saveAs")?; let mut p = Map::new(); - let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)); + let given_options = given(arg(a, 2)); // Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options // object of that format's class holds. let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase()); @@ -718,6 +722,9 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } else if !q.is_empty() { p.insert("options".into(), Value::Object(q)); } + } else { + let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id); + p.insert("format".into(), json!(format)); } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); @@ -742,7 +749,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let path = file_path(arg(a, 1), "exportFile")?; let kind = export_kind(arg(a, 2))?; // Without options, an export takes the defaults a new options object of its class holds. - let mut p = match given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) { + let mut p = match given(arg(a, 3)) { None => match kind.options { Some(class) => options_params(class, &fresh(class))?, None => Map::new(), @@ -784,11 +791,11 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { fn app_open(h: &Host, a: &[Data]) -> Answer { let path = file_path(arg(a, 1), "open")?; let mut p = Map::new(); - if let Some(d) = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)) { + if let Some(d) = given(arg(a, 2)) { let mode = if member(d, "DocumentColorSpace", &["CMYK", "RGB"], "documentColorSpace")? == "RGB" { "rgb" } else { "cmyk" }; p.insert("colorMode".into(), json!(mode)); } - if let Some(o) = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) { + if let Some(o) = given(arg(a, 3)) { let Data::Object(items) = o else { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())) }; if typename(o).is_some_and(|t| t != "PDFFileOptions") { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())); @@ -819,8 +826,11 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } } } - let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(real))); + if p.contains_key("cropTo") { + p.insert("editingData".into(), json!(false)); + } + h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; + p.insert("path".into(), json!(plain(std::path::PathBuf::from(path)))); let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { @@ -837,12 +847,23 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { /// The document's file, `None` for a document that has none, or `Script file access denied` with /// the document's name when the automation read roots do not allow the file to be named /// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them. -fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { - match st.path.as_deref() { +fn shown_file(st: &crate::DocState) -> std::result::Result, HostError> { + let path = st.path.as_deref().map(absolute_file).transpose()?; + match path.as_deref() { Some(p) if crate::file_access::check_read(p).is_err() => { Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title()))) } - p => Ok(p), + _ => Ok(path), + } +} + +fn absolute_file(path: &str) -> std::result::Result { + let path = std::path::Path::new(path); + if path.is_absolute() { + Ok(path.to_string_lossy().into_owned()) + } else { + let cwd = std::env::current_dir().map_err(|e| HostError::Error(e.to_string()))?; + Ok(cwd.join(path).to_string_lossy().into_owned()) } } @@ -852,7 +873,7 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; super::with_doc(h, doc, |_, st| { Ok(match shown_file(st)? { - Some(p) => vectorcraft_js::file_ref(p), + Some(p) => vectorcraft_js::file_ref(&p), None => vectorcraft_js::file_ref(&st.title()), }) }) @@ -864,7 +885,7 @@ fn doc_path(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let folder = super::with_doc(h, doc, |_, st| { Ok(shown_file(st)?.and_then(|p| { - let parent = std::path::Path::new(p).parent()?.to_string_lossy().into_owned(); + let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned(); (!parent.is_empty()).then_some(parent) })) })?; @@ -882,6 +903,9 @@ fn doc_saved(h: &Host, a: &[Data]) -> Answer { fn doc_set_saved(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; let saved = boolean(arg(a, 1), "Document.saved")?; + if saved == super::with_doc(h, doc, |_, st| !st.is_dirty()) { + return Ok(Data::Undefined); + } command(h, "document.setSaved", &json!({"index": doc.index, "saved": saved}))?; Ok(Data::Undefined) } @@ -897,19 +921,23 @@ const NO_FILE_TO_SAVE: &str = "the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; /// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose -/// last save named some of its artboards: saving with those options again could leave changes out. +/// save would keep only some of its artboards. const SAVES_SOME_ARTBOARDS: &str = - "the document was last saved with some of its artboards named: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; + "the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; -/// Whether the options `st` was last saved with name artboards (`artboard`, `artboards`, or a -/// `range` other than all of them), so that a save with them may write only some of the artboards. +/// Whether saving `st` with its remembered options would omit artboards. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { - let options = crate::cmd::fileio::remembered_save_options(st); - crate::cmd::fileio::ARTBOARD_PARAMS.iter().any(|k| match options.get(*k) { - None | Some(Value::Null) => false, - Some(Value::String(r)) if *k == "range" => !(r.trim().is_empty() || r.trim().eq_ignore_ascii_case("all")), - Some(_) => true, - }) + 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() { + return true; + } + let count = st.doc.artboards.len(); + let pick = serde_json::from_value::(options); + match pick.map_err(|e| e.to_string()).and_then(|p| p.resolve(count)) { + Ok(None) => false, + Ok(Some(indices)) => (0..count).any(|i| !indices.contains(&i)), + Err(_) => true, + } } /// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved @@ -918,12 +946,12 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool { /// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of /// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`] /// for a document that has no file, a converted or recovered one included, and -/// [`SAVES_SOME_ARTBOARDS`] before writing when the document's last save named some of its artboards; and +/// [`SAVES_SOME_ARTBOARDS`] before writing when the save would omit artboards; and /// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script /// cannot show the prompt. fn doc_close(h: &Host, a: &[Data]) -> Answer { let doc = this_doc(h, a)?; - let how = match given(arg(a, 1)).filter(|d| !matches!(d, Data::Null)) { + let how = match given(arg(a, 1)) { Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?, None => "PROMPTTOSAVECHANGES", }; @@ -933,7 +961,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { match how { "DONOTSAVECHANGES" => {} "SAVECHANGES" => { - let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?; + let path = absolute_file(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?)?; if picked { return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into())); } @@ -974,7 +1002,7 @@ pub(super) fn document_members(l: &Link) -> Vec { ("saveAs", method(l, doc_save_as), returns("undefined", &[("saveIn", "File"), ("options", "*")])), ("exportFile", method(l, doc_export_file), returns("undefined", &[("exportFile", "File"), ("exportFormat", "ExportType"), ("options", "*")])), ("fullName", get(l, doc_full_name), typed("File")), - ("path", get(l, doc_path), typed("File")), + ("path", get(l, doc_path), typed("Folder|string")), ("saved", property(l, doc_saved, doc_set_saved), typed("boolean")), ("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])), ]) diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 9ce5c2f820..8c09da874c 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -93,6 +93,92 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn relative_saved_paths_use_the_process_working_directory() { + let cwd = crate::cmd::findfiles::plain(std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap()); + let relative_base = PathBuf::from(format!("vc-script-relative-save-{}", std::process::id())); + let base = cwd.join(&relative_base); + std::fs::create_dir_all(base.join("main")).unwrap(); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = dir.join("relative.svg"); + let relative = file.strip_prefix(&cwd).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("file.saveAs", &json!({"path": relative.to_string_lossy()})).unwrap(); + let before = std::fs::read(&file).unwrap(); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; Folder.current = new Folder({main}); var d = app.activeDocument;\n\ + vc.log([d.fullName.fsName === new File({file}).fsName, d.path.fsName === new Folder({dir}).fsName]);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);", + main = quoted(&base.join("main")), + file = quoted(&file), + dir = quoted(&dir), + ), + ); + assert_eq!(out, json!([[true, true], 0])); + assert_ne!(std::fs::read(&file).unwrap(), before); + let _ = std::fs::remove_dir_all(base); +} + +#[cfg(unix)] +#[test] +fn save_as_uses_the_link_name_extension_for_the_encoder() { + let base = folder("linkformat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let target = dir.join("drawing.vectorcraft"); + std::fs::write(&target, b"").unwrap(); + std::os::unix::fs::symlink(&target, dir.join("drawing.svg")).unwrap(); + s.execute("file.new", &json!({})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg")))); + assert!(std::fs::read_to_string(&target).unwrap().contains("").unwrap(); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let out = logged(&mut s, &base, &format!("Folder.userData; var d = app.open(new File({})); vc.log([d.name, d.fullName.name]);", quoted(&link))); + assert_eq!(out, json!([["drawing.svg", "drawing.svg"]])); + assert_eq!(s.active().unwrap().format, "svg"); + let _ = std::fs::remove_dir_all(base); +} + /// Without options, a save or export writes what an untouched new options object of its class gives. #[test] fn omitted_options_are_a_new_options_objects_defaults() { @@ -633,6 +719,121 @@ fn open_takes_the_page_and_crop_box_of_its_options() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn crop_only_options_apply_to_an_editable_pdf() { + let base = folder("pdfcroponly"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pdf = dir.join("editable.pdf"); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": pdf.to_string_lossy(), "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::editing(&std::fs::read(&pdf).unwrap()).is_some_and(|e| e.intact)); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&pdf))); + let original = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pDFCropToBox: PDFBoxType.PDFMEDIABOX}});", quoted(&pdf))); + let cropped = s.active().unwrap().doc.artboards[0].rect; + assert!(cropped.width() > original.width() && cropped.height() > original.height()); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_document_open_rejects_files_over_the_read_limit() { + let base = folder("openreadlimit"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let file = dir.join("large.svg"); + std::fs::write(&file, b"").unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file))); + let count = s.documents().len(); + std::fs::OpenOptions::new().write(true).open(&file).unwrap().set_len(crate::cmd::fileio::SCRIPT_OPEN_MAX_BYTES as u64 + 1).unwrap(); + let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file))); + assert!(e.contains(crate::cmd::fileio::SCRIPT_OPEN_TOO_LARGE), "{e}"); + assert_eq!(s.documents().len(), count); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn pdf_open_options_reject_other_detected_formats() { + let base = folder("pdfoptionsformat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let native = dir.join("native.pdf"); + s.execute("file.saveAs", &json!({"path": native.to_string_lossy(), "format": "vectorcraft"})).unwrap(); + let svg = dir.join("drawing.pdf"); + std::fs::write(&svg, b"").unwrap(); + let count = s.documents().len(); + let uid = s.active().unwrap().uid; + for file in [&native, &svg] { + for options in ["{pageToOpen: 2}", "{pDFCropToBox: PDFBoxType.PDFMEDIABOX}"] { + let script = format!("Folder.userData; app.open(new File({}), undefined, {options});", quoted(file)); + let e = failure(&mut s, &base, &script); + assert!(e.contains("PDF open options require a PDF file"), "{e}"); + assert_eq!(s.documents().len(), count); + assert_eq!(s.active().unwrap().uid, uid); + } + } + let pdf = dir.join("actual.svg"); + s.execute("file.saveCopy", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap(); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 1}});", quoted(&pdf))); + assert_eq!(s.documents().len(), count + 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_document_open_treats_null_pdf_options_as_omitted() { + let base = folder("nullpdfdefaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({})).unwrap(); + for extension in ["svg", "vectorcraft"] { + let file = dir.join(format!("drawing.{extension}")); + s.execute("file.saveAs", &json!({"path": file.to_string_lossy()})).unwrap(); + for options in ["page: null", "cropTo: null", "page: null, cropTo: null"] { + let count = s.documents().len(); + logged(&mut s, &base, &format!("Folder.userData; vc.run('document.open', {{path: {}, {options}}});", quoted(&file))); + assert_eq!(s.documents().len(), count + 1, "{extension}: {options}"); + assert_eq!(s.active().unwrap().doc.artboards.len(), 1); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn explicit_null_options_do_not_save_export_open_or_close() { + let base = folder("nulloptions"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let file = dir.join("existing.svg"); + let original = b""; + std::fs::write(&file, original).unwrap(); + let f = format!("new File({})", quoted(&file)); + for call in [ + format!("app.activeDocument.saveAs({f}, null);"), + format!("app.activeDocument.exportFile({f}, ExportType.SVG, null);"), + format!("app.open({f}, null);"), + format!("app.open({f}, undefined, null);"), + "app.activeDocument.close(null);".into(), + ] { + let e = failure(&mut s, &base, &format!("Folder.userData; {call}")); + assert!(e.contains("TypeError"), "{call}: {e}"); + assert_eq!(std::fs::read(&file).unwrap(), original, "{call}"); + assert_eq!(s.documents().len(), 1, "{call}"); + assert!(!s.active().unwrap().is_dirty(), "{call}"); + } + logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs({f}, undefined);")); + assert_ne!(std::fs::read(&file).unwrap(), original); + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(undefined);"); + assert!(s.documents().is_empty()); + let _ = std::fs::remove_dir_all(base); +} + /// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its /// changes, and `close` with `SaveOptions.DONOTSAVECHANGES` closes it. #[test] @@ -765,6 +966,109 @@ fn closing_with_save_changes_refuses_a_save_of_some_artboards() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() { + let base = folder("closefullrange"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for (name, range, boards) in [("one", "1", 1), ("two", "1-2", 2)] { + let file = dir.join(format!("{name}.pdf")); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": boards})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.activeDocument, o = new PDFSaveOptions(); o.artboardRange = '{range}';\n\ + d.saveAs(new File({}), o);", + quoted(&file), + ), + ); + 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()); + assert_ne!(std::fs::read(&file).unwrap(), before); + } + s.execute("file.new", &json!({})).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PDFSaveOptions(); o.artboardRange = '1'; app.activeDocument.saveAs(new File({}), o);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});", + quoted(&dir.join("grown.pdf")), + ), + ); + let before = std::fs::read(dir.join("grown.pdf")).unwrap(); + let e = failure(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(e.contains("some of its artboards"), "{e}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(std::fs::read(dir.join("grown.pdf")).unwrap(), before); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { + let base = folder("closesvgboards"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for extension in ["svg", "svgz"] { + for preserve in [false, true] { + let file = dir.join(format!("drawing-{preserve}.{extension}")); + let path = quoted(&file); + let save = if preserve { + format!("vc.run('file.saveAs', {{path: {path}, preserveEditing: true}});") + } else { + format!("d.saveAs(new File({path}));") + }; + logged(&mut s, &base, &format!("Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 100, 50); {save}")); + let before = std::fs::read(&file).unwrap(); + logged(&mut s, &base, "Folder.userData; vc.run('artboard.new', {x: 300, y: 0, width: 60, height: 80});"); + let uid = s.active().unwrap().uid; + if preserve { + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(s.documents().is_empty()); + assert_ne!(std::fs::read(&file).unwrap(), before); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2); + } else { + let e = failure(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);"); + assert!(e.contains("some of its artboards"), "{extension}: {e}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().uid, uid); + assert_eq!(s.active().unwrap().doc.artboards.len(), 2); + assert!(s.active().unwrap().is_dirty()); + assert_eq!(std::fs::read(&file).unwrap(), before); + } + logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn document_path_reflection_describes_folders_and_unsaved_strings() { + let base = folder("pathreflection"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add();\n\ + vc.log([d.reflect.find('path').dataType, d.path === '']);\n\ + d.saveAs(new File({})); vc.log([d.reflect.find('path').dataType, d.path instanceof Folder ? 'Folder' : typeof d.path]);\n\ + vc.log([d.path instanceof Folder, d.path.fsName]);", + quoted(&dir.join("saved.svg")), + ), + ); + assert_eq!(out, json!([["Folder|string", true], ["Folder|string", "Folder"], [true, dir.to_string_lossy()]])); + let _ = std::fs::remove_dir_all(base); +} + /// Setting `Document.saved` records the document's saved state without saving it: `true` lets /// `close()` close a document with edits, and `false` makes an untouched one ask. #[test] @@ -794,6 +1098,24 @@ fn setting_saved_records_the_saved_state() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn unchanged_saved_assignments_do_not_record_commands() { + let base = folder("savednoop"); + let mut s = session(&base); + let out = logged( + &mut s, + &base, + "var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + d.saved = d.saved; d.saved = true; vc.log(d.saved);\n\ + d.saved = false; d.saved = d.saved; d.saved = false; vc.log(d.saved);\n\ + d.saved = true; d.saved = d.saved; vc.log(d.saved);", + ); + assert_eq!(out, json!([true, false, true])); + let changes: Vec<_> = s.journal.iter().filter(|(id, _)| id == "document.setSaved").map(|(_, p)| p["saved"].clone()).collect(); + assert_eq!(changes, [json!(false), json!(true)]); + let _ = std::fs::remove_dir_all(base); +} + /// With automation read roots that leave out the document's file, `fullName` and `path` throw /// instead of naming another file. #[test] @@ -831,6 +1153,35 @@ fn full_name_and_path_leave_out_a_file_outside_the_read_roots() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn implicit_multifile_save_redacts_preflight_refusals_before_writing() { + let base = folder("savepreflight"); + let mut s = session(&base); + let hidden = base.join("private-save-directory"); + std::fs::create_dir_all(&hidden).unwrap(); + let path = hidden.join("drawing.vectorcraft"); + s.execute("file.new", &json!({"artboards": 2})).unwrap(); + let saved = s.execute("document.save", &json!({"path": path.to_string_lossy(), "separateArtboards": true})).unwrap(); + let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| PathBuf::from(p.as_str().unwrap())).collect(); + assert!(files.len() > 1); + let before: Vec<_> = files.iter().map(|p| std::fs::read(p).unwrap()).collect(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap(); + let main = base.join("main"); + let roots = crate::file_access::AutomationRoots::new(&[&main], &[&main]).unwrap().unwrap(); + let e = crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({}))).unwrap_err().to_string(); + assert!(e.contains("automation path rejected"), "{e}"); + assert!(!e.contains("private-save-directory"), "{e}"); + assert!(!e.contains(path.to_string_lossy().as_ref()), "{e}"); + assert!(s.active().unwrap().is_dirty()); + for (file, bytes) in files.iter().zip(before) { + assert_eq!(std::fs::read(file).unwrap(), bytes); + } + let explicit = + crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({"path": path.to_string_lossy()}))).unwrap_err().to_string(); + assert!(explicit.contains(path.to_string_lossy().as_ref()), "{explicit}"); + let _ = std::fs::remove_dir_all(base); +} + /// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name /// that is not a preset either way is refused. #[test] diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 11a42a6f90..1327e57208 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -88,6 +88,39 @@ fn path_of(p: &std::path::Path) -> String { p.to_string_lossy().into_owned() } +#[test] +fn scripted_open_converts_importer_output_to_the_requested_color_space() { + let mut s = Session::new(); + install(&mut s, &tpl::returning(&tpl::importer("test.scriptcolorspace", r#"["tscmyk"]"#, "{}"), RECT)); + let dir = tmp_dir("scriptcolorspace"); + s.attach_script_data(dir.join("settings/Script Data")); + let file = dir.join("drawing.tscmyk"); + 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 (argument, mode) in [ + ("", vectorcraft_doc::ColorMode::Rgb), + (", DocumentColorSpace.CMYK", vectorcraft_doc::ColorMode::Cmyk), + (", DocumentColorSpace.RGB", vectorcraft_doc::ColorMode::Rgb), + ] { + std::fs::write(&script, format!("Folder.userData; var d = app.open(new File({path}){argument}); vc.log(d.documentColorSpace);")).unwrap(); + let count = s.documents().len(); + let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})).unwrap(); + assert_eq!(s.documents().len(), count + 1); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.color_mode, mode, "{argument}: {out}"); + let color = doc.layers[0].children().unwrap()[0].appearance.fill_paint().color().unwrap(); + if mode == vectorcraft_doc::ColorMode::Cmyk { + assert!(matches!(color, vectorcraft_color::Color::Cmyk { .. }), "{color:?}"); + assert_eq!(out["log"], json!(["DocumentColorSpace.CMYK"])); + } else { + assert!(matches!(color, vectorcraft_color::Color::Rgb { .. }), "{color:?}"); + assert_eq!(out["log"], json!(["DocumentColorSpace.RGB"])); + } + } + 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(); diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 7a596f5633..4ad90a30a8 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -1474,10 +1474,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// Whether `name` is declared in a function body this token is inside (`var name`, `function + /// Whether `name` is declared in the innermost function body (`var name`, `function /// name`, a parameter). fn declared_in_body(&self, name: &str) -> bool { - self.scopes.iter().any(|s| s.saved.get(name).is_some_and(|v| v.local)) + self.scopes.last().is_some_and(|s| s.saved.get(name).is_some_and(|v| v.local)) } /// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 9a99338da4..bf808469e5 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -208,7 +208,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) { self.acc.feature(FeatureId::FilePlaces, line); } - if n == catalog::SAVE_CHANGES { + if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) { self.save_changes(line); } if n == catalog::ON_DRAW { @@ -283,6 +283,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { "]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => { let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default(); self.setter(&name, h2, h3, line); + if name == catalog::SAVE_CHANGES + && word(h2, catalog::SAVE_OPTIONS) + && !member_mark(h3) + && !self.own_names.contains(catalog::SAVE_OPTIONS) + { + self.save_changes(line); + } } // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. "[" => self.index_receiver = self.writer_bits(h0, h1), @@ -364,7 +371,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// 0 for anything else. A receiver the check does not follow may be a document. fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { match receiver { - Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), + Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), _ => 0, } } @@ -447,11 +454,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if t.text.contains(catalog::ACTION_TEXT) { self.acc.feature(FeatureId::Actions, line); } - // `SaveOptions['SAVECHANGES']`, or the value written as the string `"SaveOptions.SAVECHANGES"`. + // The value written as the string `"SaveOptions.SAVECHANGES"`. let value = unquote(t.text, 32); - if value == catalog::SAVE_CHANGES - || value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) - { + if value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) { self.save_changes(line); } let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!==")); diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b609217756..236bede7ce 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -573,6 +573,19 @@ fn export_variables_in_brackets_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +#[test] +fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() { + for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] { + let r = report(&format!( + "var local = {{exportVariables: function () {{}}, saveAs: function () {{}}, exportFile: function () {{}}}};\n\ + eval('local = app.activeDocument');\n{call}\n" + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]), "{call}"); + let written = r.outside.iter().find(|o| o.id == "filesWritten"); + assert_eq!(written.map(|o| o.lines.as_slice()), Some(&[3][..]), "{call}"); + } +} + /// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in /// brackets, as a string or through a variable; closing without it, and the other save options, /// write nothing. @@ -592,6 +605,24 @@ fn closing_with_save_changes_writes_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 7][..])]); } +#[test] +fn unrelated_save_changes_properties_and_strings_do_not_report_writes() { + let r = report(concat!( + "var a = other.SAVECHANGES;\n", + "var b = other['SAVECHANGES'];\n", + "app.activeDocument.close('SAVECHANGES');\n", + "var c = holder.SaveOptions.SAVECHANGES;\n", + "var d = holder.SaveOptions['SAVECHANGES'];\n", + "var e = 'SAVECHANGES';\n", + "var key = SaveOptions['SAVECHANGES' + suffix];\n", + "var f = SaveOptions.SAVECHANGES;\n", + "var g = SaveOptions['SAVECHANGES'];\n", + "var h = 'SaveOptions.SAVECHANGES';\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[8, 9, 10][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[8, 9, 10][..])]); +} + /// `saveAs` and `exportFile` called with their names as string literals in brackets write the file /// too; reading the method without calling it does not. #[test] @@ -714,6 +745,27 @@ fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); } +#[test] +fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() { + let r = report(concat!( + "var f = new File(p);\n", + "function outer() {\n", + " function choose() { d = app.activeDocument; }\n", + " var d = {saveAs: function () {}};\n", + " choose(); d.saveAs(f);\n", + " function bump() { e++; }\n", + " var e = {saveAs: function () {}};\n", + " bump(); e.saveAs(f);\n", + " function own() { var g; g = app.activeDocument; }\n", + " var g = {saveAs: function () {}};\n", + " own(); g.saveAs(f);\n", + "}\n", + "outer();\n", + )); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[5, 8][..])]); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..])); +} + /// Assigning a property of `this`, the global object in the global code and in a function called /// without a receiver, may give the global variable of that name another value, before or after /// its literal. diff --git a/docs/mcp.md b/docs/mcp.md index a9542a7435..7e98a72bbd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3003,6 +3003,8 @@ other files through `$`: 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 path's fill, are not defined yet and read as `undefined`. - `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file. + When the format is selected by a `.vctemplate` path, `saveAs` writes a template copy and leaves the document's + file and saved state unchanged. `Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is. `app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/). @@ -3027,7 +3029,10 @@ other files through `$`: `coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and `includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with - `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of + `pageToOpen` and `pDFCropToBox`. These options require PDF content, including PDF-compatible `.ai` and `.ait` files. + `app.open` rejects a file over 128 MiB before reading it. + Optional arguments to `saveAs`, `exportFile`, `app.open` and `close` use defaults when omitted or `undefined`; + explicit `null` throws a type error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, `EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. @@ -3059,13 +3064,15 @@ other files through `$`: artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw - `Script file access denied`. Setting `saved` runs `document.setSaved`: `true` records the document as saved + `Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an - undo step. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; + undo step. Assigning its current value runs no command and adds no journal entry. + With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`; `SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document was last saved in and after the same write-access check of the path as `saveAs`, and throws an error and leaves the document open when the document has no file (a converted or recovered document included) or when - its last save named some of its artboards, without writing anything; and + 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`. `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. - `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type From e3077d3c1f4e6a34a4237e7233ef40d033bd668b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:18:39 -0800 Subject: [PATCH 16/20] Script check: test the computed-key case of an own saveAs in its own script A computed key such as c[k] = w makes the check unsure for the whole script, so since the last commit every saveAs in that script counts as a write, the ones before the computed key included. The test put that case in the same script as the others, so the own saveAs calls it expected to write nothing were reported. The computed-key case now has its own script and assertion, and the other cases keep theirs. --- crates/scriptcheck/src/tests.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 61474e854f..0493014da0 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -671,18 +671,16 @@ fn the_scripts_own_save_as_writes_no_file() { fn a_changed_or_shared_own_save_as_writes_a_file() { let r = report(concat!( "var f = new File(p);\n", - "var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", "var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", "a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n", "a.saveAs = app.activeDocument.saveAs;\n", "b['saveAs'] = w;\n", - "c[k] = w;\n", "delete d.saveAs;\n", "var h = e;\n", "use(g);\n", "a.saveAs(f);\n", "b.saveAs(f);\n", - "c.saveAs(f);\n", "d.saveAs(f);\n", "e.saveAs(f);\n", "g['saveAs'](f);\n", @@ -693,7 +691,11 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { "q['saveAs'](f);\n", "s.saveAs(f);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 14, 16, 17, 19, 20][..])); + // A computed key may name any variable, so every `saveAs` in the script may write, the ones + // before the computed key included. + let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc.saveAs(f);\nc[k] = w;\nc.saveAs(f);\n"); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..])); } /// Only a `var` statement directly in a function body or the global code that gives its first name From f99ef023ad76a2a1da0e76a7abd3706119e60b69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:49:37 -0800 Subject: [PATCH 17/20] Scripts: close checks the artboards the saved file keeps; saves report warnings Document.close(SaveOptions.SAVECHANGES) now judges artboard loss by the file the save writes. A PDF last saved with useArtboards: false is refused, since it holds one page of the art's bounds. A native or .ai file saved with separateArtboards is saved and closed whatever its range names, since the range picks only the separate files; a version 7 .ai file keeps the range check. Document.saveAs, Document.exportFile, app.open and the save that close(SaveOptions.SAVECHANGES) runs write each warning of their command to the console after the method's name (for example "saveAs: SVG keeps 1 of the document's 2 artboards ..."). Script Check reports a file write for a saveAs or exportFile call on the script's own object when the variable is assigned in a loop around the call, since a later iteration may run the call on a document. Loop bodies without braces follow if, else and line breaks, and a variable of the same name that a function declares is kept apart. A test shows that a waiting point change counts as unsaved for Document.saved and close(). --- crates/engine/src/cmd/fileio.rs | 6 + crates/engine/src/script/dom/save_open.rs | 33 ++- crates/engine/src/tests/script_save_open.rs | 73 ++++++ crates/scriptcheck/src/analyze.rs | 6 +- crates/scriptcheck/src/analyze/declared.rs | 263 +++++++++++++++++++- crates/scriptcheck/src/analyze/features.rs | 23 +- crates/scriptcheck/src/tests.rs | 63 +++++ docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 9 files changed, 458 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 51d7590f35..21424f7bdc 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -126,6 +126,12 @@ pub use screens::{ preset_rows as screen_preset_rows, }; pub(crate) use svg::lost_artboards_warning as svg_lost_artboards_warning; + +/// 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. +pub(crate) fn saves_legacy_ai(format: &str, p: &serde_json::Value) -> bool { + format == "ai" && formats::format(format).is_none_or(|f| legacy_ai::wanted("file.saveAs", f, p).unwrap_or(true)) +} pub use svg::options_map as svg_options; /// Atomic file writes (a temporary file renamed over the target: a failed write never damages the /// file it replaces), for the apps' own writers too. diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index bf49aae883..9106158e60 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -665,6 +665,17 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer { r } +/// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s +/// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or +/// a linked image an open could not read. → the command's answer. +fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { + let (answer, value) = super::super::command_value(h, id, p)?; + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } + Ok(answer) +} + /// The path to give a command for the real path `real`. fn plain(real: std::path::PathBuf) -> String { crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() @@ -728,7 +739,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -782,7 +793,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -831,7 +842,7 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { } h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; p.insert("path".into(), json!(plain(std::path::PathBuf::from(path)))); - let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?; + let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { ("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()), @@ -925,12 +936,24 @@ const NO_FILE_TO_SAVE: &str = const SAVES_SOME_ARTBOARDS: &str = "the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES"; -/// Whether saving `st` with its remembered options would omit artboards. +/// Whether the file that saving `st` with its remembered options writes would omit artboards. A +/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai` +/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its +/// `range` names only the separate files. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { 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() { 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) + { + return false; + } let count = st.doc.artboards.len(); let pick = serde_json::from_value::(options); match pick.map_err(|e| e.to_string()).and_then(|p| p.resolve(count)) { @@ -969,7 +992,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; let p = json!({"path": plain(real), "format": format}); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &p)))?; + exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8c09da874c..da96519b6e 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -1010,6 +1010,42 @@ fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() { let _ = std::fs::remove_dir_all(base); } +/// The artboard check of `close(SaveOptions.SAVECHANGES)` follows the file the save writes: a PDF +/// last saved without its artboards (`useArtboards: false`) is refused, and a `.ai` file whose +/// `range` names only the separate artboard files keeps every artboard and is saved. +#[test] +fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { + let base = folder("closeencoder"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let pdf = dir.join("art.pdf"); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + s.execute("document.save", &json!({"path": pdf.to_string_lossy(), "useArtboards": false})).unwrap(); + let before = std::fs::read(&pdf).unwrap(); + let e = failure( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(e.contains("some of its artboards"), "{e}"); + assert_eq!(std::fs::read(&pdf).unwrap(), before, "the PDF is left as it was"); + let mut s = session(&base); + data_folder(&mut s, &base); + let ai = dir.join("all.ai"); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + s.execute("document.save", &json!({"path": ai.to_string_lossy(), "separateArtboards": true, "range": "2"})).unwrap(); + let before = std::fs::read(&ai).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(), "the .ai file keeps every artboard, so it closes"); + assert_ne!(std::fs::read(&ai).unwrap(), before, "and the change is saved"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { let base = folder("closesvgboards"); @@ -1098,6 +1134,43 @@ fn setting_saved_records_the_saved_state() { let _ = std::fs::remove_dir_all(base); } +/// The warnings of a save go to the console after the method's name. +#[test] +fn save_as_writes_its_warnings_to_the_console() { + let base = folder("warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap(); + let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap(); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A point change that waits to be written counts as an unsaved change for `saved` and `close`. +#[test] +fn waiting_point_changes_count_as_unsaved_changes() { + let base = folder("pendingpoints"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/a.svg'));\n\ + d.pathItems[0].pathPoints[0].anchor = [1, 2]; vc.log(d.saved);\n\ + d.saved = true; d.pathItems[0].pathPoints[0].anchor = [3, 4];\n\ + var e = ''; try {{ d.close(); }} catch (x) {{ e = String(x); }} vc.log([e, app.documents.length]);" + ), + ); + assert_eq!(out[0], json!(false), "a waiting point change is unsaved"); + assert!(out[1][0].as_str().unwrap().contains("unsaved changes"), "{}", out[1]); + assert_eq!(out[1][1], json!(1), "close() keeps the document open"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn unchanged_saved_assignments_do_not_record_commands() { let base = folder("savednoop"); diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 869938027f..a66b20ef06 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -531,6 +531,8 @@ impl Chain { /// member chain or a File object assigned in it to an outer name stays. struct Scope { depth: usize, + /// The offset of the body's `{` in the text, which [`Declared::looped`] names it by. + start: usize, saved: HashMap, /// The bracket depth of the `var` statement the body is in, if any: it goes on when the body /// closes. @@ -1234,7 +1236,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if body { let params = self.params.take().map(|(_, names)| names).unwrap_or_default(); if self.scopes.len() < self.acc.limits.nesting { - self.scopes.push(Scope { depth: self.depth(), saved: HashMap::new(), var_depth: self.var_depth.take() }); + self.scopes.push(Scope { depth: self.depth(), start: t.start, saved: HashMap::new(), var_depth: self.var_depth.take() }); // The parameters are the body's own names, and so are the names it declares. for name in params { self.acc.steps = self.acc.steps.saturating_add(1); @@ -1454,11 +1456,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins /// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t` /// closes a function body, so a literal given to the body's own variable stays inside the body. + /// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods. fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) && !self.later_full && !self.later.contains(&name) + && !self.declared.looped_full && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 48f071d2ac..9079c352ef 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -1,6 +1,6 @@ //! The names declared, read before the analysis. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word}; @@ -14,6 +14,10 @@ const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_E /// The property a function reaches `Function` through. const CONSTRUCTOR: &str = "constructor"; +/// The statements whose parentheses the rest of the statement follows, so a line break after them +/// does not end a loop's body without braces. +const HEADS: &[&str] = &["if", "while", "for", "with", "switch"]; + /// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in /// brackets that spells a longer one sets [`Declared::unsure`]. const PROPERTY_CHARS: usize = 256; @@ -36,6 +40,16 @@ pub(crate) struct Declared<'s> { /// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be /// the global object, so a variable of that name may get a value the analysis doesn't read. pub(super) rebound: HashSet, + /// The variables assigned inside a loop, its parentheses included (`name = …`), each by the + /// offset of the `{` of the function body that declares it (`None`: the global code's), with the + /// outermost loops that assign it, entries of `loop_spans`. + pub(super) looped: HashMap<(Option, &'s str), Vec>, + /// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at + /// the end of the text). + pub(super) loop_spans: Vec<(usize, usize)>, + /// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any + /// variable may be assigned in a loop. + pub(super) looped_full: bool, /// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or /// a `constructor` property used, a property read, called or assigned whose name in brackets is /// not one string or number literal, which may be a variable's name on the global object @@ -48,12 +62,14 @@ pub(crate) struct Declared<'s> { /// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in /// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement -/// the body is in, which goes on when the body closes. +/// the body is in, which goes on when the body closes, and the names assigned in a loop inside it +/// so far, each with its loops ([`Declared::looped`]). struct Body<'s> { depth: usize, index: usize, names: HashSet<&'s str>, var_depth: Option, + looped: HashMap<&'s str, Vec>, } /// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in @@ -87,9 +103,43 @@ struct Declarations<'s, 'a, 'l> { untracked: Option, /// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`]. keys: Vec, + /// The loops being read, the innermost last, up to [`crate::Limits::nesting`]. + loops: Vec, out: Declared<'s>, } +/// A loop [`Declarations`] is reading: the bracket depth of its keyword, how far it has been read, +/// and, for a body without braces, whether the last `{` at that depth opened a block (not an object +/// literal), whether an `if`, `while`, `for` or `with` at that depth waits for its `)`, and whether +/// the last token was that `)`. +struct Loop { + depth: usize, + stage: Stage, + block: bool, + head: bool, + after_head: bool, + /// The loop starts with `do` and has a trailing condition. + do_loop: bool, +} + +/// How far a [`Loop`] has been read. +#[derive(Clone, Copy, PartialEq)] +enum Stage { + /// The parentheses after `for` or `while`. + Head, + /// The parentheses after the `while` of a `do` loop. + DoHead, + /// The body's first token is next. + Start, + /// A body in braces. + Block, + /// 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. + Tail, +} + /// What `src` declares ([`Declared`]), read in one pass over its tokens. pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { let mut lexer = Lexer::new(src, acc.limits.nesting); @@ -103,6 +153,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { bodies: vec![], untracked: None, keys: vec![], + loops: vec![], out: Declared::default(), }; let mut breaks = LineBreaks::default(); @@ -113,6 +164,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { Read::Token(sig) => d.token(sig), } } + // A body the file does not close keeps its names assigned in a loop as well. + while let Some(body) = d.bodies.pop() { + d.settle_looped(body); + } let mut out = d.out; out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); @@ -138,12 +193,22 @@ impl<'s> Declarations<'s, '_, '_> { if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) { self.var_depth = None; } + self.loop_start(&t); if t.kind == T::Punct { self.bracket(&t); } else if t.kind == T::Ident { self.declaration(&t); } let depth = self.depth(); + self.loop_end(&t, depth); + if t.is("=") + && !self.loops.is_empty() + && !member_mark(h1) + && !is(h1, "@") + && let Some(name) = h0.filter(|s| s.kind == T::Ident) + { + self.looped(name.text); + } if let Some(after_new) = self.assign.take() { if t.word("new") && !after_new { self.assign = Some(true); @@ -167,6 +232,191 @@ impl<'s> Declarations<'s, '_, '_> { self.h = [Some(t), h0, h1]; } + /// `t`, a token before the brackets are followed past it: the body of the innermost loop starts + /// 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 depth = self.depth(); + while let Some(l) = self.loops.last_mut() { + let after_head = std::mem::take(&mut l.after_head); + match l.stage { + Stage::Start => { + l.stage = if t.is("{") { Stage::Block } else { Stage::Statement }; + l.head = HEADS.iter().any(|w| t.word(w)) && !member_mark(h0); + break; + } + // A line break ends a body of one statement where the tokens on either side of it + // 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") => + { + l.stage = Stage::Tail; + } + Stage::Statement => { + if depth == l.depth { + if t.is("{") { + l.block = t.stmt || after_head || word(h0, "else"); + } else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) { + l.head = true; + } + } + break; + } + Stage::Tail if l.do_loop && t.word("while") => { + l.stage = Stage::DoHead; + return; + } + Stage::Tail if t.word("else") => { + l.stage = Stage::Statement; + break; + } + Stage::Tail => { + 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() + && outer.stage == Stage::Statement + && outer.depth == depth + { + outer.stage = Stage::Tail; + } + } + _ => break, + } + } + let stage = if (t.word("for") || t.word("while")) && !member_mark(h0) { + Stage::Head + } else if t.word("do") && !member_mark(h0) { + Stage::Start + } else { + return; + }; + if self.loops.len() >= self.acc.limits.nesting || (self.loops.is_empty() && !self.acc.room(self.out.loop_spans.len())) { + self.out.looped_full = true; + } else { + if self.loops.is_empty() { + self.out.loop_spans.push((t.start, usize::MAX)); + } + self.loops.push(Loop { depth, stage, block: false, head: false, after_head: false, do_loop: t.word("do") }); + } + } + + /// Ends the innermost loop at offset `at`, which ends the outermost one in + /// [`Declared::loop_spans`]. + fn pop_loop(&mut self, at: usize) { + self.loops.pop(); + if self.loops.is_empty() + && let Some((_, end)) = self.out.loop_spans.last_mut() + { + *end = at; + } + } + + /// `t`, after the brackets are followed past it to `depth`: the parentheses of a loop end at the + /// `)` back at its depth, and a body in braces at the `}` back at it. A body of one statement + /// reaches its end ([`Stage::Tail`]) at a `;` at the loop's depth, at a `}` there that closes a + /// block, or with a loop that is that statement. A bracket closing below a loop's depth ends it. + fn loop_end(&mut self, t: &Sig<'s>, depth: usize) { + let mut inner = false; + while let Some(l) = self.loops.last_mut() { + let ended = depth < l.depth + || match l.stage { + Stage::Head => { + if t.is(")") && depth == l.depth { + l.stage = Stage::Start; + } + false + } + Stage::DoHead => t.is(")") && depth == l.depth, + Stage::Block => { + if t.is("}") && depth == l.depth && l.do_loop { + l.stage = Stage::Tail; + false + } else { + t.is("}") && depth == l.depth + } + } + Stage::Statement => { + if depth == l.depth { + if t.is(";") || (t.is("}") && l.block) || inner { + l.stage = Stage::Tail; + } else if t.is(")") && l.head { + l.head = false; + l.after_head = true; + } + } + false + } + Stage::Start | Stage::Tail => false, + }; + if !ended { + break; + } + self.pop_loop(t.start); + inner = true; + } + } + + /// `name` is assigned in the loops being read: kept with the outermost one for the innermost + /// function body that declares it when that body closes ([`Self::settle_looped`]), or for the + /// global code. + fn looped(&mut self, name: &'s str) { + let id = self.out.loop_spans.len().saturating_sub(1); + match self.bodies.last_mut() { + Some(body) if body.looped.contains_key(name) || self.acc.room(body.looped.len()) => { + let ids = body.looped.entry(name).or_default(); + if !ids.contains(&id) { + ids.push(id); + } + } + Some(_) => self.out.looped_full = true, + None => self.keep_looped(None, name, vec![id]), + } + } + + /// The names assigned in a loop inside `body`, which is closing: the body's own are kept for it, + /// and the others go to the body around it, or to the global code. + fn settle_looped(&mut self, body: Body<'s>) { + let start = self.out.bodies.get(body.index).map(|(at, _)| *at); + for (name, ids) in body.looped { + if body.names.contains(name) { + self.keep_looped(start, name, ids); + } else if let Some(outer) = self.bodies.last_mut() { + if outer.looped.contains_key(name) || self.acc.room(outer.looped.len()) { + let kept = outer.looped.entry(name).or_default(); + for id in ids { + if !kept.contains(&id) { + kept.push(id); + } + } + } else { + self.out.looped_full = true; + } + } else { + self.keep_looped(None, name, ids); + } + } + } + + /// Keeps `name` of `body` as assigned in outermost loops `ids`. + fn keep_looped(&mut self, body: Option, name: &'s str, ids: Vec) { + let len = self.out.looped.len(); + match self.out.looped.get_mut(&(body, name)) { + Some(kept) => { + for id in ids { + if !kept.contains(&id) { + kept.push(id); + } + } + } + None if self.acc.room(len) => { + self.out.looped.insert((body, name), ids); + } + None => self.out.looped_full = true, + } + } + /// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and /// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read. fn unread_binding(&mut self, t: &Sig<'s>) { @@ -234,7 +484,13 @@ impl<'s> Declarations<'s, '_, '_> { if self.bodies.len() < self.acc.limits.nesting { let index = self.out.bodies.len(); self.out.bodies.push((t.start, vec![])); - self.bodies.push(Body { depth: self.depth(), index, names: HashSet::new(), var_depth: self.var_depth.take() }); + self.bodies.push(Body { + depth: self.depth(), + index, + names: HashSet::new(), + var_depth: self.var_depth.take(), + looped: HashMap::new(), + }); } else if self.untracked.is_none() { self.untracked = Some(self.depth()); } @@ -261,6 +517,7 @@ impl<'s> Declarations<'s, '_, '_> { } while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) { self.var_depth = body.var_depth; + self.settle_looped(body); } if self.untracked.is_some_and(|d| depth < d) { self.untracked = None; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index bf808469e5..8b6b4c5f1d 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -292,8 +292,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. - "[" => self.index_receiver = self.writer_bits(h0, h1), - "(" => self.call(line), + "[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)), + "(" => self.call(t, line), // `Name.prototype["+"] = …` defines an operator. "=" => { let operator = || h1.filter(|s| s.kind == T::Str).is_some_and(|s| catalog::OPERATORS.contains(&unquote(s.text, 4).as_str())); @@ -308,7 +308,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// `(` after a name: a call. - fn call(&mut self, line: Option) { + fn call(&mut self, t: &Sig<'s>, line: Option) { let [h0, h1, h2, h3] = self.h; // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") @@ -342,7 +342,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } 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)) - || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n)) + || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n)) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -369,9 +369,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The methods that `receiver`, which `before` comes before, defines when it is a variable holding /// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name; /// 0 for anything else. A receiver the check does not follow may be a document. - fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { + /// At call offset `at`, a variable assigned in a loop containing that offset may be a document. + fn writer_bits(&self, receiver: Option>, before: Option>, at: Option) -> u8 { match receiver { - Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), + Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => { + let looped = at.is_some_and(|at| { + self.declared.looped_full + || self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| { + ids.iter().any(|id| self.declared.loop_spans.get(*id).is_some_and(|(start, end)| *start <= at && at < *end)) + }) + }); + if looped { 0 } else { self.writers.get(r.text).copied().unwrap_or(0) } + } _ => 0, } } @@ -400,7 +409,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.reassigned_later(&name); } } - let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); + let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text); let escaped = if word(h0, "delete") { // `delete local…` writer(Some(*t), h0) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 0493014da0..a580c3d311 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -698,6 +698,69 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..])); } +/// A variable assigned in a loop may hold a document when a later iteration calls its `saveAs`, +/// before the assignment in the text: the call writes a file. One assigned only after a loop does +/// not. +#[test] +fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n", + "var d = {saveAs: function () {}};\n", + "for (var i = 0; i < 2; i++) { a.saveAs(f); a = app.activeDocument; }\n", + "while (n--) b.saveAs(f), b = app.activeDocument;\n", + "do { c.saveAs(f); } while ((c = next()));\n", + "for (;;) { d.saveAs(f); break; }\n", + "d = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 6][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[4, 5, 6][..])]); + // The `else` of a body without braces is in the loop; a statement after a line break that ends + // such a body is not, and neither is a variable of the same name that a function declares. + let r = report(concat!( + "var f = new File(p);\n", + "var e = {saveAs: function () {}}; var g = {saveAs: function () {}}; var h = {saveAs: function () {}};\n", + "while (n--) if (n) e.saveAs(f); else e = app.activeDocument;\n", + "while (n--) g.saveAs(f), n\n", + "g = app.activeDocument\n", + "function k() { var h; for (;;) h = app.activeDocument; }\n", + "h.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + // An object literal's `}` does not end a body without braces, a call's `)` before a line break + // does, and a literal given after the last loop that assigns its variable is the script's own. + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "while (n--) a.saveAs(f), t = {}, a = app.activeDocument;\n", + "b.saveAs(f);\n", + "while (n--) tick()\n", + "b = app.activeDocument\n", + "for (;;) { c = app.activeDocument; }\n", + "var c = {saveAs: function () {}};\n", + "c.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..])); + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}};\n", + "while (n--) if (n)\n", + " a.saveAs(f), a = app.activeDocument;\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "a.saveAs(f); b['saveAs'](f);\n", + "while (n--) { a.saveAs(f); a = app.activeDocument; }\n", + "while (n--) { b['saveAs'](f); b = app.activeDocument; }\n", + "var a = {saveAs: function () {}};\n", + "a.saveAs(f);\n", + "while (n--) { a.saveAs(f); a = app.activeDocument; }\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..])); +} + /// 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 diff --git a/docs/mcp.md b/docs/mcp.md index 2fcb2dc34f..c073a93f02 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3168,9 +3168,13 @@ through `$`: was last saved in and after the same write-access check of the path as `saveAs`, and throws an error 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`. + 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. `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. + 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 + (`saveAs: …`). - `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 13d8c9200e..2ed9a978e8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1127,7 +1127,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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 key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. From 82d4ec4336627df6a4ae241f7c3e27eb6ef68b71 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:01:56 -0800 Subject: [PATCH 18/20] Scripts: explicit crop boxes, EPS close-with-save and writer receivers checked per call - document.open with an explicit PDFCROPBOX crop opens on the crop box of a file with editing data; the default keeps the trim box and bleed. - Closing with save changes keeps an EPS document's artboard range, since the EPS file holds the whole document. - The script checker treats a writer receiver captured from an outer scope as able to change before each call, and finds the loop that holds a call with a binary search instead of a scan of every loop. --- crates/engine/src/cmd/fileio/pdfimport.rs | 10 +++- crates/engine/src/script/dom/save_open.rs | 6 +- crates/engine/src/tests/script_save_open.rs | 65 +++++++++++++++++++++ crates/scriptcheck/src/analyze/declared.rs | 40 ++++++++++++- crates/scriptcheck/src/analyze/features.rs | 9 ++- crates/scriptcheck/src/tests.rs | 47 +++++++++++++++ 6 files changed, 170 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 8ffb3f8133..954a345ae0 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -22,6 +22,8 @@ pub struct LoadOptions { pub pages: Option, /// The box each page's artboard (or placed frame) gets. pub crop: CropTo, + /// Whether the options explicitly request the crop box. + pub explicit_crop_box: bool, /// The password of an encrypted PDF. pub password: Option, /// The colour mode the document opens in, its colours converted as Document Color Mode does @@ -67,6 +69,7 @@ impl Default for LoadOptions { Self { pages: None, crop: CropTo::default(), + explicit_crop_box: false, password: None, color_mode: None, grays: Grays::default(), @@ -147,6 +150,7 @@ impl LoadOptions { Ok(Self { pages, crop, + explicit_crop_box: crop == CropTo::Crop && crop_to.or(crop_alias).is_some(), password, color_mode, grays, @@ -173,14 +177,14 @@ impl LoadOptions { } /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible - /// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes, - /// its editor's artboards, with the bleed round them (its crop box takes the bleed in). + /// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default, + /// with the bleed around them. An explicit crop-box request uses its crop box. fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { None => None, Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?), }; - let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data(); + let is_ai = !self.explicit_crop_box && self.crop == CropTo::Crop && opened.has_illustrator_data(); Ok(ImportOptions { pages, crop: if is_ai { CropTo::Trim } else { self.crop }, diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 9106158e60..09c438040c 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -939,8 +939,12 @@ const SAVES_SOME_ARTBOARDS: &str = /// Whether the file that saving `st` with its remembered options writes would omit artboards. A /// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai` /// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its -/// `range` names only the separate files. +/// `range` names only the separate files. An EPS file embeds the whole document in its main file, +/// so its `artboardRange` never omits an artboard from what reopens. fn picks_artboards(st: &crate::doc_state::DocState) -> bool { + if st.format == "eps" { + 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() { return true; diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index da96519b6e..68183e8637 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -741,6 +741,34 @@ fn crop_only_options_apply_to_an_editable_pdf() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() { + let base = folder("explicitcropbox"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for extension in ["ai", "pdf"] { + let file = dir.join(format!("editable.{extension}")); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + s.execute( + "file.saveAs", + &json!({"path": file.to_string_lossy(), "format": "ai", "preserveEditing": true, + "bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}), + ) + .unwrap(); + assert!(vectorcraft_pdf::has_illustrator_data(&std::fs::read(&file).unwrap(), None)); + let path = quoted(&file); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + let default = s.active().unwrap().doc.artboards[0].rect; + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}), undefined, {{pDFCropToBox: PDFBoxType.PDFTRIMBOX}});")); + 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; + assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}"); + assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_document_open_rejects_files_over_the_read_limit() { let base = folder("openreadlimit"); @@ -1046,6 +1074,43 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() { + let base = folder("closeepsboards"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + for (name, range) in [("single", "2"), ("several", "1-2")] { + let file = dir.join(format!("{name}.eps")); + let path = quoted(&file); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 100, 50);\n\ + vc.run('artboard.new', {{x: 150, y: 0, width: 100, height: 50}});\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 100, height: 50}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 20, height: 20}});\n\ + var o = new EPSSaveOptions(); o.saveMultipleArtboards = true; o.artboardRange = '{range}';\n\ + d.saveAs(new File({path}), o);" + ), + ); + let before = std::fs::read(&file).unwrap(); + let nodes = s.active().unwrap().doc.node_count(); + logged( + &mut s, + &base, + "Folder.userData; vc.run('shape.rectangle', {x: 40, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);", + ); + assert!(s.documents().is_empty(), "{range}"); + assert_ne!(std::fs::read(&file).unwrap(), before, "{range}"); + logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));")); + assert_eq!(s.active().unwrap().doc.artboards.len(), 3, "{range}"); + assert!(s.active().unwrap().doc.node_count() > nodes, "{range}"); + logged(&mut s, &base, "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() { let base = folder("closesvgboards"); diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 9079c352ef..03ad43ab10 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -22,6 +22,33 @@ const HEADS: &[&str] = &["if", "while", "for", "with", "switch"]; /// brackets that spells a longer one sets [`Declared::unsure`]. const PROPERTY_CHARS: usize = 256; +#[cfg(not(test))] +type LoopSpans = Vec<(usize, usize)>; + +#[cfg(test)] +#[derive(Default)] +pub(super) struct LoopSpans { + spans: Vec<(usize, usize)>, + reads: std::cell::Cell, +} + +#[cfg(test)] +impl std::ops::Deref for LoopSpans { + type Target = Vec<(usize, usize)>; + + fn deref(&self) -> &Self::Target { + self.reads.set(self.reads.get() + 1); + &self.spans + } +} + +#[cfg(test)] +impl std::ops::DerefMut for LoopSpans { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.spans + } +} + /// The names a file's function bodies and its global code declare, read before the analysis. A /// function's `var` statements and the function declarations directly in its body make the names /// they declare the function's own before any statement in it runs, and the function declarations @@ -46,7 +73,7 @@ pub(crate) struct Declared<'s> { pub(super) looped: HashMap<(Option, &'s str), Vec>, /// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at /// the end of the text). - pub(super) loop_spans: Vec<(usize, usize)>, + pub(super) loop_spans: LoopSpans, /// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any /// variable may be assigned in a loop. pub(super) looped_full: bool, @@ -60,6 +87,13 @@ pub(crate) struct Declared<'s> { pub(super) unsure: bool, } +#[cfg(test)] +impl Declared<'_> { + pub(crate) fn loop_span_reads(&self) -> usize { + self.loop_spans.reads.get() + } +} + /// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in /// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement /// the body is in, which goes on when the body closes, and the names assigned in a loop inside it @@ -169,6 +203,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> { d.settle_looped(body); } let mut out = d.out; + for ids in out.looped.values_mut() { + ids.sort_unstable(); + ids.dedup(); + } out.unsure |= out.rebound.contains(catalog::FOLDER); acc.steps = acc.steps.saturating_add(lexer.steps); out diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 8b6b4c5f1d..48db72caad 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -373,13 +373,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn writer_bits(&self, receiver: Option>, before: Option>, at: Option) -> u8 { match receiver { Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => { + let Some(bits) = self.writers.get(r.text).copied() else { return 0 }; + if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) { + return 0; + } let looped = at.is_some_and(|at| { self.declared.looped_full || self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| { - ids.iter().any(|id| self.declared.loop_spans.get(*id).is_some_and(|(start, end)| *start <= at && at < *end)) + let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at); + next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok()) }) }); - if looped { 0 } else { self.writers.get(r.text).copied().unwrap_or(0) } + if looped { 0 } else { bits } } _ => 0, } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index a580c3d311..2991b1c23f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -790,6 +790,34 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..])); } +#[test] +fn writer_calls_after_many_assignment_loops_have_bounded_work() { + for reinitialize in [false, true] { + let mut src = "var d = {saveAs: function () {}};\n".to_string(); + for _ in 0..512 { + src.push_str("while (n--) { d = next(); }\n"); + } + if reinitialize { + src.push_str("var d = {saveAs: function () {}};\n"); + } + src.push_str("var local = {saveAs: function () {}};\n"); + for _ in 0..2048 { + src.push_str("d.saveAs(f); local.saveAs(f);\n"); + } + let limits = Limits::default(); + let mut acc = report::Acc::new(&limits); + let declared = analyze::declarations(&src, &mut acc); + let before = declared.loop_span_reads(); + analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc); + let reads = declared.loop_span_reads() - before; + if reinitialize { + assert!(reads < 16 * 2048, "{reads} span accesses for 2048 calls on d"); + } else { + assert_eq!(reads, 0); + } + } +} + /// A function body read before the literal that assigns its variable without declaring it may run /// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the /// name assigns its own variable. @@ -810,6 +838,25 @@ fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..])); } +#[test] +fn captured_writer_receivers_can_change_before_each_call() { + for method in ["saveAs", "exportFile"] { + for call in [format!("d.{method}(f)"), format!("d['{method}'](f)")] { + for (prefix, suffix) in [("", ""), ("function outer() {\n", "}\nouter();\n")] { + let src = format!( + "{prefix}var d = {{{method}: function () {{}}}};\n\ + function save(f) {{ {call}; }}\n\ + d = app.activeDocument; save(f);\n{suffix}" + ); + let r = report(&src); + let line = if prefix.is_empty() { 2 } else { 3 }; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[line][..]), "{src}"); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[line][..])], "{src}"); + } + } + } +} + #[test] fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() { let r = report(concat!( From f4c911d4d34f9b10071fd050dbc14ab665a61fb9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:36:01 -0800 Subject: [PATCH 19/20] 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. --- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 13 +++++- crates/engine/src/cmd/fileio/svg.rs | 9 +++- crates/engine/src/script/dom/save_open.rs | 31 ++++++++++--- crates/engine/src/tests/script_save_open.rs | 39 ++++++++++++++++ crates/engine/tests/plugin_import.rs | 27 +++++++++++ crates/scriptcheck/src/analyze.rs | 19 +++++++- crates/scriptcheck/src/analyze/declared.rs | 33 +++++++++++--- crates/scriptcheck/src/analyze/features.rs | 11 ++--- crates/scriptcheck/src/tests.rs | 50 +++++++++++++++++++++ docs/mcp.md | 7 ++- 11 files changed, 215 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 21424f7bdc..38654bb8ba 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -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. diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index e426bd5a23..cce50485dd 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1096,8 +1096,17 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result { 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")); } diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index e5ecc858dc..ac66cb8e65 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -174,12 +174,17 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option Option { 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 { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 09c438040c..060454798a 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -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::(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::(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, diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 68183e8637..064ff3c15a 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -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"); diff --git a/crates/engine/tests/plugin_import.rs b/crates/engine/tests/plugin_import.rs index 1327e57208..9f77d86ec4 100644 --- a/crates/engine/tests/plugin_import.rs +++ b/crates/engine/tests/plugin_import.rs @@ -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(); diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index a66b20ef06..a88d7fd04e 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -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>; 4], + /// The significant token before the four of [`Self::h`]. + h4: Option>, 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 { diff --git a/crates/scriptcheck/src/analyze/declared.rs b/crates/scriptcheck/src/analyze/declared.rs index 03ad43ab10..ca4ac99823 100644 --- a/crates/scriptcheck/src/analyze/declared.rs +++ b/crates/scriptcheck/src/analyze/declared.rs @@ -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; diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 48db72caad..ac0e69b52f 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -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>, before: Option>| 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 }; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 2991b1c23f..ca87f3d384 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -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 diff --git a/docs/mcp.md b/docs/mcp.md index b2678c4f1d..d4cb072175 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 From ed0859d0d0a8809adc95feab96190324aa532b9f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:51:17 -0800 Subject: [PATCH 20/20] Scripts: kept-default option enumerations and refusal of non-UTF-8 real paths The enumerations whose default member an option keeps (OutputFlattening, CompressionQuality, the PDF color, compression, mark and security enums, and the SVG encoding, DTD, CSS and font enums) are now defined, so a script that sets an option to its default no longer throws a ReferenceError; another member still throws as not available yet. saveAs, exportFile, app.open and close with SAVECHANGES refuse a path whose real file name is not valid UTF-8 instead of writing to or opening a file named with a lossy copy of it. --- crates/engine/src/script/dom/save_open.rs | 88 +++++++++++++++++-- crates/engine/src/tests/script_save_open.rs | 86 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 37 +++++++- docs/mcp.md | 8 +- docs/target-app-parity.md | 2 +- 5 files changed, 209 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 060454798a..510364d249 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -110,6 +110,76 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), ("SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"]), + // The enumerations of the options that keep their defaults (`Default::Member`). + ("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]), + ( + "CompressionQuality", + &[ + "AUTOMATICJPEG2000HIGH", + "AUTOMATICJPEG2000LOSSLESS", + "AUTOMATICJPEG2000LOW", + "AUTOMATICJPEG2000MAXIMUM", + "AUTOMATICJPEG2000MEDIUM", + "AUTOMATICJPEG2000MINIMUM", + "AUTOMATICJPEGHIGH", + "AUTOMATICJPEGLOW", + "AUTOMATICJPEGMAXIMUM", + "AUTOMATICJPEGMEDIUM", + "AUTOMATICJPEGMINIMUM", + "JPEG2000HIGH", + "JPEG2000LOSSLESS", + "JPEG2000LOW", + "JPEG2000MAXIMUM", + "JPEG2000MEDIUM", + "JPEG2000MINIMUM", + "JPEGHIGH", + "JPEGLOW", + "JPEGMAXIMUM", + "JPEGMEDIUM", + "JPEGMINIMUM", + "None", + "ZIP4BIT", + "ZIP8BIT", + ], + ), + ("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]), + ( + "ColorDestination", + &[ + "COLORDESTINATIONDOCCMYK", + "COLORDESTINATIONDOCRGB", + "COLORDESTINATIONPROFILE", + "COLORDESTINATIONWORKINGCMYK", + "COLORDESTINATIONWORKINGRGB", + "None", + ], + ), + ("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]), + ("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]), + ("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]), + ("PageMarksTypes", &["Japanese", "Roman"]), + ( + "PDFChangesAllowedEnum", + &[ + "CHANGE128ANYCHANGES", + "CHANGE128COMMENTING", + "CHANGE128EDITPAGE", + "CHANGE128FILLFORM", + "CHANGE128NONE", + "CHANGE40ANYCHANGES", + "CHANGE40COMMENTING", + "CHANGE40NONE", + "CHANGE40PAGELAYOUT", + ], + ), + ("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]), + ("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]), + ("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]), + ("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]), + ("SVGDocumentEncoding", &["ASCII", "UTF16", "UTF8"]), + ("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]), + ("SVGFontSubsetting", &["ALLGLYPHS", "COMMONENGLISH", "COMMONROMAN", "GLYPHSUSED", "GLYPHSUSEDPLUSENGLISH", "GLYPHSUSEDPLUSROMAN", "None"]), + ("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]), ]; const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; @@ -676,9 +746,9 @@ fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer { Ok(answer) } -/// The path to give a command for the real path `real`. -fn plain(real: std::path::PathBuf) -> String { - crate::cmd::findfiles::plain(real).to_string_lossy().into_owned() +/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8. +fn plain(real: std::path::PathBuf) -> std::result::Result { + crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into())) } /// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the @@ -738,7 +808,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { p.insert("format".into(), json!(format)); } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(real))); + p.insert("path".into(), json!(plain(real)?)); exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -793,7 +863,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { } let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; - p.insert("path".into(), json!(plain(real))); + p.insert("path".into(), json!(plain(real)?)); exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?; Ok(Data::Undefined) } @@ -841,8 +911,10 @@ fn app_open(h: &Host, a: &[Data]) -> Answer { if p.contains_key("cropTo") { p.insert("editingData".into(), json!(false)); } - h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; - p.insert("path".into(), json!(plain(std::path::PathBuf::from(path)))); + // The command opens the given path; a real path that is not valid UTF-8 is still refused. + let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?; + plain(real)?; + p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?)); let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?; let index = match &r { Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) { @@ -1012,7 +1084,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer { // A refusal names the document, as `fullName` does when the read roots hide its file. let name = super::with_doc(h, doc, |_, st| st.title()); let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?; - let p = json!({"path": plain(real), "format": format}); + let p = json!({"path": plain(real)?, "format": format}); exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?; } _ => return Err(HostError::Error(UNSAVED_CHANGES.into())), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 064ff3c15a..e8bd8675cb 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -212,6 +212,92 @@ fn omitted_options_are_a_new_options_objects_defaults() { let _ = std::fs::remove_dir_all(base); } +/// A path that resolves to a name that is not valid UTF-8 is refused before anything is written or +/// opened, so no file with a lossy copy of the name is touched. +#[cfg(unix)] +#[test] +fn script_file_commands_refuse_non_utf8_resolved_paths() { + use std::os::unix::ffi::OsStringExt; + + let base = folder("non-utf8-target"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let original = dir.join("original.vectorcraft"); + s.execute("file.saveAs", &json!({"path": original.to_string_lossy()})).unwrap(); + let bytes = std::fs::read(&original).unwrap(); + let target = dir.join(std::ffi::OsString::from_vec(b"target-\xff.vectorcraft".to_vec())); + // A file system that refuses such a name has nothing to refuse. + if std::fs::write(&target, &bytes).is_err() { + let _ = std::fs::remove_dir_all(base); + return; + } + let link = dir.join("alias.vectorcraft"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + let lossy = PathBuf::from(target.to_string_lossy().into_owned()); + std::fs::write(&lossy, &bytes).unwrap(); + for call in ["app.activeDocument.saveAs(f);", "app.activeDocument.exportFile(f, ExportType.SVG);", "app.open(f);"] { + let alias = if call.contains("exportFile") { + let alias = dir.join("alias.svg"); + std::os::unix::fs::symlink(&target, &alias).unwrap(); + alias + } else { + link.clone() + }; + let count = s.documents().len(); + let error = failure(&mut s, &base, &format!("Folder.userData; var f = new File({}); {call}", quoted(&alias))); + assert!(error.contains("Script file path is not valid UTF-8"), "{call}: {error}"); + assert_eq!(s.documents().len(), count); + assert_eq!(std::fs::read(&target).unwrap(), bytes); + assert_eq!(std::fs::read(&lossy).unwrap(), bytes); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Every enumeration an option keeps its default in is defined: the default member is accepted, and +/// another member of the same enumeration is refused as not available yet. +#[test] +fn kept_enum_options_accept_their_default_member() { + let base = folder("keptenums"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let file = |n: &str| format!("new File({})", quoted(&dir.join(n))); + let cases: &[(&str, &str, &str, &str)] = &[ + ("IllustratorSaveOptions", "flattenOutput", "OutputFlattening.PRESERVEAPPEARANCE", "OutputFlattening.PRESERVEPATHS"), + ("PDFSaveOptions", "colorCompression", "CompressionQuality.None", "CompressionQuality.ZIP8BIT"), + ("PDFSaveOptions", "colorConversionID", "ColorConversion.None", "ColorConversion.COLORCONVERSIONTODEST"), + ("PDFSaveOptions", "colorDestinationID", "ColorDestination.None", "ColorDestination.COLORDESTINATIONPROFILE"), + ("PDFSaveOptions", "colorDownsamplingMethod", "DownsampleMethod.NODOWNSAMPLE", "DownsampleMethod.SUBSAMPLE"), + ("PDFSaveOptions", "colorProfileID", "ColorProfile.None", "ColorProfile.INCLUDEALLPROFILE"), + ("PDFSaveOptions", "monochromeCompression", "MonochromeCompression.None", "MonochromeCompression.CCIT4"), + ("PDFSaveOptions", "pageMarksType", "PageMarksTypes.Roman", "PageMarksTypes.Japanese"), + ("PDFSaveOptions", "pDFAllowPrinting", "PDFPrintAllowedEnum.PRINT128HIGHRESOLUTION", "PDFPrintAllowedEnum.PRINT40NONE"), + ("PDFSaveOptions", "pDFChangesAllowed", "PDFChangesAllowedEnum.CHANGE128ANYCHANGES", "PDFChangesAllowedEnum.CHANGE40NONE"), + ("PDFSaveOptions", "pDFXStandard", "PDFXStandard.PDFXNONE", "PDFXStandard.PDFX42007"), + ("PDFSaveOptions", "trimMarkWeight", "PDFTrimMarkWeight.TRIMMARKWEIGHT0125", "PDFTrimMarkWeight.TRIMMARKWEIGHT05"), + ("ExportOptionsSVG", "cssProperties", "SVGCSSPropertyLocation.STYLEATTRIBUTES", "SVGCSSPropertyLocation.ENTITIES"), + ("ExportOptionsSVG", "documentEncoding", "SVGDocumentEncoding.ASCII", "SVGDocumentEncoding.UTF8"), + ("ExportOptionsSVG", "DTD", "SVGDTDVersion.SVG1_1", "SVGDTDVersion.SVGTINY1_2"), + ("ExportOptionsSVG", "fontSubsetting", "SVGFontSubsetting.ALLGLYPHS", "SVGFontSubsetting.GLYPHSUSED"), + ("ExportOptionsSVG", "fontType", "SVGFontType.CEFFONT", "SVGFontType.OUTLINEFONT"), + ]; + for (i, (class, key, default, other)) in cases.iter().enumerate() { + let call = |value: &str, n: String| { + let set = format!("var o = new {class}(); o.{key} = {value};"); + match *class { + "ExportOptionsSVG" => format!("{set} app.activeDocument.exportFile({}, ExportType.SVG, o);", file(&format!("{n}.svg"))), + "PDFSaveOptions" => format!("{set} app.activeDocument.saveAs({}, o);", file(&format!("{n}.pdf"))), + _ => format!("{set} app.activeDocument.saveAs({}, o);", file(&format!("{n}.ai"))), + } + }; + logged(&mut s, &base, &format!("Folder.userData; {}", call(default, format!("ok{i}")))); + let e = failure(&mut s, &base, &format!("Folder.userData; {}", call(other, format!("no{i}")))); + assert!(e.contains("is not available yet"), "{class}.{key} = {other}: {e}"); + } + let _ = std::fs::remove_dir_all(base); +} + /// A raster export at 100% has one pixel per point, whatever the document's raster effects /// resolution. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 4263fad910..b55418acb2 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -192,9 +192,42 @@ const INSIDE: &[(&str, &str)] = &[ // The enumerations of saving, exporting and opening. ( "", - "Compatibility EPSPostScriptLevelEnum EPSPreview ExportType PDFBoxType PDFCompatibility PDFOverprint SaveOptions \ - UserInteractionLevel", + "ColorConversion ColorDestination ColorProfile Compatibility CompressionQuality DownsampleMethod EPSPostScriptLevelEnum \ + EPSPreview ExportType MonochromeCompression OutputFlattening PDFBoxType PDFChangesAllowedEnum PDFCompatibility \ + PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \ + SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel", ), + ("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"), + ( + "ColorDestination.", + "COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \ + COLORDESTINATIONWORKINGRGB None", + ), + ("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"), + ( + "CompressionQuality.", + "AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM AUTOMATICJPEG2000MEDIUM \ + AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM \ + JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM \ + JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT", + ), + ("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"), + ("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"), + ("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"), + ( + "PDFChangesAllowedEnum.", + "CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE CHANGE40ANYCHANGES \ + CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT", + ), + ("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"), + ("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"), + ("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"), + ("PageMarksTypes.", "Japanese Roman"), + ("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"), + ("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"), + ("SVGDocumentEncoding.", "ASCII UTF16 UTF8"), + ("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"), + ("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"), ( "Compatibility.", "ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \ diff --git a/docs/mcp.md b/docs/mcp.md index d4cb072175..3e795ea765 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3131,7 +3131,13 @@ through `$`: explicit `null` throws a type error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, `EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as - `"ExportType.PNG24"`. + `"ExportType.PNG24"`. The enumerations of the options that keep their defaults (`OutputFlattening`, + `CompressionQuality`, `ColorConversion`, `ColorDestination`, `ColorProfile`, `DownsampleMethod`, + `MonochromeCompression`, `PageMarksTypes`, `PDFChangesAllowedEnum`, `PDFPrintAllowedEnum`, `PDFTrimMarkWeight`, + `PDFXStandard`, `SVGCSSPropertyLocation`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and + `SVGFontType`) are defined too: the default member is accepted, and another member throws as not available yet. A + path whose real file name is not valid UTF-8 throws `Script file path is not valid UTF-8` before anything is written + or opened. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4e695e800b..0547365012 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1127,7 +1127,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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 key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.