mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 05:22:58 -05:00
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.
This commit is contained in:
1 parent
3977aa6268
commit
48a09ccae3
14 files changed
+954
-12
No files matched your search
@@ -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)?;
|
||||
}
|
||||
|
||||
@@ -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> {
|
||||
});
|
||||
HostClass { name: c.name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) }
|
||||
})
|
||||
.chain(screens::classes(link))
|
||||
.collect()
|
||||
}
|
||||
@@ -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
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/Document.html>,
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensItemToExport.html>,
|
||||
//! <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> and
|
||||
//! <https://www.indesignjs.de/indesignapi/illustrator/ExportForScreensType.html> 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 `<fileNamePrefix><name><suffix>.<extension>` 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<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
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<String, Value>) -> 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<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
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<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
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<String, Value>) {
|
||||
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<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
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<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
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<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
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<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
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::<std::result::Result<Vec<u64>, 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<Map<String, Value>, 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<String, Value>, &'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<Vec<Map<String, Value>>, 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<HostClass> {
|
||||
[&ITEM, &JPEG, &PNG24, &PNG8, &SVG, &PDF]
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
current(&l)?.charge_call(64)?;
|
||||
Ok(fresh(c))
|
||||
});
|
||||
HostClass { name: c.name.into(), parent: None, members: Vec::new(), index: None, construct: Some(f) }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -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<std::path::PathBuf, &'static str> {
|
||||
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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Value> {
|
||||
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<String> {
|
||||
let mut v: Vec<String> =
|
||||
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::<String>::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);
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Option<crate::Data>> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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::<Vec<_>>(), [("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::<Vec<_>>(), [("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.
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
+39
-1
@@ -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 `<fileNamePrefix><name><suffix>.<extension>` 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
|
||||
|
||||
@@ -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`.
|
||||
|
||||
Reference in new issue
Block a user