From 48a09ccae35e34bd317ef0dcbd0c9cf28df0e9ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 07:05:03 -0800 Subject: [PATCH 01/27] Scripts: Document.exportForScreens writes artboards, assets or the document into a folder Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?) runs document.exportForScreens with one format row. The option classes ExportForScreensOptionsJPEG, ExportForScreensOptionsPNG24, ExportForScreensOptionsPNG8, ExportForScreensOptionsWebOptimizedSVG and ExportForScreensPDFOptions, ExportForScreensItemToExport and the enumerations they use follow the public reference pages. An omitted options object takes a new one's defaults; a bad argument, an options object of another class and an item that names nothing throw before anything is written. The folder gets the same write-access check as a File opened for writing: a folder outside the script's folders is refused, and so is an existing file. A prefix character that a file name may not hold is written as "-". A Folder object passed to a host method now carries its path, as a File does; before, it arrived as an empty object. The script checker counts exportForScreens under filesWritten. Docs: docs/mcp.md, docs/target-app-parity.md, docs/gaps.md. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/save_open.rs | 6 + .../src/script/dom/save_open/screens.rs | 491 ++++++++++++++++++ crates/engine/src/script/files.rs | 12 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_screens.rs | 351 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 18 +- crates/js/src/file_classes.rs | 14 +- crates/js/src/host.rs | 7 +- crates/scriptcheck/src/catalog.rs | 6 +- crates/scriptcheck/src/tests.rs | 15 + docs/gaps.md | 2 +- docs/mcp.md | 40 +- docs/target-app-parity.md | 1 + 14 files changed, 954 insertions(+), 12 deletions(-) create mode 100644 crates/engine/src/script/dom/save_open/screens.rs create mode 100644 crates/engine/src/tests/script_screens.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2be7b42074..104511f055 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2077,7 +2077,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.iter().chain(save_open::ENUMS) { + for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(save_open::screens::ENUMS) { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 6400b32f73..c7c5eadd14 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -62,6 +62,8 @@ use std::rc::Rc; use serde_json::{Map, Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; +pub(super) mod screens; + use super::{ Answer, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, current, doc_ref, get, given, method, named, num, on_doc, property, text, this_doc, whole, @@ -955,6 +957,9 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { ("saved", property(l, doc_saved, doc_set_saved)), ("close", method(l, doc_close)), ]) + .into_iter() + .chain(screens::document_members(l)) + .collect() } /// The option classes: each `new Name()` gives a record with its `typename` and the defaults its @@ -969,5 +974,6 @@ pub(super) fn classes(link: &Link) -> Vec { }); HostClass { name: c.name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } }) + .chain(screens::classes(link)) .collect() } diff --git a/crates/engine/src/script/dom/save_open/screens.rs b/crates/engine/src/script/dom/save_open/screens.rs new file mode 100644 index 0000000000..f4008be1b6 --- /dev/null +++ b/crates/engine/src/script/dom/save_open/screens.rs @@ -0,0 +1,491 @@ +//! `Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?)` +//! with `ExportForScreensItemToExport`, the option classes `ExportForScreensOptionsJPEG`, +//! `ExportForScreensOptionsPNG24`, `ExportForScreensOptionsPNG8`, +//! `ExportForScreensOptionsWebOptimizedSVG` and `ExportForScreensPDFOptions`, and the enumerations +//! they use, as the scripting reference pages +//! , +//! , +//! , +//! , +//! , +//! , +//! and +//! describe. +//! +//! The method runs `document.exportForScreens` with one format row into the folder, which goes +//! through the script's file grants as a `File` opened for writing there would, and the command +//! writes only where the script's `File` objects may ([`super::exactly`]). +//! +//! VectorCraft's own rules, which the reference pages do not state: +//! - `exportFolder` is a `Folder`, or a `File` read as the folder at its path. The files go into +//! that folder, without sub-folders, each named `.` as +//! `document.exportForScreens` names them (`@2x` after a raster file of twice the size), with +//! the characters a file name may not hold in the prefix written as `-`. The export keeps its +//! settings in the document, as an export from the dialog does. +//! - `itemToExport` exports, in this order, the artboards of `artboards` (`all`, the default, or a +//! range of artboard numbers such as `1-3, 5`; `""` for none), the assets of `assets` (their ids) +//! and, with `document` true, the bounds of the whole document's art (a PDF of every artboard). +//! One that names nothing throws. Each of the three is its own export: when a later one throws, +//! the files of the earlier ones stay written. +//! - `ExportForScreensType.SE_JPEG100`, `SE_JPEG80`, `SE_JPEG50` and `SE_JPEG20` write JPEG at a +//! quality of 100, 80, 50 and 20. A scale factor is from 0.01 to 64 and a resolution from 0.72 +//! to 4608 ppi. +//! - `RasterImageLocation.PRESERVE`, the default, embeds raster images as `EMBED` does, and +//! `SVGFontType.SVGFONT`, the default, writes text as SVG text elements. +//! - Options are read as `Document.exportFile` reads them: a listed option that is not mapped is +//! accepted at its default and throws at any other value, and a property the pages do not list +//! throws an error that names it, unless it is `undefined`. The options object's class must be +//! the one of `exportFormat`, and an omitted options object takes the defaults a new one holds. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember}; + +use super::{ + Answer, Default, Host, Link, MAX_TEXT_BYTES, OptionClass, arg, boolean, builtin_preset_name, command, current, exactly, fresh, given, member, + method, named, num, on_doc, plain, refused, text, this_doc, typename, whole, whole_in, written_as_range, +}; + +/// The enumerations these members use, as `dom`'s are made. +pub(in crate::script::dom) const ENUMS: &[(&str, &[&str])] = &[ + ("ExportForScreensType", &["SE_JPEG100", "SE_JPEG20", "SE_JPEG50", "SE_JPEG80", "SE_PDF", "SE_PNG24", "SE_PNG8", "SE_SVG"]), + ("ExportForScreensScaleType", &["SCALEBYFACTOR", "SCALEBYHEIGHT", "SCALEBYRESOLUTION", "SCALEBYWIDTH"]), + ("AntiAliasingMethod", &["ARTOPTIMIZED", "None", "TYPEOPTIMIZED"]), + ("JPEGCompressionMethodType", &["BASELINEOPTIMIZED", "BASELINESTANDARD", "PROGRESSIVE"]), + ("RasterImageLocation", &["EMBED", "LINK", "PRESERVE"]), + ("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]), + ("SVGFontType", &["OUTLINEFONT", "SVGFONT"]), + ("SVGIdType", &["SVGIDMINIMAL", "SVGIDREGULAR", "SVGIDUNIQUE"]), +]; + +/// The members of `enumeration` in [`ENUMS`]. +fn members(enumeration: &str) -> &'static [&'static str] { + ENUMS.iter().find(|(n, _)| *n == enumeration).map_or(&[][..], |(_, m)| *m) +} + +/// The member of `enumeration` that `d` names. +fn pick<'a>(d: &'a Data, enumeration: &str, what: &str) -> std::result::Result<&'a str, HostError> { + member(d, enumeration, members(enumeration), what) +} + +/// The least and most pixels per point a raster file of an export has. +const SCALE_FACTORS: (f64, f64) = (0.01, 64.0); + +// ---- Raster options ---- + +/// The options JPEG, PNG24 and PNG8 share: anti-aliasing and the size, the size kept under `_scale` +/// and `_scaleValue` until [`size`] reads them together. +fn raster_map(class: &str, name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("{class}.{name}"); + match name { + "antiAliasing" => { + let mode = match pick(d, "AntiAliasingMethod", &what)? { + "ARTOPTIMIZED" => "art", + "TYPEOPTIMIZED" => "type", + _ => "none", + }; + p.insert("antiAlias".into(), json!(mode)); + } + "scaleType" => { + p.insert("_scale".into(), json!(pick(d, "ExportForScreensScaleType", &what)?)); + } + "scaleTypeValue" => match d { + Data::Number(n) if n.is_finite() && *n > 0.0 => { + p.insert("_scaleValue".into(), json!(n)); + } + Data::Number(_) => return Err(HostError::Range(format!("{what} must be a number above 0"))), + _ => return Err(HostError::Type(format!("{what} must be a number"))), + }, + _ => return Ok(false), + } + Ok(true) +} + +/// The format row's size from `_scale` and `_scaleValue`: a factor (`scale`), a width or a height +/// in pixels (`width`, `height`), or a resolution (`ppi`). +fn size(p: &mut Map) -> std::result::Result<(), HostError> { + let how = p.remove("_scale").and_then(|v| v.as_str().map(str::to_string)).unwrap_or_else(|| "SCALEBYFACTOR".into()); + let value = p.remove("_scaleValue").and_then(|v| v.as_f64()).unwrap_or(1.0); + let (lo, hi) = SCALE_FACTORS; + let (key, per_point) = match how.as_str() { + "SCALEBYWIDTH" => ("width", None), + "SCALEBYHEIGHT" => ("height", None), + "SCALEBYRESOLUTION" => ("ppi", Some(value / 72.0)), + _ => ("scale", Some(value)), + }; + if per_point.is_some_and(|f| !(lo..=hi).contains(&f)) { + let range = if key == "ppi" { "from 0.72 to 4608" } else { "from 0.01 to 64" }; + return Err(HostError::Range(format!("scaleTypeValue must be {range} with ExportForScreensScaleType.{how}"))); + } + p.insert(key.into(), json!(value)); + Ok(()) +} + +fn jpeg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + const CLASS: &str = "ExportForScreensOptionsJPEG"; + let what = format!("{CLASS}.{name}"); + match name { + "compressionMethod" => { + let method = match pick(d, "JPEGCompressionMethodType", &what)? { + "BASELINEOPTIMIZED" => "optimized", + "PROGRESSIVE" => "progressive", + _ => "baseline", + }; + p.insert("method".into(), json!(method)); + } + "embedICCProfile" => { + p.insert("embedIcc".into(), json!(boolean(d, &what)?)); + } + "progressiveScan" => { + p.insert("scans".into(), json!(whole_in(d, &what, 3, 5)?)); + } + _ => return raster_map(CLASS, name, d, p), + } + Ok(true) +} + +fn jpeg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("compressionMethod", text("JPEGCompressionMethodType.BASELINESTANDARD")), + ("embedICCProfile", Data::Bool(false)), + ("progressiveScan", num(3.0)), + ("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")), + ("scaleTypeValue", num(1.0)), + ] +} + +/// PNG24's background, kept under `_transparent` and `_black` until [`background`] reads them +/// together. +fn png24_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + const CLASS: &str = "ExportForScreensOptionsPNG24"; + let what = format!("{CLASS}.{name}"); + match name { + "transparency" => { + p.insert("_transparent".into(), json!(boolean(d, &what)?)); + } + "backgroundBlack" => { + p.insert("_black".into(), json!(boolean(d, &what)?)); + } + "interlaced" => { + p.insert("interlaced".into(), json!(boolean(d, &what)?)); + } + _ => return raster_map(CLASS, name, d, p), + } + Ok(true) +} + +/// The PNG24 row's `background`: transparent with `transparency`, otherwise black with +/// `backgroundBlack` and white without it. +fn background(p: &mut Map) { + let transparent = p.remove("_transparent").and_then(|v| v.as_bool()).unwrap_or(true); + let black = p.remove("_black").and_then(|v| v.as_bool()).unwrap_or(false); + let background = if transparent { + "transparent" + } else if black { + "black" + } else { + "white" + }; + p.insert("background".into(), json!(background)); +} + +fn png24_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("backgroundBlack", Data::Bool(false)), + ("interlaced", Data::Bool(false)), + ("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")), + ("scaleTypeValue", num(1.0)), + ("transparency", Data::Bool(true)), + ] +} + +fn png8_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + const CLASS: &str = "ExportForScreensOptionsPNG8"; + let what = format!("{CLASS}.{name}"); + match name { + "colorCount" => { + p.insert("colors".into(), json!(whole_in(d, &what, 2, 256)?)); + } + "interlaced" => { + p.insert("interlaced".into(), json!(boolean(d, &what)?)); + } + "transparency" => { + p.insert("transparency".into(), json!(boolean(d, &what)?)); + } + // Matted on white, the default `matteColor`, or not matted. + "matte" => { + p.insert("matte".into(), if boolean(d, &what)? { json!("white") } else { Value::Null }); + } + _ => return raster_map(CLASS, name, d, p), + } + Ok(true) +} + +const PNG8_KEPT: &[(&str, Default)] = &[("matteColor", Default::Unset)]; + +fn png8_starts() -> Vec<(&'static str, Data)> { + vec![ + ("antiAliasing", text("AntiAliasingMethod.ARTOPTIMIZED")), + ("colorCount", num(128.0)), + ("interlaced", Data::Bool(false)), + ("matte", Data::Bool(true)), + ("scaleType", text("ExportForScreensScaleType.SCALEBYFACTOR")), + ("scaleTypeValue", num(1.0)), + ("transparency", Data::Bool(true)), + ] +} + +// ---- Vector options ---- + +fn svg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportForScreensOptionsWebOptimizedSVG.{name}"); + let (key, value) = match name { + "coordinatePrecision" => ("decimals", json!(whole_in(d, &what, 1, 7)?)), + "cssProperties" => { + let styling = match pick(d, "SVGCSSPropertyLocation", &what)? { + "ENTITIES" => "entities", + "PRESENTATIONATTRIBUTES" => "presentation", + "STYLEELEMENTS" => "css", + _ => "style", + }; + ("styling", json!(styling)) + } + "fontType" => ("outlineText", json!(pick(d, "SVGFontType", &what)? == "OUTLINEFONT")), + "rasterImageLocation" => ("images", json!(if pick(d, "RasterImageLocation", &what)? == "LINK" { "link" } else { "embed" })), + "svgId" => { + let ids = match pick(d, "SVGIdType", &what)? { + "SVGIDMINIMAL" => "minimal", + "SVGIDUNIQUE" => "unique", + _ => "layerNames", + }; + ("objectIds", json!(ids)) + } + "svgMinify" => ("minify", json!(boolean(d, &what)?)), + "svgResponsive" => ("responsive", json!(boolean(d, &what)?)), + _ => return Ok(false), + }; + p.insert(key.into(), value); + Ok(true) +} + +fn svg_starts() -> Vec<(&'static str, Data)> { + vec![ + ("coordinatePrecision", num(3.0)), + ("cssProperties", text("SVGCSSPropertyLocation.STYLEATTRIBUTES")), + ("fontType", text("SVGFontType.SVGFONT")), + ("rasterImageLocation", text("RasterImageLocation.PRESERVE")), + ("svgId", text("SVGIdType.SVGIDREGULAR")), + ("svgMinify", Data::Bool(false)), + ("svgResponsive", Data::Bool(true)), + ] +} + +/// The PDF preset's name, at most 255 bytes, as the reference page limits it. +fn pdf_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + if name != "pdfPreset" { + return Ok(false); + } + let what = "ExportForScreensPDFOptions.pdfPreset"; + let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) }; + if s.len() > 255 { + return Err(HostError::Range(format!("{what} is longer than 255 bytes"))); + } + if !s.is_empty() { + p.insert("preset".into(), json!(s)); + } + Ok(true) +} + +fn pdf_starts() -> Vec<(&'static str, Data)> { + Vec::new() +} + +// ---- What to export ---- + +/// `ExportForScreensItemToExport`'s properties, kept under `_artboards`, `_assets` and `_document` +/// until [`exports`] reads them. +fn item_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { + let what = format!("ExportForScreensItemToExport.{name}"); + match name { + "artboards" => { + let r = match d { + Data::String(s) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range(format!("{what} is too long"))), + Data::String(s) => s.clone(), + Data::Number(n) => { + whole(*n).filter(|n| *n >= 1).ok_or_else(|| HostError::Range(format!("{what} must be a whole number from 1 or a range")))?; + vectorcraft_js::number_to_string(*n) + } + _ => return Err(HostError::Type(format!("{what} must be a string"))), + }; + p.insert("_artboards".into(), json!(r)); + } + "assets" => { + let Data::Array(ids) = d else { return Err(HostError::Type(format!("{what} must be an array of asset ids"))) }; + let ids = ids + .iter() + .map(|id| match id { + Data::Number(n) => whole(*n).ok_or_else(|| HostError::Range(format!("{what} holds {n}, not an asset id"))), + _ => Err(HostError::Type(format!("{what} must be an array of asset ids"))), + }) + .collect::, HostError>>()?; + p.insert("_assets".into(), json!(ids)); + } + "document" => { + p.insert("_document".into(), json!(boolean(d, &what)?)); + } + _ => return Ok(false), + } + Ok(true) +} + +fn item_starts() -> Vec<(&'static str, Data)> { + vec![("artboards", text("all")), ("assets", Data::Array(Vec::new())), ("document", Data::Bool(false))] +} + +const JPEG: OptionClass = OptionClass { name: "ExportForScreensOptionsJPEG", map: jpeg_map, kept: &[], starts: jpeg_starts }; +const PNG24: OptionClass = OptionClass { name: "ExportForScreensOptionsPNG24", map: png24_map, kept: &[], starts: png24_starts }; +const PNG8: OptionClass = OptionClass { name: "ExportForScreensOptionsPNG8", map: png8_map, kept: PNG8_KEPT, starts: png8_starts }; +const SVG: OptionClass = OptionClass { name: "ExportForScreensOptionsWebOptimizedSVG", map: svg_map, kept: &[], starts: svg_starts }; +const PDF: OptionClass = OptionClass { name: "ExportForScreensPDFOptions", map: pdf_map, kept: &[], starts: pdf_starts }; +const ITEM: OptionClass = OptionClass { name: "ExportForScreensItemToExport", map: item_map, kept: &[], starts: item_starts }; + +/// The params of `class` for `d` (a new object's when `d` is omitted), over a new object's, so a +/// property a record leaves out keeps its default. +fn params(class: &OptionClass, d: Option<&Data>) -> std::result::Result, HostError> { + let mut p = super::options_params(class, &fresh(class))?; + if let Some(d) = d { + p.extend(super::options_params(class, d)?); + } + Ok(p) +} + +/// The format row `exportFormat` (`d`) asks for, with its option class. +fn format(d: &Data) -> std::result::Result<(Map, &'static OptionClass), HostError> { + let (format, quality, class) = match pick(d, "ExportForScreensType", "exportFormat")? { + "SE_JPEG100" => ("jpg", Some(100), &JPEG), + "SE_JPEG80" => ("jpg", Some(80), &JPEG), + "SE_JPEG50" => ("jpg", Some(50), &JPEG), + "SE_JPEG20" => ("jpg", Some(20), &JPEG), + "SE_PNG24" => ("png", None, &PNG24), + "SE_PNG8" => ("png8", None, &PNG8), + "SE_SVG" => ("svg", None, &SVG), + _ => ("pdf", None, &PDF), + }; + let mut row = Map::new(); + row.insert("format".into(), json!(format)); + if let Some(q) = quality { + row.insert("quality".into(), json!(q)); + } + Ok((row, class)) +} + +/// The exports `itemToExport` asks for, in order: the artboards, the assets and the whole +/// document, each as the params that pick it. +fn exports(d: Option<&Data>) -> std::result::Result>, HostError> { + if let Some(d) = d + && typename(d) != Some(ITEM.name) + { + return Err(HostError::Type("itemToExport must be an ExportForScreensItemToExport object".into())); + } + let mut p = params(&ITEM, d)?; + let mut out = Vec::new(); + if let Some(Value::String(r)) = p.remove("_artboards") { + let all = r.trim().eq_ignore_ascii_case("all"); + if !r.trim().is_empty() { + if !all && !written_as_range(&r) { + return Err(HostError::Range(format!("ExportForScreensItemToExport.artboards `{r}` is not a range of artboard numbers"))); + } + out.push(Map::from_iter([("range".to_string(), json!(if all { "all" } else { r.as_str() }))])); + } + } + if let Some(ids) = p.remove("_assets").filter(|v| v.as_array().is_some_and(|a| !a.is_empty())) { + out.push(Map::from_iter([("assets".to_string(), ids)])); + } + if p.remove("_document").and_then(|v| v.as_bool()) == Some(true) { + out.push(Map::from_iter([("fullDocument".to_string(), json!(true))])); + } + if out.is_empty() { + return Err(HostError::Error( + "exportForScreens has nothing to export: itemToExport names no artboards, no assets and not the document".into(), + )); + } + Ok(out) +} + +/// The path of the `Folder` (or `File`) argument `d`, or a `TypeError`. +fn folder_path(d: &Data) -> std::result::Result<&str, HostError> { + let wrong = || HostError::Type("exportForScreens needs a Folder".into()); + if let Some(p) = vectorcraft_js::file_ref_path(d) { + return Ok(p); + } + let Data::Object(items) = d else { return Err(wrong()) }; + match items.as_slice() { + [(k, Data::String(path))] if k == vectorcraft_js::FOLDER_REF_KEY => Ok(path), + _ => Err(wrong()), + } +} + +/// `document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, +/// fileNamePrefix?)`: `document.exportForScreens` of one format row into the folder, once for each +/// of the artboards, the assets and the whole document that `itemToExport` names. +fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + let folder = folder_path(arg(a, 1))?; + let (mut row, class) = format(arg(a, 2))?; + let options = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)); + let mut q = params(class, options)?; + if class.name == PNG24.name { + background(&mut q); + } + if class.name == PDF.name { + builtin_preset_name(h, &mut q); + } else if class.name != SVG.name { + size(&mut q)?; + } + row.extend(q); + let exports = exports(given(arg(a, 4)).filter(|d| !matches!(d, Data::Null)))?; + let prefix = match given(arg(a, 5)).filter(|d| !matches!(d, Data::Null)) { + None => None, + Some(Data::String(s)) if s.len() > MAX_TEXT_BYTES => return Err(HostError::Range("fileNamePrefix is too long".into())), + Some(Data::String(s)) => Some(s.clone()), + Some(_) => return Err(HostError::Type("fileNamePrefix must be a string".into())), + }; + let real = h.disk.borrow().folder_target(folder).map_err(|m| refused(m, folder))?; + let mut base = Map::new(); + base.insert("folder".into(), json!(plain(real))); + base.insert("folders".into(), json!("none")); + base.insert("formats".into(), json!([Value::Object(row)])); + if let Some(prefix) = prefix { + base.insert("prefix".into(), json!(prefix)); + } + for items in exports { + let mut p = base.clone(); + p.extend(items); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.exportForScreens", &Value::Object(p))))?; + } + Ok(Data::Undefined) +} + +/// The members these add to `Document`. +pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("exportForScreens", method(l, doc_export_for_screens))]) +} + +/// The classes: each `new Name()` gives a record with its `typename` and the defaults its reference +/// page gives. +pub(super) fn classes(link: &Link) -> Vec { + [&ITEM, &JPEG, &PNG24, &PNG8, &SVG, &PDF] + .into_iter() + .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 4f9358fb90..944a3dd5f6 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -127,6 +127,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; pub(crate) const READ_ONLY: &str = "Script file is read-only"; pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; +pub(crate) const NOT_FOLDER: &str = "Script folder is a file"; 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"; #[cfg(not(unix))] @@ -712,6 +713,17 @@ impl Disk { } } + /// The real path of the folder `path` that an export writes its files into, as a `File` + /// opened for writing there would reach it ([`Disk::target`]), or why it may not: a file is + /// not a folder. + pub(crate) fn folder_target(&self, path: &str) -> Result { + let real = self.target(path, true)?; + match std::fs::metadata(&real) { + Ok(m) if !m.is_dir() => Err(NOT_FOLDER), + _ => 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. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cad79e5046..cb2acdc530 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -181,6 +181,7 @@ mod script_include; mod script_io; mod script_run; mod script_save_open; +mod script_screens; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_screens.rs b/crates/engine/src/tests/script_screens.rs new file mode 100644 index 0000000000..c9bd000e1d --- /dev/null +++ b/crates/engine/src/tests/script_screens.rs @@ -0,0 +1,351 @@ +//! Exporting for screens from a script: `Document.exportForScreens`, `ExportForScreensItemToExport`, +//! the option classes and the file grants the folder 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-screens-{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() +} + +/// The names of the files in `dir`, sorted; none when it is not there. +fn names(dir: &Path) -> Vec { + let mut v: Vec = + std::fs::read_dir(dir).map(|r| r.map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); + v.sort(); + v +} + +/// A script that makes a document of two artboards with a rectangle on the first, in `dir`. +fn two_artboards(dir: &Path) -> String { + format!( + "Folder.userData; var dir = {}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n", + quoted(dir) + ) +} + +/// Each export type writes its format into the folder, a file per artboard of the item's range, at +/// the size the options' scale type gives. +#[test] +fn export_for_screens_writes_each_format_into_the_folder() { + let base = folder("formats"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let out = logged( + &mut s, + &base, + &format!( + "{}var one = new ExportForScreensItemToExport(); one.artboards = '1';\n\ + vc.log([one.typename, new ExportForScreensItemToExport().artboards, new ExportForScreensOptionsJPEG().scaleTypeValue]);\n\ + d.exportForScreens(new Folder(dir + '/jpg'), ExportForScreensType.SE_JPEG100, undefined, one);\n\ + var p = new ExportForScreensOptionsPNG24(); p.scaleType = ExportForScreensScaleType.SCALEBYFACTOR; p.scaleTypeValue = 2;\n\ + d.exportForScreens(new Folder(dir + '/png'), ExportForScreensType.SE_PNG24, p);\n\ + var w = new ExportForScreensOptionsPNG8(); w.scaleType = ExportForScreensScaleType.SCALEBYWIDTH; w.scaleTypeValue = 50;\n\ + d.exportForScreens(new Folder(dir + '/png8'), ExportForScreensType.SE_PNG8, w, one);\n\ + var r = new ExportForScreensOptionsJPEG(); r.scaleType = ExportForScreensScaleType.SCALEBYRESOLUTION; r.scaleTypeValue = 144;\n\ + d.exportForScreens(new Folder(dir + '/ppi'), ExportForScreensType.SE_JPEG20, r, one);\n\ + d.exportForScreens(new Folder(dir + '/svg'), ExportForScreensType.SE_SVG);\n\ + d.exportForScreens(new Folder(dir + '/pdf'), ExportForScreensType.SE_PDF, new ExportForScreensPDFOptions(), one);", + two_artboards(&dir) + ), + ); + assert_eq!(out[0], json!(["ExportForScreensItemToExport", "all", 1])); + let size = |sub: &str| { + let files = names(&dir.join(sub)); + let image = image::open(dir.join(sub).join(&files[0])).unwrap(); + (files, image.width(), image.height()) + }; + let (jpg, w, h) = size("jpg"); + assert!(jpg.len() == 1 && jpg[0].ends_with(".jpg"), "one artboard: {jpg:?}"); + assert_eq!((w, h), (200, 100), "a pixel per point at 1x"); + let (png, w, h) = size("png"); + assert!(png.len() == 2 && png.iter().all(|n| n.ends_with("@2x.png")), "both artboards at 2x: {png:?}"); + assert_eq!((w, h), (400, 200), "{png:?}"); + let (png8, w, h) = size("png8"); + assert_eq!(png8.len(), 1, "{png8:?}"); + assert_eq!((w, h), (50, 25), "50 pixels wide, in proportion"); + let (_, w, h) = size("ppi"); + assert_eq!((w, h), (400, 200), "144 ppi is two pixels per point"); + let svg = names(&dir.join("svg")); + assert!(svg.len() == 2 && svg.iter().all(|n| n.ends_with(".svg")), "{svg:?}"); + let pdf = names(&dir.join("pdf")); + assert_eq!(pdf.len(), 1, "{pdf:?}"); + assert!(std::fs::read(dir.join("pdf").join(&pdf[0])).unwrap().starts_with(b"%PDF")); + assert_eq!(s.active().unwrap().path, None, "the export leaves the document's file as it is"); + let _ = std::fs::remove_dir_all(base); +} + +/// Without options, an export writes what an untouched new options object of its class gives. +#[test] +fn omitted_options_are_a_new_options_objects_defaults() { + let base = folder("defaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let types = [ + ("SE_JPEG80", "ExportForScreensOptionsJPEG"), + ("SE_PNG24", "ExportForScreensOptionsPNG24"), + ("SE_PNG8", "ExportForScreensOptionsPNG8"), + ("SE_SVG", "ExportForScreensOptionsWebOptimizedSVG"), + ]; + let calls: String = types + .iter() + .map(|(t, c)| { + format!( + "d.exportForScreens(new Folder(dir + '/{t}-a'), ExportForScreensType.{t});\n\ + d.exportForScreens(new Folder(dir + '/{t}-b'), ExportForScreensType.{t}, new {c}());\n" + ) + }) + .collect(); + logged(&mut s, &base, &format!("{}{calls}", two_artboards(&dir))); + for (t, _) in types { + let (a, b) = (dir.join(format!("{t}-a")), dir.join(format!("{t}-b"))); + assert!(names(&a) == names(&b) && names(&a).len() == 2, "{t}: {:?} {:?}", names(&a), names(&b)); + for n in names(&a) { + assert!(std::fs::read(a.join(&n)).unwrap() == std::fs::read(b.join(&n)).unwrap(), "{t}: {n} differs"); + } + } + let _ = std::fs::remove_dir_all(base); +} + +/// `itemToExport` exports the artboards of its range, its assets and the whole document, each that +/// it names; one that names nothing throws and writes nothing. +#[test] +fn item_to_export_picks_artboards_assets_and_the_document() { + let base = folder("items"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + &format!( + "{}var ids = vc.run('assets.add', {{name: 'Logo', multiple: false}}).assets;\n\ + var a = new ExportForScreensItemToExport(); a.artboards = ''; a.assets = ids;\n\ + d.exportForScreens(new Folder(dir + '/assets'), ExportForScreensType.SE_SVG, undefined, a);\n\ + var whole = new ExportForScreensItemToExport(); whole.artboards = ''; whole.document = true;\n\ + d.exportForScreens(new Folder(dir + '/document'), ExportForScreensType.SE_PNG24, undefined, whole);\n\ + var both = new ExportForScreensItemToExport(); both.assets = ids; both.artboards = '2';\n\ + d.exportForScreens(new Folder(dir + '/both'), ExportForScreensType.SE_SVG, undefined, both);", + two_artboards(&dir) + ), + ); + assert_eq!(names(&dir.join("assets")), ["Logo.svg"]); + let whole = names(&dir.join("document")); + assert_eq!(whole.len(), 1, "{whole:?}"); + let image = image::open(dir.join("document").join(&whole[0])).unwrap(); + let (w, h) = (image.width(), image.height()); + assert!((50..60).contains(&w) && (20..30).contains(&h), "the bounds of the document's art, not an artboard: {w}x{h}"); + let both = names(&dir.join("both")); + assert!(both.len() == 2 && both.contains(&"Logo.svg".to_string()), "artboard 2 and the asset: {both:?}"); + for empty in ["''", "' '"] { + let e = failure( + &mut s, + &base, + &format!( + "Folder.userData; var i = new ExportForScreensItemToExport(); i.artboards = {empty};\n\ + app.activeDocument.exportForScreens(new Folder({} + '/none'), ExportForScreensType.SE_PNG24, undefined, i);", + quoted(&dir) + ), + ); + assert!(e.contains("nothing to export"), "{empty}: {e}"); + } + assert!(!dir.join("none").exists(), "an empty item writes nothing"); + let _ = std::fs::remove_dir_all(base); +} + +/// The prefix comes before each file's name, and a path character in it does not make a folder or +/// reach out of the export folder. +#[test] +fn a_file_name_prefix_stays_in_the_folder() { + let base = folder("prefix"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + &format!( + "{}d.exportForScreens(new Folder(dir + '/out'), ExportForScreensType.SE_SVG, undefined, undefined, 'web-');\n\ + d.exportForScreens(new Folder(dir + '/up'), ExportForScreensType.SE_SVG, undefined, undefined, '../x/');", + two_artboards(&dir) + ), + ); + let out = names(&dir.join("out")); + assert!(out.len() == 2 && out.iter().all(|n| n.starts_with("web-")), "{out:?}"); + let up = names(&dir.join("up")); + assert!(up.len() == 2 && up.iter().all(|n| n.starts_with("..-x-")), "{up:?}"); + assert!(std::fs::read_dir(dir.join("up")).unwrap().all(|e| e.unwrap().file_type().unwrap().is_file()), "no folder was made"); + assert!(!dir.join("x").exists(), "nothing is written beside the folder"); + let _ = std::fs::remove_dir_all(base); +} + +/// The folder goes through the script's file grants: one outside them, and a file given as the +/// folder, throw before anything is written. +#[test] +fn an_unwritable_folder_is_refused() { + let base = folder("refused"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("taken"), "kept").unwrap(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let outside = quoted(&base.join("outside/screens")); + let e = failure( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.exportForScreens(new Folder({outside}), ExportForScreensType.SE_PNG24);"), + ); + assert!(e.contains(DENIED), "{e}"); + assert!(!base.join("outside/screens").exists()); + let taken = quoted(&dir.join("taken")); + let e = + failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.exportForScreens(new Folder({taken}), ExportForScreensType.SE_PNG24);")); + assert!(e.contains(crate::script::files::NOT_FOLDER), "{e}"); + assert_eq!(std::fs::read_to_string(dir.join("taken")).unwrap(), "kept"); + assert_eq!(names(&base.join("outside")), Vec::::new()); + let _ = std::fs::remove_dir_all(base); +} + +/// Only a `Folder` the `Folder` class made (or a `File`) names the folder: an object made from +/// `Folder.prototype` throws a `TypeError`, and a `Folder` whose hidden path property a script set +/// keeps its own path. +#[test] +fn a_forged_folder_is_refused() { + let base = folder("forged"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let (inside, outside) = (quoted(&dir.join("in")), quoted(&base.join("outside/x"))); + let call = |f: &str| format!("Folder.userData; app.activeDocument.exportForScreens({f}, ExportForScreensType.SE_SVG);"); + let made = format!("(function () {{ var f = Object.create(Folder.prototype); f.__vcPath = {inside}; return f; }})()"); + let e = failure(&mut s, &base, &call(&made)); + assert!(e.contains("TypeError") && e.contains("needs a Folder"), "{e}"); + let moved = format!("(function () {{ var f = new Folder({outside}); f.__vcPath = {inside}; return f; }})()"); + let e = failure(&mut s, &base, &call(&moved)); + assert!(e.contains(DENIED), "{e}"); + assert!(!dir.join("in").exists() && !base.join("outside/x").exists(), "nothing is written"); + logged(&mut s, &base, &call(&format!("new File({inside})"))); + assert_eq!(names(&dir.join("in")).len(), 1, "a File names the folder at its path"); + let _ = std::fs::remove_dir_all(base); +} + +/// Bad arguments throw before anything is written. +#[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 Folder({})", quoted(&dir.join("x"))); + let e = "app.activeDocument.exportForScreens"; + let long = "a".repeat(300); + let cases: Vec<(String, &str)> = vec![ + (format!("{e}('x', ExportForScreensType.SE_PNG24);"), "needs a Folder"), + (format!("{e}({f}, 'SE_PNG24');"), "ExportForScreensType"), + (format!("{e}({f}, ExportType.PNG24);"), "ExportForScreensType"), + (format!("{e}({f}, ExportForScreensType.SE_PNG24, new ExportForScreensOptionsJPEG());"), "ExportForScreensOptionsPNG24"), + ( + format!("{e}({f}, ExportForScreensType.SE_SVG, {{typename: 'ExportForScreensOptionsWebOptimizedSVG', svgMinified: true}});"), + "has no option svgMinified", + ), + (format!("var o = new ExportForScreensOptionsJPEG(); o.progressiveScan = 6; {e}({f}, ExportForScreensType.SE_JPEG50, o);"), "from 3 to 5"), + (format!("var o = new ExportForScreensOptionsPNG8(); o.colorCount = 1; {e}({f}, ExportForScreensType.SE_PNG8, o);"), "from 2 to 256"), + (format!("var o = new ExportForScreensOptionsPNG8(); o.matteColor = 1; {e}({f}, ExportForScreensType.SE_PNG8, o);"), "not available yet"), + (format!("var o = new ExportForScreensOptionsPNG24(); o.scaleTypeValue = 0; {e}({f}, ExportForScreensType.SE_PNG24, o);"), "above 0"), + ( + format!("var o = new ExportForScreensOptionsPNG24(); o.scaleTypeValue = 100; {e}({f}, ExportForScreensType.SE_PNG24, o);"), + "from 0.01 to 64", + ), + ( + format!( + "var o = new ExportForScreensOptionsPNG24(); o.scaleType = ExportForScreensScaleType.SCALEBYRESOLUTION; o.scaleTypeValue = 5000; {e}({f}, ExportForScreensType.SE_PNG24, o);" + ), + "from 0.72 to 4608", + ), + ( + format!("var o = new ExportForScreensOptionsPNG24(); o.scaleType = 'SCALEBYWIDTH'; {e}({f}, ExportForScreensType.SE_PNG24, o);"), + "ExportForScreensScaleType", + ), + ( + format!("var o = new ExportForScreensOptionsPNG24(); o.antiAliasing = true; {e}({f}, ExportForScreensType.SE_PNG24, o);"), + "AntiAliasingMethod", + ), + ( + format!("var o = new ExportForScreensOptionsWebOptimizedSVG(); o.svgId = SVGFontType.SVGFONT; {e}({f}, ExportForScreensType.SE_SVG, o);"), + "SVGIdType", + ), + (format!("var o = new ExportForScreensPDFOptions(); o.pdfPreset = '{long}'; {e}({f}, ExportForScreensType.SE_PDF, o);"), "255 bytes"), + (format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, {{artboards: '1'}});"), "ExportForScreensItemToExport"), + (format!("var i = new ExportForScreensItemToExport(); i.artboards = '2-1'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), "range"), + ( + format!("var i = new ExportForScreensItemToExport(); i.artboards = 0; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "whole number from 1", + ), + ( + format!("var i = new ExportForScreensItemToExport(); i.assets = 3; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "array of asset ids", + ), + ( + format!("var i = new ExportForScreensItemToExport(); i.assets = [1.5]; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "not an asset id", + ), + ( + format!("var i = new ExportForScreensItemToExport(); i.document = 'yes'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "true or false", + ), + ( + format!("var i = new ExportForScreensItemToExport(); i.artboard = '1'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), + "has no option artboard", + ), + (format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, undefined, 5);"), "fileNamePrefix must be a string"), + (format!("var i = new ExportForScreensItemToExport(); i.artboards = '3'; {e}({f}, ExportForScreensType.SE_PNG24, undefined, i);"), "range"), + ]; + for (case, wanted) in &cases { + let e = failure(&mut s, &base, &format!("Folder.userData; {case}")); + assert!(e.contains(wanted), "{case}: {e}"); + } + assert!(!dir.join("x").exists(), "nothing was written"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 71a4191fae..cdf92819be 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,6 +39,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("Document.prototype.exportForScreens", "app.activeDocument.exportForScreens(f, ExportForScreensType.SE_PNG24);", "filesWritten"), ("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"), ]; @@ -155,13 +156,28 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of exporting for screens. + ( + "", + "AntiAliasingMethod ExportForScreensScaleType ExportForScreensType JPEGCompressionMethodType RasterImageLocation \ + SVGCSSPropertyLocation SVGFontType SVGIdType", + ), + ("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"), + ("ExportForScreensScaleType.", "SCALEBYFACTOR SCALEBYHEIGHT SCALEBYRESOLUTION SCALEBYWIDTH"), + ("ExportForScreensType.", "SE_JPEG100 SE_JPEG20 SE_JPEG50 SE_JPEG80 SE_PDF SE_PNG24 SE_PNG8 SE_SVG"), + ("JPEGCompressionMethodType.", "BASELINEOPTIMIZED BASELINESTANDARD PROGRESSIVE"), + ("RasterImageLocation.", "EMBED LINK PRESERVE"), + ("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"), + ("SVGFontType.", "OUTLINEFONT SVGFONT"), + ("SVGIdType.", "SVGIDMINIMAL SVGIDREGULAR SVGIDUNIQUE"), ]; /// The classes the host adds with nothing but a prototype and its constructor: the page item types /// and the save and export option classes. const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \ - ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions"; + ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions ExportForScreensItemToExport ExportForScreensOptionsJPEG \ + ExportForScreensOptionsPNG24 ExportForScreensOptionsPNG8 ExportForScreensOptionsWebOptimizedSVG ExportForScreensPDFOptions"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 3b5a21ca8b..3387ad1e00 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -97,15 +97,21 @@ 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. + /// it, or a `Folder` the `Folder` class made, as [`folder_ref`] gives one; `None` for any other + /// object, one made with `Object.create(File.prototype)` or `Object.create(Folder.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) { + let key = if o.proto == Some(c.file_proto) { + FILE_REF_KEY + } else if o.proto == Some(c.folder_proto) { + FOLDER_REF_KEY + } else { 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()))])), + Class::FsEntry(s) => Some(crate::Data::Object(vec![(key.to_string(), crate::Data::String(s.to_rust_string()))])), _ => None, }) } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index e31a8dff9e..60e6c28e06 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -263,11 +263,14 @@ 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`]). + // A `File` or a `Folder` reads as its path ([`crate::FILE_REF_KEY`], [`crate::FOLDER_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); + let len = match &file { + Data::Object(items) => items.iter().map(|(_, v)| if let Data::String(p) = v { p.len() } else { 0 }).sum(), + _ => 0, + }; self.charge_reading(r, len.saturating_mul(3).saturating_add(2))?; return Ok(file); } diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 7ed0a20efd..e1d2e87c57 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -74,8 +74,10 @@ pub(crate) const REFLECT: &str = "reflect"; // The roots of the document model: https://ai-scripting.docsforadobe.dev/jsobjref/Application/ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", "selection"]; -// Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ -pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +// Document methods that write the file they are given, or files in the folder they are given: +// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and +// https://www.indesignjs.de/indesignapi/illustrator/Document.html (exportForScreens) +pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs", "exportForScreens"]; // The save option of `Document.close` that saves the document to its own file: // https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 97b36d2b2c..eedbd638c7 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -543,6 +543,21 @@ fn save_as_and_export_file_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// A document's `exportForScreens` writes files into the folder it is given, called directly or by +/// its name in brackets; an object of the script's own that defines it writes nothing. +#[test] +fn export_for_screens_writes_files() { + let r = report(concat!( + "var dir = new Folder(p);\n", + "app.activeDocument.exportForScreens(dir, ExportForScreensType.SE_PNG24);\n", + "documents[0]['exportForScreens'](dir, ExportForScreensType.SE_SVG);\n", + "var local = {exportForScreens: function () {}};\n", + "local.exportForScreens(dir);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3][..])]); +} + /// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in /// brackets, as a string or through a variable; closing without it, and the other save options, /// write nothing. diff --git a/docs/gaps.md b/docs/gaps.md index fad8ae8dba..451bb1f782 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -814,7 +814,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, and save, export and open documents with - `Document.saveAs`, `Document.exportFile` and `app.open`, read a document's `fullName`, `path` and `saved`, and + `Document.saveAs`, `Document.exportFile`, `Document.exportForScreens` and `app.open`, read a document's `fullName`, `path` and `saved`, and close it with `Document.close`. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and diff --git a/docs/mcp.md b/docs/mcp.md index e45b156a6b..17118c0b91 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2589,7 +2589,7 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File - object; a document's `saveAs` or `exportFile` counts too, and so does `SaveOptions.SAVECHANGES` wherever the script + object; a document's `saveAs`, `exportFile` or `exportForScreens` counts too, and so does `SaveOptions.SAVECHANGES` wherever the script reads it, since `close` given it saves the document to its file), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, @@ -2846,6 +2846,44 @@ app through the global object `vc`, and writes to the Script Console and runs ot and leaves the document open when the document has no file (a converted or recovered document included); and `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot show the prompt. A bad value throws an error before anything is written. +- `Document.exportForScreens(exportFolder, exportFormat, options?, itemToExport?, fileNamePrefix?)` runs + `document.exportForScreens` with one format row into `exportFolder`, a `Folder` (or a `File`, read as the folder at + its path) (https://www.indesignjs.de/indesignapi/illustrator/Document.html). `exportFormat` is an + `ExportForScreensType` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html): `SE_JPEG100`, + `SE_JPEG80`, `SE_JPEG50` and `SE_JPEG20` write JPEG at a quality of 100, 80, 50 and 20 and take + `new ExportForScreensOptionsJPEG()`; `SE_PNG24` takes `new ExportForScreensOptionsPNG24()`; `SE_PNG8` takes + `new ExportForScreensOptionsPNG8()`; `SE_SVG` takes `new ExportForScreensOptionsWebOptimizedSVG()`; and `SE_PDF` + takes `new ExportForScreensPDFOptions()` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsJPEG.html, + https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG24.html, + https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG8.html, + https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsWebOptimizedSVG.html, + https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensPDFOptions.html). The raster classes map + `antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR`, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, + `SCALEBYRESOLUTION` in ppi); JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5); + PNG24 maps `transparency`, `backgroundBlack` and `interlaced`; PNG8 maps `colorCount` (2 to 256), `interlaced`, + `matte` and `transparency`. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`, + `rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`, and the PDF class maps `pdfPreset` (at most 255 + bytes; a name in square brackets names a built-in preset as `PDFSaveOptions.pDFPreset` does). `itemToExport` is a + `new ExportForScreensItemToExport()` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html) + with `artboards` (`all`, the default, a range of artboard numbers such as `1-3, 5`, or `""` for none), `assets` (a + list of asset ids, as `assets.list` gives them) and `document` (false by default). `fileNamePrefix` goes before each + file's name. The enumerations `ExportForScreensType`, `ExportForScreensScaleType`, `AntiAliasingMethod`, + `JPEGCompressionMethodType`, `RasterImageLocation`, `SVGCSSPropertyLocation`, `SVGFontType` and `SVGIdType` hold + strings such as `"ExportForScreensType.SE_PNG24"`. + VectorCraft's own rules: the folder is checked as a `File` opened for writing in it is checked, before the command + runs: a folder outside the script's folders throws `Script file access denied`, and a file throws `Script folder is + a file`. The command writes only where the script's folders allow. The files go into the folder without + sub-folders, each named `.` as `document.exportForScreens` names them (`@2x` + after a raster file at twice the size); a character a file name may not hold, `/` and `\` included, is written as + `-` in the prefix. The export keeps its settings in the document, as an export from the dialog does. The artboards, + the assets and, with `document` true, the bounds of the whole document's art (a PDF of every artboard) are each + their own export, in that order: when a later one throws, the files of the earlier ones stay written. An + `itemToExport` that names nothing throws `nothing to export`. A scale factor is from 0.01 to 64 and a resolution + from 0.72 to 4608 ppi. `RasterImageLocation.PRESERVE`, the default, embeds raster images as `EMBED` does, and + `SVGFontType.SVGFONT`, the default, writes text as SVG text elements. A listed option that is not mapped + (`matteColor`) is accepted at its default and throws at any other value, a property the pages do not list throws an + error that names it, an omitted options object takes the defaults a new one holds, and an options object of + another class throws. 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 75a99d9283..b6adf11cbf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1035,6 +1035,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). 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, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. + - Scripts: `Document.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_screens.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From bc99687e5e03b8447ca03d0b99593721df979036 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 10:09:45 -0800 Subject: [PATCH 02/27] Scripts: selection, opacity, PageItems and option checks follow review - Document.selection = undefined (an index past the end of pageItems) throws "this is not a page item" and keeps the selection; null and [] still clear it. Repeated items are found with a set instead of a scan of the list. - Assigning a page item the opacity it already has runs no command, unless a graph keeps another opacity for the item's series or kind. - PageItems.toString() on a stale collection throws as typename does. - PageItem.controlBounds throws "not available yet" instead of returning the visible bounds, which leave out the direction handles. - A host class member that is not available hides an available member of the same name in the class it descends from, for hasOwnProperty and propertyIsEnumerable. - script.check: a call of another method of an object literal with its own saveAs or exportFile (local.install()), and a property assignment that names the variable (this.local = d, $.global['local'] = d), end the exemption, so a later saveAs counts as a file write. - docs/mcp.md: SCALEBYFACTOR is a multiplier from 0.01 to 64, and SCALEBYRESOLUTION takes 0.72 to 4608 ppi. The write_encoded doc comment limits the all-or-nothing case to paths the access check refuses. - Tests: the authored error-origin case throws the Window text, the getIsFileOpen paths are JSON string literals, the folder saveAs case looks up its grant and expects "Script file is not a regular file", the selection case catches the error inside the script, and the close case checks that the file changed. --- crates/engine/src/cmd/fileio/export_names.rs | 5 ++- crates/engine/src/script/dom.rs | 25 +++++++---- crates/engine/src/tests/script_dom.rs | 45 ++++++++++++++----- crates/engine/src/tests/script_run.rs | 2 +- crates/engine/src/tests/script_save_open.rs | 14 ++++-- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/host_classes.rs | 19 ++++---- crates/js/src/host_tests.rs | 33 ++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 44 ++++++++++++++++-- crates/scriptcheck/src/tests.rs | 23 ++++++++++ docs/mcp.md | 12 ++--- 11 files changed, 178 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/fileio/export_names.rs b/crates/engine/src/cmd/fileio/export_names.rs index 48a8c828ab..dfa1479a9d 100644 --- a/crates/engine/src/cmd/fileio/export_names.rs +++ b/crates/engine/src/cmd/fileio/export_names.rs @@ -74,8 +74,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`. Every path is -/// checked against the file access in force before the first file is written, so a refused path -/// writes none of them. +/// checked against the file access in force before the first file is written, so a path that +/// check refuses writes none of them. A write that fails after that check leaves the files +/// written before it. 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()); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 104511f055..337da8c093 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1298,15 +1298,17 @@ fn selection_of(h: &Host, uid: u64) -> Answer { } /// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or -/// `[]`. Every one must be an object of that document that can be selected. +/// `[]`. Every one must be an object of that document that can be selected; `undefined`, such as an +/// index past the end of `pageItems`, is not a page item. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); let locks = d.locked_artboards(); @@ -1321,7 +1323,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { Ok(text("PageItems")) } +fn items_to_string(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("[PageItems]")) +} + fn items_parent(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) @@ -1584,9 +1591,9 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - // A value the getter reports for the item's opacity sends the opacity it has, and - // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still - // replaces the one the graph keeps for its series or kind. + // A value the getter reports for the item's opacity runs no command, unless the item is a graph + // mark or label whose graph keeps another opacity for its series or kind: the opacity it has + // then replaces that one. // The opacity the item already has may be assigned while its layer is hidden or locked, unless // it would still replace the opacity a graph keeps for the item's series or kind. let item = this_item(h, a)?; @@ -1601,7 +1608,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if now.is_none() || keeps_other { refuse_in_closed_layer(h, item)?; } - set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) + set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { @@ -2154,7 +2161,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("index", method(l, items_index)), ("getByName", method(l, items_by_name)), ("removeAll", method(l, items_remove_all)), - ("toString", class_text("PageItems")), + ("toString", method(l, items_to_string)), ]), Some(function(l, items_at)), )); @@ -2174,7 +2181,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), @@ -2187,6 +2193,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), [ "artworkKnockout", "blendingMode", + "controlBounds", "isIsolated", "layer", "pixelAligned", diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4e705538d9..cb2cf5a63c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -266,8 +266,9 @@ fn assigning_the_reported_opacity_changes_nothing() { let (mut s, a, _) = doc(); s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap(); let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); - let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;"); - assert_eq!(out, vec![json!(33.3333)]); + let r = run(&mut s, "var i = app.activeDocument.pageItems[1]; vc.log(i.opacity); i.opacity = i.opacity;").unwrap(); + assert_eq!(r["log"], json!([33.3333])); + assert_eq!(r["slowestCommands"], json!([]), "no command runs for the opacity the item has"); assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); assert_eq!(undo_steps(&s), steps); // A value close to the reported one but not equal to it is still applied. @@ -282,8 +283,14 @@ fn assigning_the_reported_opacity_changes_nothing() { fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap(); - let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); - assert!(e.contains("Cannot select PathItem"), "{e}"); + // The script catches the error and reads the selection before the run ends. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, e = '';\ + try { d.selection = [p[0], p[1]]; } catch (x) { e = String(x); } vc.log(e); vc.log(d.selection.length);", + ); + assert!(out[0].as_str().is_some_and(|e| e.contains("Cannot select PathItem")), "{out:?}"); + assert_eq!(out[1], json!(0)); assert!(s.active().unwrap().selection.objects.is_empty()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log( @@ -295,6 +302,13 @@ fn selection_assignment_is_atomic_across_invalid_items() { ); assert_eq!(out, vec![json!(true), json!(2), json!(true), json!(1), json!(1)]); assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // An index past the end gives `undefined`, which is not a page item: the selection stays. + let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];"); + assert!(e.contains("this is not a page item"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + // A list with an item repeated thousands of times selects it once. + log(&mut s, "var d = app.activeDocument, p = d.pageItems, l = []; for (var i = 0; i < 5000; i++) l.push(p[0], p[1]); d.selection = l;"); + assert_eq!(s.active().unwrap().selection.objects, vec![b, a]); // An item of another document cannot be selected here. s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let e = failure(&mut s, "app.activeDocument.selection = app.documents[0].pageItems[0];"); @@ -680,9 +694,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); - for (member, message) in - [("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")] - { + for (member, message) in [ + ("d.typename", "Stale document"), + ("d.parent", "Stale document"), + ("p.typename", "Stale document"), + ("p.toString()", "Stale document"), + ("l.typename", "Stale"), + ] { let e = failure(&mut s, &format!("#targetengine keep\n{member};")); assert!(e.contains(message), "{member}: {e}"); } @@ -875,9 +893,12 @@ fn a_startup_preset_alone_gives_its_first_size() { #[test] fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); - for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].blendingMode;", + "app.activeDocument.pageItems[0].uuid = 'x';", + "app.activeDocument.pageItems[0].rotate(5);", + "app.activeDocument.pageItems[0].controlBounds;", + ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); @@ -1345,8 +1366,8 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let (p, other) = (json!(path.to_string_lossy()), json!(format!("{}.other", path.to_string_lossy()))); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 188656a672..e311f41853 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -182,7 +182,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), ("throw 'invalid array length';", "thrown", "invalid array length", "script"), - ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + ("throw 'ReferenceError: Window is not defined';", "thrown", "ReferenceError: Window is not defined", "script"), ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index a3f937a244..15e64aecc2 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -286,8 +286,8 @@ fn save_as_export_file_and_open_refuse_paths_outside_the_grants() { } 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}"); + let e = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir))); + assert!(e.contains("Script file is not a regular file"), "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()); @@ -716,12 +716,18 @@ fn closing_with_save_changes_keeps_the_documents_format() { &base, &format!( "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ - vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());\n\ - vc.run('shape.rectangle', {{x: 20, y: 20, width: 5, height: 5}}); d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);" + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}}); d.saveAs(new File({d} + '/p.svg'), new PDFSaveOptions());" ), ); + let saved = std::fs::read(dir.join("p.svg")).unwrap_or_default(); + logged( + &mut s, + &base, + "Folder.userData; var d = app.activeDocument; vc.run('shape.rectangle', {x: 20, y: 20, width: 5, height: 5}); d.close(SaveOptions.SAVECHANGES);", + ); let bytes = std::fs::read(dir.join("p.svg")).unwrap_or_default(); assert!(bytes.starts_with(b"%PDF"), "the save on close keeps the PDF format"); + assert_ne!(bytes, saved, "the close wrote the second rectangle to the file"); assert!(s.documents().is_empty()); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index cdf92819be..b0ba62e31a 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "PageItem.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \ - controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ + controlBounds controlBounds= duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \ left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \ position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags tags= toString top top= transform \ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 206f781ef3..cf26a42490 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -25,11 +25,12 @@ //! //! `hasOwnProperty` and `propertyIsEnumerable` are true on an object of a host class for each //! member of its class and of the classes it descends from, apart from the members that are not -//! available yet ([`HostMember::Unavailable`]). `for`-`in` lists the properties among those members, +//! available yet ([`HostMember::Unavailable`]). A member a class declares, available or not, hides +//! the member of that name in the classes it descends from. `for`-`in` lists the properties among those members, //! and not the methods. `Object.keys`, `Object.getOwnPropertyNames` and //! `Object.getOwnPropertyDescriptor` do not report the members. -use std::collections::HashSet; +use std::collections::HashMap; use std::rc::Rc; use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key}; @@ -89,8 +90,9 @@ pub(crate) struct Entry { family: u32, /// The class this class's prototype inherits from, as an index into the realm's classes. parent: Option, - /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones. - own: Rc>, + /// The names of the members the class declares, each with whether `hasOwnProperty` reports it: + /// every member but the unavailable ones. + own: Rc>, } impl Entry { @@ -143,14 +145,15 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { impl Interp { /// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host - /// class, and `k` names an available member of that class or of a class it descends from. + /// class, and the closest of that class and the classes it descends from that declares `k` + /// declares it as available. pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult { let Class::Host(h) = &self.object(id)?.class else { return Ok(false) }; let mut class = Some(h.class); while let Some(c) = class { let Some(e) = self.host_classes.get(c as usize) else { return Err(Abrupt::Internal("host class out of range".into())) }; - if e.own.contains(k) { - return Ok(true); + if let Some(available) = e.own.get(k) { + return Ok(*available); } class = e.parent; } @@ -307,7 +310,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect(); + let members = class.members.iter().map(|(name, m)| (key(name), !matches!(m, HostMember::Unavailable(_)))).collect(); i.host_classes.push(Entry { name: class.name.as_str().into(), proto, diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 8213e989ae..bdcd905584 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -756,6 +756,39 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() { ); } +#[test] +fn a_member_a_class_declares_hides_the_one_its_parent_declares() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let base = HostClass { + name: "Base".into(), + parent: None, + members: vec![ + ("size".to_string(), HostMember::Get(value.clone())), + ("later".to_string(), HostMember::Unavailable(missing.clone())), + ("kept".to_string(), HostMember::Get(value.clone())), + ], + index: None, + construct: None, + }; + let leaf = HostClass { + name: "Leaf".into(), + parent: Some("Base".into()), + members: vec![("size".to_string(), HostMember::Unavailable(missing)), ("later".to_string(), HostMember::Get(value))], + index: None, + construct: None, + }; + r.define_host_classes(vec![base, leaf], vec![("it".into(), host_ref("Leaf", &[1.0]))]).unwrap(); + r.start( + "var read; try { it.size; read = 'read'; } catch (e) { read = 'threw'; }\ + [it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), read, it.hasOwnProperty('later'),\ + it.propertyIsEnumerable('later'), it.hasOwnProperty('kept')].join()", + ) + .unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,threw,true,true,true".into())); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 48303c173e..f6431ad2ba 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -300,8 +300,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// `(` after a name: a call. - fn call(&mut self, line: Option) { + /// What the call whose `(` is the current token reaches. + fn classify_call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") @@ -373,7 +373,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or /// `exportFile` is assigned: another name may hold its object, or its methods may change, so its /// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`, - /// `local[k] = w`, `delete local.saveAs`). + /// `local[k] = w`, `delete local.saveAs`). A property assignment whose name is such a variable's + /// (`this.local = d`, `$.global['local'] = d`) may give the variable a new value through the global + /// object, so its methods are no longer known either. fn writer_use(&mut self, t: &Sig<'s>) { let [h0, h1, h2, h3] = self.h; let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); @@ -403,6 +405,42 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if let Some(name) = escaped { self.writers.remove(name); } + if changes { + let rebound = if is(h1, ".") { + h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) + } else if is(h0, "]") && is(h2, "[") { + h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 256)) + } else { + None + }; + if let Some(name) = rebound { + self.writers.remove(&name); + } + } + } + + /// `(` after a name: a call ([`Self::classify_call`]). A call of a variable of + /// [`Analyzer::writers`]'s method other than the `saveAs` or `exportFile` its literal defines + /// (`local.install()`, `local['install']()`) may replace the object's methods through `this`, so + /// after the call they are no longer known. + fn call(&mut self, line: Option) { + let [h0, h1, h2, h3] = self.h; + let bits = self.writer_bits(h2, h3); + let receiver = if is(h1, ".") && bits != 0 && h0.is_some_and(|s| s.kind == T::Ident && !Self::defines(bits, s.text)) { + h2 + } else if is(h0, "]") + && is(h2, "[") + && self.index_receiver != 0 + && h1.is_some_and(|s| s.kind == T::Str && !Self::defines(self.index_receiver, &unquote(s.text, 32))) + { + h3 + } else { + None + }; + self.classify_call(line); + if let Some(r) = receiver { + self.writers.remove(r.text); + } } /// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called. diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index c118128eec..637d1371ce 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -650,6 +650,29 @@ fn a_changed_or_shared_own_save_as_writes_a_file() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[11, 12, 13, 14, 15, 16, 18, 19, 21, 22][..])); } +/// A call of another method of such an object may replace its `saveAs` through `this`, and a property +/// assignment that names the variable (`this.local = d`) may give it another value through the global +/// object: after either, its `saveAs` writes the file again. +#[test] +fn a_method_call_or_a_global_property_ends_the_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}, install: function () { this.saveAs = app.activeDocument.saveAs; }};\n", + "var b = {saveAs: function () {}, install: function () {}};\n", + "var c = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n", + "a.saveAs(f); a.install();\n", + "b['install']();\n", + "this.c = app.activeDocument;\n", + "$.global['e'] = app.activeDocument;\n", + "g.saveAs(f); g.saveAs(f);\n", + "a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + "e.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment diff --git a/docs/mcp.md b/docs/mcp.md index 41869aadf9..bfd486709e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2720,8 +2720,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to - 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, + 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, + `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs @@ -2788,8 +2788,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, - Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and - `app.beep`, throw an error that says they are not available yet when they are read or assigned. + Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.controlBounds`, + `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. `hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and @@ -2874,8 +2874,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsPNG8.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensOptionsWebOptimizedSVG.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensPDFOptions.html). The raster classes map - `antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR`, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, - `SCALEBYRESOLUTION` in ppi); JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5); + `antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR` as a multiplier from 0.01 to 64, so 2 doubles the + size, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, `SCALEBYRESOLUTION` in ppi from 0.72 to 4608); JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5); PNG24 maps `transparency`, `backgroundBlack` and `interlaced`; PNG8 maps `colorCount` (2 to 256), `interlaced`, `matte` and `transparency`. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`, `rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`, and the PDF class maps `pdfPreset` (at most 255 From 70e6f4e797632bedd375356085e8b264fc1f8a78 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:20:32 -0800 Subject: [PATCH 03/27] Save: a refused file in a save of several files is not given to the writer When the file access in force refuses one of the files a save writes, the save returns the access error before calling the writer, so a writer that does not check the file access itself writes none of the files. --- crates/engine/src/cmd/fileio/save.rs | 10 ++++------ crates/engine/src/tests/script_save_open.rs | 4 ++-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index cf00d4194a..08138a85ca 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,15 +1071,13 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. When one is refused, the save returns that error and `write` is not called, so + // none of the files is written, also by a writer that does not check the file access. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(e) = files.iter().find_map(|(p, _)| super::may_write(p).err()) { - write(p, bytes)?; - // A writer that does not check the file access writes none of the others. - return Err(super::may_write(p).err().unwrap_or_else(|| crate::EngineError::Other(format!("file access denied: {p}")))); + return Err(e); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 15e64aecc2..0c4efa0c58 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -208,7 +208,7 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() { } /// When the writer a save is given does not check the file access itself, a save of several files -/// still writes none of them after the refused one. +/// with a refused one gives none of them to the writer. #[test] fn a_refused_file_stops_a_save_whose_writer_does_not_check() { use crate::cmd::fileio::{SaveMode, save_job, save_plan}; @@ -247,7 +247,7 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() { }); assert!(r.is_err(), "{r:?}"); let refused = refused.unwrap(); - assert_eq!(written, std::slice::from_ref(&refused), "only the refused file went to the writer"); + assert!(written.is_empty(), "no file went to the writer: {written:?}"); let mut perms = std::fs::metadata(&refused).unwrap().permissions(); #[allow(clippy::permissions_set_readonly_false)] perms.set_readonly(false); From 60eb7e002be84c3a00599810f7f71f02bfc7b878 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:06:16 -0800 Subject: [PATCH 04/27] Scripts: exportForScreens numbers a file that an earlier item of the same call named Document.exportForScreens exports the artboards, the assets and the document that itemToExport names one after another into the folder. A later export now names its files around the names the earlier ones took, so an asset named as an artboard writes Logo-2.svg next to Logo.svg instead of writing over it. --- crates/engine/src/cmd/fileio.rs | 4 +-- crates/engine/src/cmd/fileio/screens.rs | 34 +++++++++++++++++++ .../src/script/dom/save_open/screens.rs | 16 +++++---- crates/engine/src/tests/script_screens.rs | 22 ++++++++++++ 4 files changed, 68 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 7aca68fd02..4830432047 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -112,8 +112,8 @@ pub use save::{ }; pub(crate) use screens::{ PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS, - check_settings as check_screen_settings, export as export_screens, safe_file_name, store_settings as store_screen_settings, - with_export_preset as with_screen_export_preset, + check_settings as check_screen_settings, export as export_screens, safe_file_name, sharing_names as sharing_screen_names, + store_settings as store_screen_settings, with_export_preset as with_screen_export_preset, }; pub use screens::{ PRESET_FILE_EXTS as SCREEN_EXPORT_PRESET_EXTS, PRESET_FILE_FORMAT as SCREEN_EXPORT_PRESET_FORMAT, PRESET_KEYS as SCREEN_EXPORT_PRESET_KEYS, diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 442f38e3cc..4ab1c492a1 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -638,6 +638,25 @@ fn fold(name: &str) -> String { .collect() } +thread_local! { + /// The [`fold`]ed names the exports run by [`sharing_names`] on this thread have taken so far. + static SHARED_NAMES: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// `f`, with every `document.exportForScreens` it runs on this thread naming its files around +/// the names the ones before it took, so a later export does not write over an earlier one's file +/// (it numbers its own: `-2`, `-3`…). +pub(crate) fn sharing_names(f: impl FnOnce() -> T) -> T { + let outer = SHARED_NAMES.with(|n| n.borrow_mut().replace(HashSet::new())); + let r = f(); + SHARED_NAMES.with(|n| *n.borrow_mut() = outer); + r +} + +/// The key the names taken by an earlier export are held under in [`Output::taken`]: no file of +/// this export has it. +const EARLIER_EXPORT: &str = "\0earlier export"; + /// The file names (and bytes) an export wrote, or the files it returns. #[derive(Default)] struct Output { @@ -1342,6 +1361,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> create_dir(dir)?; } let mut out = Output::default(); + // The names earlier exports of a [`sharing_names`] run took into the same files. + if !o.zip { + SHARED_NAMES.with(|n| { + for name in n.borrow().iter().flatten() { + out.taken.insert(name.clone(), EARLIER_EXPORT.to_string()); + } + }); + } // The notes on the options, then the encoders' notes for every file, each once. let mut notes: Vec = Vec::new(); for text in unused { @@ -1417,6 +1444,13 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> files += 1; } } + if !o.zip { + SHARED_NAMES.with(|n| { + if let Some(shared) = n.borrow_mut().as_mut() { + shared.extend(out.taken.keys().cloned()); + } + }); + } // A cancel that came while the last file was encoded returns no files. A folder export // without a ZIP has written every file by now, so it returns them. if o.zip || folder.is_none() { diff --git a/crates/engine/src/script/dom/save_open/screens.rs b/crates/engine/src/script/dom/save_open/screens.rs index f4008be1b6..c4cf253ecd 100644 --- a/crates/engine/src/script/dom/save_open/screens.rs +++ b/crates/engine/src/script/dom/save_open/screens.rs @@ -461,12 +461,16 @@ fn doc_export_for_screens(h: &Host, a: &[Data]) -> Answer { if let Some(prefix) = prefix { base.insert("prefix".into(), json!(prefix)); } - for items in exports { - let mut p = base.clone(); - p.extend(items); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.exportForScreens", &Value::Object(p))))?; - } - Ok(Data::Undefined) + // The artboards, the assets and the document are exported one after another into the folder: + // a later export numbers a file whose name an earlier one took instead of writing over it. + crate::cmd::fileio::sharing_screen_names(|| { + for items in exports { + let mut p = base.clone(); + p.extend(items); + exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.exportForScreens", &Value::Object(p))))?; + } + Ok(Data::Undefined) + }) } /// The members these add to `Document`. diff --git a/crates/engine/src/tests/script_screens.rs b/crates/engine/src/tests/script_screens.rs index c9bd000e1d..343feff945 100644 --- a/crates/engine/src/tests/script_screens.rs +++ b/crates/engine/src/tests/script_screens.rs @@ -195,6 +195,28 @@ fn item_to_export_picks_artboards_assets_and_the_document() { let _ = std::fs::remove_dir_all(base); } +/// An asset named as an artboard of the item's range gets a file of its own: the artboard's file +/// keeps its name and the asset's is numbered, in place of writing over it. +#[test] +fn an_asset_named_as_an_artboard_does_not_overwrite_its_file() { + let base = folder("clash"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + &format!( + "{}vc.run('artboard.setProps', {{artboards: [{{index: 0, name: 'Logo'}}]}});\n\ + var ids = vc.run('assets.add', {{name: 'Logo', multiple: false}}).assets;\n\ + var both = new ExportForScreensItemToExport(); both.artboards = '1'; both.assets = ids;\n\ + d.exportForScreens(new Folder(dir + '/both'), ExportForScreensType.SE_SVG, undefined, both);", + two_artboards(&dir) + ), + ); + assert_eq!(names(&dir.join("both")), ["Logo-2.svg", "Logo.svg"]); + let _ = std::fs::remove_dir_all(base); +} + /// The prefix comes before each file's name, and a path character in it does not make a folder or /// reach out of the export folder. #[test] From bee68ccd13acf2d747e0cd8a5e1f78ddf3e5502e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:01:18 -0800 Subject: [PATCH 05/27] Scripts: a saveAs that can replace itself, or a computed global key, ends the own-method exemption - A saveAs or exportFile in an object literal whose body uses `this` or the variable's own name may replace the object's methods when it runs, so the script check no longer counts it as the script's own method and reports its calls as file writes. - An assignment to a property of the global object under a key that is not one string literal (`$.global[key] = d`, `this['lo' + 'cal'] = d`) may rebind any variable, so the check forgets every own saveAs after it. - A save without a path that writes several files and is refused by the file access names the refused file by its file name, as the single-file save does, instead of its full path. --- crates/engine/src/cmd/fileio/save.rs | 23 +++++++++--- crates/scriptcheck/src/analyze.rs | 20 ++++++++++- crates/scriptcheck/src/analyze/features.rs | 19 +++++++++- crates/scriptcheck/src/tests.rs | 42 ++++++++++++++++++++++ 4 files changed, 97 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 08138a85ca..9fba907289 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -602,6 +602,10 @@ pub struct SaveJob { stamped: Option, /// The artboards also saved to files of their own (`separateArtboards`). boards: Vec, + /// Does a refusal by the file access name the refused file by its file name + /// ([`SaveJob::naming_refused_file`])? + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + names_refused_file: bool, } /// Writes the file at a path with what the filler it is given writes into it @@ -963,7 +967,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option Self { + self.names_refused_file = true; + self + } + /// The document when the job was made (what counts as saved once the file is written). pub(crate) fn snapshot(&self) -> &Arc { &self.snapshot @@ -1075,9 +1087,9 @@ impl SaveJob { // none of the files is written, also by a writer that does not check the file access. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some(e) = files.iter().find_map(|(p, _)| super::may_write(p).err()) + && let Some((p, e)) = files.iter().find_map(|(p, _)| super::may_write(p).err().map(|e| (p, e))) { - return Err(e); + return Err(if self.names_refused_file { super::access::naming_in_error(e, p) } else { e }); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { @@ -1239,9 +1251,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8]) /// A save command: plan, then write with the file system (a native file as it is encoded). pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result { let plan = save_plan(s, mode, p)?; - let job = save_job(s, plan)?; - let uid = s.doc()?.uid; let given = str_param(p, "path").is_some_and(|g| !g.is_empty()); + let job = save_job(s, plan)?; + let job = if given { job } else { job.naming_refused_file() }; + let uid = s.doc()?.uid; // Without a path, the files written are the document's own file and those beside it. let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| { super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) }) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index 4eaebc96ca..dda0f3c1c5 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -646,6 +646,11 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// The depths of the open `[` that index the global object (`$.global[`, `this[`, + /// `globalThis[`), the innermost last, up to [`crate::Limits::nesting`] of them. + global_indexes: Vec, + /// The last token was the `]` that closes an index of the global object. + global_index_closed: bool, /// This file or what the scan started with gives names values the analysis doesn't read /// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names. unsure: bool, @@ -726,6 +731,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { objects: vec![], closed: None, index_receiver: 0, + global_indexes: vec![], + global_index_closed: false, unsure: known.unsure || declared.unsure, own_names: HashSet::new(), scopes: vec![], @@ -1447,8 +1454,19 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing /// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the /// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on - /// (`{…} && d`), see the variable as it was. + /// (`{…} && d`), see the variable as it was. A `this` or the variable's own name inside the body + /// of such a function expression takes the method out as well: running it may replace the + /// object's methods (`{saveAs: function () { this.saveAs = d.saveAs; }}`). fn object_key(&mut self, t: &Sig<'s>, before: usize) { + if t.kind == T::Ident { + for o in self.objects.iter_mut().filter(|o| o.depth < before) { + if let Some((bit, Value::Body)) = o.value + && (t.text == "this" || t.text == o.name) + { + o.value = Some((bit, Value::Other)); + } + } + } if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) { o.step(t); } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index f6431ad2ba..70942a0986 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -375,9 +375,23 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`, /// `local[k] = w`, `delete local.saveAs`). A property assignment whose name is such a variable's /// (`this.local = d`, `$.global['local'] = d`) may give the variable a new value through the global - /// object, so its methods are no longer known either. + /// object, so its methods are no longer known either. An assignment to a property of the global + /// object under any other key (`$.global[key] = d`, `this['lo' + 'cal'] = d`) may give any such + /// variable a new value: no variable's methods are known after it. fn writer_use(&mut self, t: &Sig<'s>) { let [h0, h1, h2, h3] = self.h; + let global_index_closed = std::mem::take(&mut self.global_index_closed); + if t.is("[") { + let global = (word(h0, "global") && is(h1, ".") && word(h2, "$") && !member_mark(h3)) + || ((word(h0, "this") || word(h0, "globalThis")) && !member_mark(h1)); + if global && self.global_indexes.len() < self.acc.limits.nesting { + self.global_indexes.push(self.depth()); + } + } else if t.is("]") { + let depth = self.depth(); + self.global_index_closed = self.global_indexes.last() == Some(&(depth + 1)); + self.global_indexes.retain(|d| *d <= depth); + } let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); let key = t.is(":") && (is(h1, "{") || is(h1, ",")); @@ -415,6 +429,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { }; if let Some(name) = rebound { self.writers.remove(&name); + } else if global_index_closed { + // `$.global[key] = …`: the key may name any of them. + self.writers.clear(); } } } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 0adc738db2..28aec12789 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -673,6 +673,48 @@ fn a_method_call_or_a_global_property_ends_the_own_save_as() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13][..])); } +/// An assignment to a property of the global object under a key that is not one string literal may +/// give any such variable another value: after it, their `saveAs` writes the file again. One under a +/// string literal ends only the variable it names, and an index of another object ends none. +#[test] +fn a_computed_global_property_ends_every_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n", + "var rows = [];\n", + "rows[k] = 1; $.global['b'] = app.activeDocument;\n", + "a.saveAs(f);\n", + "$.global[key] = app.activeDocument;\n", + "a.saveAs(f);\n", + "var c = {saveAs: function () {}};\n", + "this['lo' + 'cal'] = app.activeDocument;\n", + "c.saveAs(f);\n", + "var h = {saveAs: function () {}};\n", + "globalThis[names[0]] = app.activeDocument;\n", + "h.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[7, 10, 13][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[7, 10, 13][..])]); +} + +/// A `saveAs` whose body uses `this` or the variable's own name may replace the object's methods +/// when it runs, so it is not the script's own and its calls write the file. A `this` in another +/// method's body leaves `saveAs` the script's own. +#[test] +fn an_own_save_as_that_may_replace_itself_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var doc = app.activeDocument;\n", + "var a = {saveAs: function () { this.saveAs = function (g) { doc.saveAs(g); }; }};\n", + "var b = {saveAs: function () { b.saveAs = w; }};\n", + "var c = {saveAs: function (g) { return g; }, install: function () { this.n = 1; }};\n", + "a.saveAs(f); a.saveAs(f);\n", + "b.saveAs(f);\n", + "c.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment From 210ba07347b0daa9204b4b5fe1559513fa336f2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:58:37 -0800 Subject: [PATCH 06/27] Scripts: a hoisted function that changes or shares a variable, a captured variable and a labelled var end the own-method exemption A function declared before the literal that assigns the variable's saveAs or hands the variable on, a function that calls the method on a variable it reads from outside, and a var statement after a label keep reporting the file write. --- crates/scriptcheck/src/analyze.rs | 13 +++- crates/scriptcheck/src/analyze/features.rs | 79 ++++++++++++++++------ crates/scriptcheck/src/tests.rs | 45 ++++++++++++ 3 files changed, 115 insertions(+), 22 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index dda0f3c1c5..bed249d6eb 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -637,6 +637,12 @@ struct Analyzer<'s, 'a, 'l> { /// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit /// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing. writers: HashMap, + /// The variables a function body read before any literal gave them methods, in a way that + /// changes or shares them ([`Analyzer::writer_use`]): the body may run after the literal (a + /// hoisted declaration), so the literal's methods are not the script's own. Each name has the + /// most function bodies that were open where it was read; a literal in a body with that many + /// open or more is unaffected, since it gives a variable of its own. + shared_early: HashMap, /// The object literals being assigned to a variable, the innermost last, up to /// [`crate::Limits::nesting`] of them. objects: Vec, @@ -646,6 +652,8 @@ struct Analyzer<'s, 'a, 'l> { /// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver /// that is not such a variable. index_receiver: u8, + /// Whether that receiver's own methods hold at this place ([`Analyzer::stable`]). + index_stable: bool, /// The depths of the open `[` that index the global object (`$.global[`, `this[`, /// `globalThis[`), the innermost last, up to [`crate::Limits::nesting`] of them. global_indexes: Vec, @@ -728,9 +736,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(), maybe_files_full: false, writers: HashMap::new(), + shared_early: HashMap::new(), objects: vec![], closed: None, index_receiver: 0, + index_stable: false, global_indexes: vec![], global_index_closed: false, unsure: known.unsure || declared.unsure, @@ -1392,7 +1402,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let body = self.scopes.last().map_or(0, |s| s.depth); let starts = before.is_none() || [";", "{", "}"].iter().any(|p| is(before, p)) - || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !word(before, "else") && !word(before, "do")); + || (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do")); let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body); if self.objects.len() < self.acc.limits.nesting { self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None }); @@ -1441,6 +1451,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && self.shared_early.get(&name).is_none_or(|&open| open <= self.scopes.len()) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { self.writers.insert(name, bits); diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 70942a0986..839476d420 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -285,7 +285,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.setter(&name, h2, h3, line); } // `local['saveAs']`: what the object before the bracket defines, for a call that may follow. - "[" => self.index_receiver = self.writer_bits(h0, h1), + "[" => { + self.index_receiver = self.writer_bits(h0, h1); + self.index_stable = h0.is_some_and(|r| self.stable(r.text)); + } "(" => self.call(line), // `Name.prototype["+"] = …` defines an operator. "=" => { @@ -308,7 +311,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { && is(h2, "[") && let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) && catalog::DOM_FILE_WRITES.contains(&method.as_str()) - && !Self::defines(self.index_receiver, &method) + && !(self.index_stable && Self::defines(self.index_receiver, &method)) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -335,7 +338,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); } else if (file && catalog::FILE_WRITES.contains(&n)) - || (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3), n)) + || (catalog::DOM_FILE_WRITES.contains(&n) && !(h2.is_some_and(|r| self.stable(r.text)) && Self::defines(self.writer_bits(h2, h3), n))) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -362,6 +365,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// The methods that `receiver`, which `before` comes before, defines when it is a variable holding /// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name; /// 0 for anything else. A receiver the check does not follow may be a document. + /// Whether a call of `name`'s own method may be left out: the call is in the global code, or in a + /// function body that declares `name` itself. A body that reads `name` from outside may run + /// after the variable was given another value, so its calls are not known. + fn stable(&self, name: &str) -> bool { + self.scopes.last().is_none_or(|s| s.saved.contains_key(name)) + } + fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { match receiver { Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), @@ -395,30 +405,57 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let writer = |s: Option>, before: Option>| s.filter(|s| self.writer_bits(Some(*s), before) != 0).map(|s| s.text); let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")); let key = t.is(":") && (is(h1, "{") || is(h1, ",")); - let escaped = if word(h0, "delete") { - // `delete local…` - writer(Some(*t), h0) - } else if let Some(name) = writer(h0, h1) { - // `local` followed by anything but a member, its own assignment or an object key's `:`. - (!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name) - } else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) { - // `local.saveAs = …` - writer(h2, h3) - } else if is(h0, "[") { - // `local[k]` with a key that is not a string literal. - writer(h1, h2).filter(|_| t.kind != T::Str) - } else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) { - // `local['name' + k]`. - writer(h2, h3).filter(|_| !t.is("]")) - } else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) { - // `local['saveAs'] = …` - writer(h3, None) + let escape = |writer: &dyn Fn(Option>, Option>) -> Option<&'s str>| -> Option<&'s str> { + if word(h0, "delete") { + // `delete local…` + writer(Some(*t), h0) + } else if let Some(name) = writer(h0, h1) { + // `local` followed by anything but a member, its own assignment or an object key's `:`. + (!t.is(".") && !t.is("[") && !t.is("=") && !key).then_some(name) + } else if is(h1, ".") && changes && h0.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&m.text)) { + // `local.saveAs = …` + writer(h2, h3) + } else if is(h0, "[") { + // `local[k]` with a key that is not a string literal. + writer(h1, h2).filter(|_| t.kind != T::Str) + } else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) { + // `local['name' + k]`. + writer(h2, h3).filter(|_| !t.is("]")) + } else if is(h0, "]") && is(h2, "[") && changes && h1.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str())) { + // `local['saveAs'] = …` + writer(h3, None) + } else { + None + } + }; + let escaped = escape(&writer); + // A function body reads a variable of the enclosing code that no literal has given methods yet + // in a way that changes or shares it: the body may run after the literal, as a hoisted + // declaration does. + let early = if escaped.is_none() && !self.scopes.is_empty() { + let captured = |s: Option>, before: Option>| { + s.filter(|s| { + s.kind == T::Ident + && !member_mark(before) + && !self.writers.contains_key(s.text) + && self.scopes.last().is_some_and(|b| !b.saved.contains_key(s.text)) + }) + .map(|s| s.text) + }; + escape(&captured) } else { None }; if let Some(name) = escaped { self.writers.remove(name); } + if let Some(name) = early + && (self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len())) + { + let open = self.scopes.len(); + let seen = self.shared_early.entry(name.to_string()).or_insert(open); + *seen = (*seen).max(open); + } if changes { let rebound = if is(h1, ".") { h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string()) diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 28aec12789..938981691e 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -715,6 +715,51 @@ fn an_own_save_as_that_may_replace_itself_writes_a_file() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 6, 7][..])); } +/// A function declared before the literal is hoisted, so it may change or share the variable before +/// the literal's later calls run: its calls then keep reporting the write. A function with a +/// variable of its own of the same name, and one that only calls the method, leave the method the +/// script's own. +#[test] +fn a_hoisted_function_that_changes_or_shares_the_variable_ends_the_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "function a(w) { local.saveAs = w; }\n", + "var local = {saveAs: function () {}};\n", + "local.saveAs(f);\n", + "function b() { use(other); }\n", + "var other = {saveAs: function () {}};\n", + "other.saveAs(f);\n", + "function c() { var calm = app.activeDocument; use(calm); }\n", + "var calm = {saveAs: function () {}};\n", + "calm.saveAs(f);\n", + "function d() { quiet.saveAs(f); }\n", + "var quiet = {saveAs: function () {}};\n", + "quiet.saveAs(f);\n", + "function g1() { use(mine); }\n", + "function g2() { var mine = {saveAs: function () {}}; mine.saveAs(f); }\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11][..])); +} + +/// A function that reads the variable from outside runs after whatever the script gave it since, so +/// its calls keep reporting the write. A `var` after a label or a `case` is in a branch as well. +#[test] +fn a_captured_or_labelled_own_save_as_writes_a_file() { + let r = report(concat!( + "var f = new File(p);\n", + "var local = {saveAs: function () {}};\n", + "function run() { local.saveAs(f); }\n", + "function run2() { local['saveAs'](f); }\n", + "local = app.activeDocument;\n", + "run();\n", + "function own() { var inner = {saveAs: function () {}}; inner.saveAs(f); inner['saveAs'](f); }\n", + "if (flag) skip:\n", + "var lab = {saveAs: function () {}};\n", + "lab.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4, 10][..])); +} + /// Only a `var` statement directly in a function body or the global code that gives its first name /// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the /// statement. A literal given in a branch, one the value goes on from, one given by an assignment From 4e43269851df94e759b8a275c8a2cec3cee45025 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:33:33 -0800 Subject: [PATCH 07/27] Scripts: a full table of shared names, an assignment and a member call in a hoisted function end the own-method exemption The script check kept a literal's own saveAs when the table of shared names was full, when a function assigned the variable with =, a compound operator, ++ or --, and when a function called a member of it or read it. Each case now keeps reporting the write. --- crates/scriptcheck/src/analyze.rs | 14 ++++- crates/scriptcheck/src/analyze/features.rs | 35 +++++++++--- crates/scriptcheck/src/tests.rs | 63 +++++++++++++++++++++- 3 files changed, 104 insertions(+), 8 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index bed249d6eb..0c9012c6ac 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -643,6 +643,9 @@ struct Analyzer<'s, 'a, 'l> { /// most function bodies that were open where it was read; a literal in a body with that many /// open or more is unaffected, since it gives a variable of its own. shared_early: HashMap, + /// [`Analyzer::shared_early`] had no room for a name: no literal gives methods that are the + /// script's own from then on. + shared_full: bool, /// The object literals being assigned to a variable, the innermost last, up to /// [`crate::Limits::nesting`] of them. objects: Vec, @@ -737,6 +740,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { maybe_files_full: false, writers: HashMap::new(), shared_early: HashMap::new(), + shared_full: false, objects: vec![], closed: None, index_receiver: 0, @@ -1423,6 +1427,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { { let h1 = self.h[1]; let declared = word(h1, "var") || (is(h1, ",") && self.var_depth.is_some()); + if !declared && !member_mark(h1) && !is(h1, "@") { + self.share_early(name.text); + } if declared { if self.in_catch(name.text) { self.declare_in_catch(name.text); @@ -1436,7 +1443,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.assign = Some(Assign { name: name.text.to_string(), after_new: false }); } } - match self.updated(t) { + let updated = self.updated(t); + if let Some((name, _)) = updated { + self.share_early(name); + } + match updated { // The value on the right is read at this depth, and the name holds nothing the check // follows once that value ends ([`Analyzer::settle_groups`]). Some((name, true)) => self.start_value(name.to_string(), Operand::Other), @@ -1451,6 +1462,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn settle_literal(&mut self, t: &Sig<'s>) { if let Some((name, bits)) = self.closed.take() && (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t))) + && !self.shared_full && self.shared_early.get(&name).is_none_or(|&open| open <= self.scopes.len()) && (self.writers.contains_key(&name) || self.acc.room(self.writers.len())) { diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 839476d420..d77b17a20c 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -2,6 +2,12 @@ use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word}; +/// Words that start or continue a statement or an expression, never a variable's name. +const RESERVED: [&str; 24] = [ + "var", "function", "if", "else", "for", "while", "do", "return", "new", "typeof", "delete", "in", "instanceof", "this", "with", "switch", "case", + "try", "catch", "finally", "throw", "break", "continue", "void", +]; + /// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…). pub(super) fn platform_name(n: &str) -> bool { matches!( @@ -372,6 +378,23 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.scopes.last().is_none_or(|s| s.saved.contains_key(name)) } + /// A function body uses `name`, which no literal has given methods and the body does not declare, + /// in a way that may change or share it ([`Analyzer::shared_early`]). With no room left for the + /// name, no literal's methods are the script's own from then on. + pub(super) fn share_early(&mut self, name: &str) { + let Some(body) = self.scopes.last() else { return }; + if body.saved.contains_key(name) || self.writers.contains_key(name) { + return; + } + if self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len()) { + let open = self.scopes.len(); + let seen = self.shared_early.entry(name.to_string()).or_insert(open); + *seen = (*seen).max(open); + } else { + self.shared_full = true; + } + } + fn writer_bits(&self, receiver: Option>, before: Option>) -> u8 { match receiver { Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0), @@ -449,12 +472,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if let Some(name) = escaped { self.writers.remove(name); } - if let Some(name) = early - && (self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len())) - { - let open = self.scopes.len(); - let seen = self.shared_early.entry(name.to_string()).or_insert(open); - *seen = (*seen).max(open); + if let Some(name) = early { + self.share_early(name); + } + // A name read in a function body that the body does not declare, as a receiver or otherwise. + if let Some(r) = h0.filter(|r| r.kind == T::Ident && !member_mark(h1) && !RESERVED.contains(&r.text)) { + self.share_early(r.text); } if changes { let rebound = if is(h1, ".") { diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 938981691e..c0e86dc0f1 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -738,7 +738,68 @@ fn a_hoisted_function_that_changes_or_shares_the_variable_ends_the_own_save_as() "function g1() { use(mine); }\n", "function g2() { var mine = {saveAs: function () {}}; mine.saveAs(f); }\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11][..])); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 11, 13][..])); +} + +/// A table of shared names with no room left for one more means a function may share any name: no +/// literal after it gives methods that are the script's own. +#[test] +fn a_full_table_of_shared_names_keeps_reporting_the_write() { + let src = concat!( + "var f = new File(p);\n", + "function a(w) { p1.saveAs = w; p2.saveAs = w; p3.saveAs = w; }\n", + "var local = {saveAs: function () {}};\n", + "local.saveAs(f);\n", + ); + let r = check("test.jsx", src.as_bytes(), None, &Limits { entries: 2, ..Limits::default() }); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..])); +} + +/// A function body that assigns a variable it does not declare (`=`, a compound operator, `++` or +/// `--`) may run after the literal and give the variable another value. +#[test] +fn an_assignment_in_a_hoisted_function_ends_the_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "function a(w) { local = w; }\n", + "var local = {saveAs: function () {}};\n", + "local.saveAs(f);\n", + "function b() { other += 1; }\n", + "var other = {saveAs: function () {}};\n", + "other.saveAs(f);\n", + "function c() { third++; }\n", + "var third = {saveAs: function () {}};\n", + "third.saveAs(f);\n", + "function e() { --fourth; }\n", + "var fourth = {saveAs: function () {}};\n", + "fourth.saveAs(f);\n", + "function d() { var mine = 1; mine = 2; }\n", + "var mine = {saveAs: function () {}};\n", + "mine.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10, 13][..])); +} + +/// A function body that calls a method of, or reads, a variable it does not declare may run before +/// the literal as well, so a later literal's calls keep reporting the write. +#[test] +fn a_member_call_or_read_in_a_hoisted_function_ends_the_own_save_as() { + let r = report(concat!( + "var f = new File(p);\n", + "function a() { local.run(); }\n", + "var local = {saveAs: function () {}};\n", + "local.saveAs(f);\n", + "function b() { other['m'](); }\n", + "var other = {saveAs: function () {}};\n", + "other.saveAs(f);\n", + "function c() { return third.name; }\n", + "var third = {saveAs: function () {}};\n", + "third.saveAs(f);\n", + "function d() { var calm = 1; return calm.name; }\n", + "var calm = {saveAs: function () {}};\n", + "calm.saveAs(f);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10][..])); } /// A function that reads the variable from outside runs after whatever the script gave it since, so From 9a2b6499ca19a4857dcffa5c51ec9cfa0c3a51a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:46:31 -0800 Subject: [PATCH 08/27] Scripts: format the reserved word list --- crates/scriptcheck/src/analyze/features.rs | 26 ++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index d77b17a20c..0ddeb99cb0 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -4,8 +4,30 @@ use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, ca /// Words that start or continue a statement or an expression, never a variable's name. const RESERVED: [&str; 24] = [ - "var", "function", "if", "else", "for", "while", "do", "return", "new", "typeof", "delete", "in", "instanceof", "this", "with", "switch", "case", - "try", "catch", "finally", "throw", "break", "continue", "void", + "var", + "function", + "if", + "else", + "for", + "while", + "do", + "return", + "new", + "typeof", + "delete", + "in", + "instanceof", + "this", + "with", + "switch", + "case", + "try", + "catch", + "finally", + "throw", + "break", + "continue", + "void", ]; /// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…). From 66cbebac3aa3646a1a1034e92d2d11518870b3db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 08:48:51 -0800 Subject: [PATCH 09/27] Preserve PNG8 transparency and reject unsupported SVG links --- .../src/script/dom/save_open/screens.rs | 11 ++++- crates/engine/src/tests/script_screens.rs | 48 +++++++++++++++++++ crates/js/src/host.rs | 2 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 5 files changed, 61 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom/save_open/screens.rs b/crates/engine/src/script/dom/save_open/screens.rs index c4cf253ecd..07ef0aa324 100644 --- a/crates/engine/src/script/dom/save_open/screens.rs +++ b/crates/engine/src/script/dom/save_open/screens.rs @@ -15,6 +15,8 @@ //! The method runs `document.exportForScreens` with one format row into the folder, which goes //! through the script's file grants as a `File` opened for writing there would, and the command //! writes only where the script's `File` objects may ([`super::exactly`]). +//! With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. SVG raster images are +//! embedded; `RasterImageLocation.LINK` returns an error. //! //! VectorCraft's own rules, which the reference pages do not state: //! - `exportFolder` is a `Folder`, or a `File` read as the folder at its path. The files go into @@ -217,7 +219,7 @@ fn png8_map(name: &str, d: &Data, p: &mut Map) -> std::result::Re } // Matted on white, the default `matteColor`, or not matted. "matte" => { - p.insert("matte".into(), if boolean(d, &what)? { json!("white") } else { Value::Null }); + p.insert("matte".into(), json!(if boolean(d, &what)? { "white" } else { "none" })); } _ => return raster_map(CLASS, name, d, p), } @@ -254,7 +256,12 @@ fn svg_map(name: &str, d: &Data, p: &mut Map) -> std::result::Res ("styling", json!(styling)) } "fontType" => ("outlineText", json!(pick(d, "SVGFontType", &what)? == "OUTLINEFONT")), - "rasterImageLocation" => ("images", json!(if pick(d, "RasterImageLocation", &what)? == "LINK" { "link" } else { "embed" })), + "rasterImageLocation" => { + if pick(d, "RasterImageLocation", &what)? == "LINK" { + return Err(HostError::Error(format!("{what}: RasterImageLocation.LINK is not available yet"))); + } + ("images", json!("embed")) + } "svgId" => { let ids = match pick(d, "SVGIdType", &what)? { "SVGIDMINIMAL" => "minimal", diff --git a/crates/engine/src/tests/script_screens.rs b/crates/engine/src/tests/script_screens.rs index 343feff945..691fd5a107 100644 --- a/crates/engine/src/tests/script_screens.rs +++ b/crates/engine/src/tests/script_screens.rs @@ -9,6 +9,54 @@ use crate::*; const DENIED: &str = "Script file access denied"; +#[test] +fn screen_png8_without_matting_keeps_transparent_edge_colors() { + let base = vectorcraft_testkit::TempDir::new("screen-png8-unmatted"); + std::fs::create_dir_all(base.join("main")).unwrap(); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 20, 20); \ + vc.run('shape.rectangle', {{x: 0, y: 0, width: 20, height: 20}}); \ + vc.run('paint.setFill', {{color: '#ff0000'}}); d.pageItems[0].opacity = 50; \ + var o = new ExportForScreensOptionsPNG8(); o.matte = false; \ + d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG8, o);", + quoted(&dir.join("png8")) + ), + ); + let output = dir.join("png8"); + let files = names(&output); + assert_eq!(files.len(), 1); + let rgba = image::open(output.join(&files[0])).unwrap().to_rgba8(); + let pixel = rgba.get_pixel(5, 5).0; + assert!(pixel[0] > 200 && pixel[1] < 20 && pixel[2] < 20, "{pixel:?}"); +} + +#[test] +fn linked_screen_svg_images_are_rejected_before_output_is_created() { + let base = vectorcraft_testkit::TempDir::new("screen-svg-linked"); + std::fs::create_dir_all(base.join("main")).unwrap(); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap(); + let output = dir.join("svg"); + let error = failure( + &mut s, + &base, + &format!( + "Folder.userData; var o = new ExportForScreensOptionsWebOptimizedSVG(); \ + o.rasterImageLocation = RasterImageLocation.LINK; \ + app.activeDocument.exportForScreens(new Folder({}), ExportForScreensType.SE_SVG, o);", + quoted(&output) + ), + ); + assert!(error.contains("not available yet"), "{error}"); + assert!(!output.exists()); +} + /// 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-screens-{name}-{}", std::process::id())); diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index bbb1be9d47..564cce2efd 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -268,7 +268,7 @@ impl Interp { if r.hosted && let Some(file) = self.file_ref_of(id)? { - let len = match &file { + let len: usize = match &file { Data::Object(items) => items.iter().map(|(_, v)| if let Data::String(p) = v { p.len() } else { 0 }).sum(), _ => 0, }; diff --git a/docs/mcp.md b/docs/mcp.md index 60044f85b2..72ec7c7532 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2941,8 +2941,8 @@ other files through `$`: `antiAliasing`, `scaleType` and `scaleTypeValue` (`SCALEBYFACTOR` as a multiplier from 0.01 to 64, so 2 doubles the size, `SCALEBYWIDTH` and `SCALEBYHEIGHT` in pixels, `SCALEBYRESOLUTION` in ppi from 0.72 to 4608); JPEG also maps `compressionMethod`, `embedICCProfile` and `progressiveScan` (3 to 5); PNG24 maps `transparency`, `backgroundBlack` and `interlaced`; PNG8 maps `colorCount` (2 to 256), `interlaced`, - `matte` and `transparency`. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`, - `rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`, and the PDF class maps `pdfPreset` (at most 255 + `matte` and `transparency`. With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. The SVG class maps `coordinatePrecision` (1 to 7), `cssProperties`, `fontType`, + `rasterImageLocation`, `svgId`, `svgMinify` and `svgResponsive`. SVG `RasterImageLocation.LINK` throws; `EMBED` and `PRESERVE` embed raster images. The PDF class maps `pdfPreset` (at most 255 bytes; a name in square brackets names a built-in preset as `PDFSaveOptions.pDFPreset` does). `itemToExport` is a `new ExportForScreensItemToExport()` (https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html) with `artboards` (`all`, the default, a range of artboard numbers such as `1-3, 5`, or `""` for none), `assets` (a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3578b81e5f..0ba5bf7e8b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1049,7 +1049,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: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`. - - Scripts: `Document.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_screens.rs`. + - Scripts: `Document.exportForScreens` writes the artboards, assets or whole document of an `ExportForScreensItemToExport` into a folder as JPEG, PNG-24, PNG-8, SVG or PDF with a file name prefix, with the option classes and enumerations the reference pages https://www.indesignjs.de/indesignapi/illustrator/Document.html, https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html and https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html describe, and writes only where the script's `File` objects may (`docs/mcp.md`). With PNG8 transparency enabled, `matte: false` preserves transparency without a white background. SVG embeds raster images and rejects `RasterImageLocation.LINK`. `crates/engine/src/tests/script_screens.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`. From e3b74e2fdad5fbfdba640c7a3659c4c327fccf9d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 11:05:12 -0800 Subject: [PATCH 10/27] Validate screen export sizes before creating output --- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/fileio/screens.rs | 11 ++++++++++- crates/engine/src/tests/script_screens.rs | 23 ++++++++++++++++++++++ crates/scriptcheck/src/analyze/features.rs | 2 +- crates/scriptcheck/src/tests.rs | 14 +++++++++++++ docs/mcp.md | 5 ++++- docs/target-app-parity.md | 2 +- 7 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 5e756623f0..48c584d7ad 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,