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`.