mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 05:22:58 -05:00
Merge pull request #9315 from dotCooCoo/feat/scripts-export-for-screens
Scripts: Document.exportForScreens writes artboards, assets or the document into a folder
This commit is contained in:
26 files changed
+2698
-175
No files matched your search
@@ -117,8 +117,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,
|
||||
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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; a native, .ai or EPS file of an artboard holds the grown artboard with a bleed of 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 <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/[email protected]); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is
Line truncated
|
||||
"{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; a native, .ai or EPS file of an artboard holds the grown artboard with a bleed of 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 <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100; webp 0–100 with lossless: false), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/[email protected]); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused; a key only another format takes in a row or in settings is not used, and warnings name it as given (formats[0].quality; a key in settings only when no row of that format reads it; not a key of an exportPreset). Under automation read roots, an svg or svgz row, and a row whose files carry the native document (vectorcraft, eps, ai but a version 7 file, a pdf with preserveEditing on that holds every artboard of the document it is
Line truncated
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
|
||||
@@ -74,8 +74,9 @@ pub(super) fn distinct_names_by(names: impl IntoIterator<Item = String>, 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<Value> {
|
||||
let files = enc.named(doc, path.unwrap_or(name));
|
||||
let (main, linked) = files.split_at(enc.files.len());
|
||||
|
||||
@@ -282,7 +282,11 @@ impl Row {
|
||||
// The resolution is stored in the file too.
|
||||
ScreenSize::Ppi(ppi) => o["ppi"] = json!(ppi),
|
||||
size => {
|
||||
o["scale"] = json!(size.scale_for(C, region)?);
|
||||
let scale = size.scale_for(C, region)?;
|
||||
if !scale.is_finite() || !(0.01..=64.0).contains(&scale) {
|
||||
return Err(bad(C, "the effective raster scale must be between 0.01 and 64 pixels per point"));
|
||||
}
|
||||
o["scale"] = json!(scale);
|
||||
if let Some(m) = o.as_object_mut() {
|
||||
m.remove("ppi");
|
||||
}
|
||||
@@ -638,6 +642,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<Option<HashSet<String>>> = 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<T>(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 {
|
||||
@@ -1194,6 +1217,11 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
let ungrown = (grown && o.assets.is_none() && o.layers.is_none() && o.selection.is_none()).then_some(original);
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
for row in rows.iter().filter(|row| row.format.raster) {
|
||||
for item in &items {
|
||||
row.options_for(item.region, item.artboard)?;
|
||||
}
|
||||
}
|
||||
// Before the folder is made or any row is written, with the artboards each file holds.
|
||||
let single: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
|
||||
let st = s.doc()?;
|
||||
@@ -1348,6 +1376,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<Note> = Vec::new();
|
||||
for text in unused {
|
||||
@@ -1426,6 +1462,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() {
|
||||
|
||||
@@ -3410,8 +3410,17 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
/// holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in
|
||||
ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(raster_capture::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS)
|
||||
// An enumeration the save or rasterize options also define (`SVGFontType`, `AntiAliasingMethod`) is defined once,
|
||||
// with every member.
|
||||
let screens = save_open::screens::ENUMS.iter().filter(|(n, _)| !save_open::ENUMS.iter().chain(raster_capture::ENUMS).any(|(m, _)| m == n));
|
||||
for (name, members) in ENUMS
|
||||
.iter()
|
||||
.chain(save_open::ENUMS)
|
||||
.chain(screens)
|
||||
.chain(print::ENUMS)
|
||||
.chain(raster_capture::ENUMS)
|
||||
.chain(images::ENUMS)
|
||||
.chain(tracing::ENUMS)
|
||||
{
|
||||
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/> describe.
|
||||
//!
|
||||
//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's
|
||||
//! transaction. The file is a `File` object, and the method reads and writes only where that
|
||||
//! transaction and writes command warnings to the run's console.
|
||||
//! The file is a `File` object, and the method reads and writes only where that
|
||||
//! `File` may ([`super::super::files`]): the path is checked before the command runs, and the
|
||||
//! command's own reads and writes leave out the files of the open documents that `vc.run`'s
|
||||
//! commands may use.
|
||||
@@ -26,6 +27,8 @@
|
||||
//! `exportFile` adds the format's extension unless the name already ends
|
||||
//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes
|
||||
//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art.
|
||||
//! An SVG export writes a compressed file when `compressed` is true, which adds `.svgz`, and
|
||||
//! when the name ends with `.svgz`.
|
||||
//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it,
|
||||
//! and when one of those files may not be written, none of them is.
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF
|
||||
@@ -75,6 +78,8 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
pub(super) mod screens;
|
||||
|
||||
use super::{
|
||||
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, current, doc_ref, get, given, method, named,
|
||||
num, on_doc, property, returns, text, this_doc, typed, whole,
|
||||
@@ -642,6 +647,16 @@ fn svg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Res
|
||||
"compressed" => {
|
||||
p.insert("_svgz".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"cssProperties" => {
|
||||
let locations = ["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"];
|
||||
let styling = match member(d, "SVGCSSPropertyLocation", &locations, &what)? {
|
||||
"ENTITIES" => "entities",
|
||||
"PRESENTATIONATTRIBUTES" => "presentation",
|
||||
"STYLEELEMENTS" => "css",
|
||||
_ => "style",
|
||||
};
|
||||
p.insert("styling".into(), json!(styling));
|
||||
}
|
||||
"preserveEditability" => {
|
||||
p.insert("preserveEditing".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
@@ -655,7 +670,6 @@ fn svg_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Res
|
||||
|
||||
const SVG_KEPT: &[(&str, Default)] = &[
|
||||
("artboardRange", Default::Text("")),
|
||||
("cssProperties", Default::Member("SVGCSSPropertyLocation", "STYLEATTRIBUTES")),
|
||||
("documentEncoding", Default::Member("SVGDocumentEncoding", "ASCII")),
|
||||
("DTD", Default::Member("SVGDTDVersion", "SVG1_1")),
|
||||
("fontSubsetting", Default::Member("SVGFontSubsetting", "ALLGLYPHS")),
|
||||
@@ -673,6 +687,7 @@ fn svg_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("compressed", Data::Bool(false)),
|
||||
("coordinatePrecision", num(3.0)),
|
||||
("cssProperties", text("SVGCSSPropertyLocation.STYLEATTRIBUTES")),
|
||||
("embedRasterImages", Data::Bool(false)),
|
||||
("includeVariablesAndDatasets", Data::Bool(false)),
|
||||
("preserveEditability", Data::Bool(false)),
|
||||
@@ -1020,7 +1035,9 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
// An SVG export to a name that ends with `.svgz` writes a compressed file, whatever `compressed` holds.
|
||||
let svgz_name = path.rsplit(['/', '\\']).next().is_some_and(|n| n.to_lowercase().ends_with(".svgz"));
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false) || (kind.format == "svg" && svgz_name);
|
||||
let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0));
|
||||
if (hs - vs).abs() > 1e-9 {
|
||||
@@ -1303,6 +1320,9 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
("saved", property(l, doc_saved, doc_set_saved), typed("boolean")),
|
||||
("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])),
|
||||
])
|
||||
.into_iter()
|
||||
.chain(screens::document_members(l))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its
|
||||
@@ -1317,5 +1337,6 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
});
|
||||
HostClass { construct: Some(f), ..class(c.name, None, Vec::new(), None) }
|
||||
})
|
||||
.chain(screens::classes(link))
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
//! `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`]).
|
||||
//! 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
|
||||
//! 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.
|
||||
//! `null` in place of the options, `itemToExport` or `fileNamePrefix` throws a TypeError.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{
|
||||
Answer, Default, Described, Host, Link, MAX_TEXT_BYTES, OptionClass, arg, boolean, builtin_preset_name, current, exactly, fresh, given, member,
|
||||
method, named, num, on_doc, plain, refused, returns, text, this_doc, typename, warned, 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(), json!(if boolean(d, &what)? { "white" } else { "none" }));
|
||||
}
|
||||
_ => 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" => {
|
||||
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",
|
||||
"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));
|
||||
if matches!(options, Some(Data::Null)) {
|
||||
return Err(HostError::Type("the options must be an object".into()));
|
||||
}
|
||||
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)))?;
|
||||
let prefix = match given(arg(a, 5)) {
|
||||
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));
|
||||
}
|
||||
// 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| warned(h, "exportForScreens", "document.exportForScreens", &Value::Object(p))))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
}
|
||||
|
||||
/// The members these add to `Document`.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![(
|
||||
"exportForScreens",
|
||||
method(l, doc_export_for_screens),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("exportFolder", "Folder"),
|
||||
("targetType", "ExportForScreensType"),
|
||||
("options", "*"),
|
||||
("itemToExport", "ExportForScreensItemToExport"),
|
||||
("fileNamePrefix", "string"),
|
||||
],
|
||||
),
|
||||
)])
|
||||
}
|
||||
|
||||
/// 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(), info: 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))]
|
||||
@@ -720,6 +721,24 @@ 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. A root (`/`, `E:\`) has no name of its own: its real path must be inside a
|
||||
/// folder the script may write to and the automation write roots in force.
|
||||
pub(crate) fn folder_target(&self, path: &str) -> Result<std::path::PathBuf, &'static str> {
|
||||
let p = self.checked(path)?;
|
||||
if p.file_name().is_none() {
|
||||
let real = std::fs::canonicalize(p).map_err(|_| ACCESS_DENIED)?;
|
||||
let writable = crate::file_access::check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_ok();
|
||||
return if self.writes.allows(&real) && writable { Ok(real) } else { Err(ACCESS_DENIED) };
|
||||
}
|
||||
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.
|
||||
|
||||
@@ -201,6 +201,7 @@ mod script_print;
|
||||
mod script_raster_capture;
|
||||
mod script_run;
|
||||
mod script_save_open;
|
||||
mod script_screens;
|
||||
mod script_scriptui;
|
||||
mod script_styles;
|
||||
mod script_tags;
|
||||
|
||||
@@ -741,8 +741,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);
|
||||
assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command");
|
||||
@@ -842,8 +843,14 @@ fn a_layer_opacity_close_to_the_current_one_is_set() {
|
||||
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());
|
||||
// In either order, the refused assignment leaves nothing selected while the script runs.
|
||||
let out = log(
|
||||
@@ -875,6 +882,9 @@ 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]);
|
||||
// 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[1].pageItems[0];");
|
||||
|
||||
@@ -10,6 +10,34 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[test]
|
||||
fn file_wrappers_report_encoder_warnings_without_changing_their_return_values() {
|
||||
for method in ["exportFile", "saveAs", "exportForScreens"] {
|
||||
let base = folder(&format!("encoder-warnings-{method}"));
|
||||
let mut s = session(&base);
|
||||
s.execute("file.new", &json!({"width": 80, "height": 40})).unwrap();
|
||||
crate::tests_menucmds::place_undecodable_png(&mut s);
|
||||
let format = if method == "saveAs" { "pdf" } else { "png" };
|
||||
let expected = s.execute("document.export", &json!({"format": format})).unwrap()["warnings"].clone();
|
||||
let warnings = expected.as_array().unwrap();
|
||||
assert!(!warnings.is_empty(), "the fixture must produce an encoder warning");
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let path = quoted(&dir.join("output.png"));
|
||||
let call = match method {
|
||||
"exportFile" => format!("d.exportFile(new File({path}), ExportType.PNG24)"),
|
||||
"saveAs" => format!("d.saveAs(new File({}))", quoted(&dir.join("output.pdf"))),
|
||||
_ => format!("d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG24)", quoted(&dir.join("screens"))),
|
||||
};
|
||||
let report =
|
||||
run(&mut s, &base, &format!("Folder.userData; var d = app.activeDocument; var answer = {call}; vc.log(answer === undefined);")).unwrap();
|
||||
assert_eq!(report["log"], json!([true]), "{method}: {report}");
|
||||
let lines = report["console"]["lines"].as_array().unwrap();
|
||||
for warning in warnings.iter().filter_map(Value::as_str) {
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|line| line.contains(warning)), "{method}: {warning}: {lines:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_as_uses_the_scripts_extension_before_following_a_link() {
|
||||
@@ -221,7 +249,6 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
|
||||
assert!(dir.join("e.JPG").is_file() && !dir.join("e.JPG.jpg").exists(), "a name that ends with the extension keeps it");
|
||||
assert!(std::fs::read(dir.join("f.svgz")).unwrap().starts_with(&[0x1f, 0x8b]));
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -380,7 +407,7 @@ fn save_as_uses_the_link_name_extension_for_the_encoder() {
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg"))));
|
||||
assert!(std::fs::read_to_string(&target).unwrap().contains("<svg"));
|
||||
assert_eq!(s.active().unwrap().format, "svg");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -403,7 +430,7 @@ fn save_as_template_preserves_the_document_file_and_saved_state() {
|
||||
assert_eq!(out, json!([[true, true], [true, false]]));
|
||||
assert!(dir.join("clean.vctemplate").is_file());
|
||||
assert!(dir.join("dirty.vctemplate").is_file());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -419,7 +446,7 @@ fn open_uses_the_requested_symlink_filename() {
|
||||
let out = logged(&mut s, &base, &format!("Folder.userData; var d = app.open(new File({})); vc.log([d.name, d.fullName.name]);", quoted(&link)));
|
||||
assert_eq!(out, json!([["drawing.svg", "drawing.svg"]]));
|
||||
assert_eq!(s.active().unwrap().format, "svg");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// Without options, a save or export writes what an untouched new options object of its class gives.
|
||||
@@ -456,7 +483,6 @@ fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
let pdf = std::fs::read(dir.join(name)).unwrap();
|
||||
assert!(pdf.starts_with(b"%PDF-1.4"), "{name}: PDFCompatibility.ACROBAT5 is PDF 1.4, {:?}", String::from_utf8_lossy(&pdf[..8]));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// White, the default `matteColor` of `ExportOptionsPNG24` and `ExportOptionsJPEG`, is accepted, and
|
||||
@@ -531,7 +557,7 @@ fn script_file_commands_refuse_non_utf8_resolved_paths() {
|
||||
let target = dir.join(std::ffi::OsString::from_vec(b"target-\xff.vectorcraft".to_vec()));
|
||||
// A file system that refuses such a name has nothing to refuse.
|
||||
if std::fs::write(&target, &bytes).is_err() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
return;
|
||||
}
|
||||
let link = dir.join("alias.vectorcraft");
|
||||
@@ -553,7 +579,7 @@ fn script_file_commands_refuse_non_utf8_resolved_paths() {
|
||||
assert_eq!(std::fs::read(&target).unwrap(), bytes);
|
||||
assert_eq!(std::fs::read(&lossy).unwrap(), bytes);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// Every enumeration an option keeps its default in is defined: the default member is accepted, and
|
||||
@@ -578,7 +604,6 @@ fn kept_enum_options_accept_their_default_member() {
|
||||
("PDFSaveOptions", "pDFChangesAllowed", "PDFChangesAllowedEnum.CHANGE128ANYCHANGES", "PDFChangesAllowedEnum.CHANGE40NONE"),
|
||||
("PDFSaveOptions", "pDFXStandard", "PDFXStandard.PDFXNONE", "PDFXStandard.PDFX42007"),
|
||||
("PDFSaveOptions", "trimMarkWeight", "PDFTrimMarkWeight.TRIMMARKWEIGHT0125", "PDFTrimMarkWeight.TRIMMARKWEIGHT05"),
|
||||
("ExportOptionsSVG", "cssProperties", "SVGCSSPropertyLocation.STYLEATTRIBUTES", "SVGCSSPropertyLocation.ENTITIES"),
|
||||
("ExportOptionsSVG", "documentEncoding", "SVGDocumentEncoding.ASCII", "SVGDocumentEncoding.UTF8"),
|
||||
("ExportOptionsSVG", "DTD", "SVGDTDVersion.SVG1_1", "SVGDTDVersion.SVGTINY1_2"),
|
||||
("ExportOptionsSVG", "fontSubsetting", "SVGFontSubsetting.ALLGLYPHS", "SVGFontSubsetting.GLYPHSUSED"),
|
||||
@@ -597,7 +622,7 @@ fn kept_enum_options_accept_their_default_member() {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; {}", call(other, format!("no{i}"))));
|
||||
assert!(e.contains("is not available yet"), "{class}.{key} = {other}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// A raster export at 100% has one pixel per point, whatever the document's raster effects
|
||||
@@ -624,7 +649,6 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() {
|
||||
let image = image::open(dir.join(name)).unwrap();
|
||||
assert_eq!((image.width(), image.height()), (200, 100), "{name}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The value of the DXF header variable `name` (the group after its name).
|
||||
@@ -757,7 +781,6 @@ fn a_pdf_preset_keeps_its_settings_unless_an_option_changes() {
|
||||
let pdf = std::fs::read(dir.join(name)).unwrap();
|
||||
assert!(pdf.starts_with(version), "{name}: {:?}", String::from_utf8_lossy(&pdf[..8]));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A save that writes several files, such as an EPS with a file per artboard, writes none of them
|
||||
@@ -792,7 +815,6 @@ fn a_save_writes_nothing_when_one_of_its_files_is_refused() {
|
||||
let e = failure(&mut s, &base, &save);
|
||||
assert!(e.contains("not a file"), "{e}");
|
||||
assert!(!central.exists(), "the central file is not written when a folder is where an artboard's file goes");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An export that writes several files writes none of them when a folder is where one of them goes.
|
||||
@@ -863,7 +885,6 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&refused, perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Every path goes through the script's file grants, as a `File` opened for reading or writing.
|
||||
@@ -897,8 +918,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());
|
||||
@@ -909,7 +930,6 @@ fn save_as_export_file_and_open_refuse_paths_outside_the_grants() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(dir.join("kept.svg"), perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The file of an open document is not written or read through a script method unless the
|
||||
@@ -927,7 +947,6 @@ fn an_open_documents_file_is_not_saved_over_without_a_grant() {
|
||||
let e = failure(&mut s, &base, &format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&path)));
|
||||
assert!(e.contains(DENIED), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A save or export to a file a `File` object holds open for writing throws, so the object's bytes
|
||||
@@ -953,7 +972,6 @@ fn a_file_open_for_writing_is_not_saved_over() {
|
||||
assert_eq!(std::fs::read_to_string(dir.join(name)).unwrap(), "pending", "{name}: the File's own bytes");
|
||||
assert_eq!(s.active().unwrap().path, None, "{name}: the document's file is unchanged");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A file `open` reads besides the one it names, here an SVG's linked image, is read only where
|
||||
@@ -994,7 +1012,6 @@ fn open_reads_linked_files_only_where_the_script_may() {
|
||||
std::fs::copy(dir.join("page.svg"), dir.join("copy.svg")).unwrap();
|
||||
s.execute("document.open", &json!({"path": dir.join("copy.svg").to_string_lossy()})).unwrap();
|
||||
assert!(ims(&s).is_empty() && kinds(&s).iter().any(|k| k.starts_with("Path")), "{:?}", kinds(&s));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A file an open document links to is read by `open` only where the script may read, too.
|
||||
@@ -1053,7 +1070,6 @@ fn an_svg_export_writes_nothing_when_one_of_its_files_is_refused() {
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&image, perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An export does not write a file it writes besides the one named, here an SVG's image, while a
|
||||
@@ -1085,7 +1101,6 @@ fn an_svg_export_does_not_write_an_image_a_file_holds_open() {
|
||||
assert!(log[0].as_str().unwrap().contains(DENIED), "{log}");
|
||||
assert!(!svg.exists(), "the SVG is not written when its image may not be");
|
||||
assert_eq!(std::fs::read_to_string(&image).unwrap(), "pending", "the File's own bytes");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A link inside a granted folder that leads out of it is followed and refused.
|
||||
@@ -1108,7 +1123,6 @@ fn a_link_out_of_the_granted_folder_is_refused() {
|
||||
assert!(e.contains(DENIED), "{e}");
|
||||
assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1, "nothing is written outside");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Without options, `saveAs` takes the format from the path the script names, not from the file a
|
||||
@@ -1126,7 +1140,6 @@ fn save_as_takes_the_format_of_the_named_path_through_a_link() {
|
||||
let written = std::fs::read(dir.join("target.pdf")).unwrap();
|
||||
assert!(!written.starts_with(b"%PDF"), "the named .svg path writes SVG, not PDF");
|
||||
assert!(String::from_utf8_lossy(&written).contains("<svg"), "an SVG file");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Bad arguments throw before anything is written or opened.
|
||||
@@ -1252,7 +1265,6 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "nothing was written");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
assert_eq!(s.active().unwrap().path, None);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a
|
||||
@@ -1289,7 +1301,6 @@ fn a_forged_file_is_refused() {
|
||||
assert!(std::fs::read_dir(base.join("outside")).unwrap().count() == 1);
|
||||
assert_eq!(s.documents().len(), 1, "nothing is opened");
|
||||
assert_eq!(s.active().unwrap().path, None);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A document from an earlier run is stale, and saving it throws.
|
||||
@@ -1303,7 +1314,6 @@ fn a_stale_document_is_not_saved() {
|
||||
let e = failure(&mut s, &base, &format!("#targetengine keep\nFolder.userData; held.saveAs(new File({}));", quoted(&dir.join("x.svg"))));
|
||||
assert!(e.contains("Stale document"), "{e}");
|
||||
assert!(!dir.join("x.svg").exists());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `open` applies the page and crop box of its options to a PDF.
|
||||
@@ -1312,9 +1322,13 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
|
||||
let base = folder("pdf");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": 2})).unwrap();
|
||||
// Page 2 is 200 × 400 pt with a 180 × 380 pt crop box, unlike page 1's 100 × 100 pt.
|
||||
let mut second = vectorcraft_testkit::pdf::PdfPage::new(200.0, 400.0, "0 0 1 rg 20 30 40 50 re f");
|
||||
second.crop = Some([10.0, 10.0, 190.0, 390.0]);
|
||||
let pages = [vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"), second];
|
||||
let pdf = dir.join("two.pdf");
|
||||
s.execute("file.saveAs", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap();
|
||||
std::fs::write(&pdf, vectorcraft_testkit::pdf::pdf(&pages, None)).unwrap();
|
||||
let size = |s: &Session| s.active().map(|st| st.doc.artboards.iter().map(|a| (a.rect.width(), a.rect.height())).collect::<Vec<_>>());
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
@@ -1325,6 +1339,9 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!(["DocumentColorSpace.CMYK"]));
|
||||
assert_eq!(size(&s), Some(vec![(200.0, 400.0)]), "page 2 on its media box");
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 2}});", quoted(&pdf)));
|
||||
assert_eq!(size(&s), Some(vec![(180.0, 380.0)]), "page 2 on its crop box, the default");
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 3}});", quoted(&pdf)));
|
||||
assert!(!e.is_empty(), "a page the file does not have");
|
||||
assert_eq!(s.documents().len(), 2);
|
||||
@@ -1334,7 +1351,65 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
|
||||
logged(&mut s, &base, &undefined);
|
||||
assert_eq!(s.documents().len(), 3);
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "both pages");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// An SVG export to a name that ends with `.svgz` writes a compressed file at that name, without
|
||||
/// options and with `compressed` false; a name without the suffix stays a plain SVG. `cssProperties`
|
||||
/// picks how the style properties are written.
|
||||
#[test]
|
||||
fn export_file_keeps_an_svgz_name_compressed_and_applies_css_properties() {
|
||||
let base = folder("svgz");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let d = quoted(&dir);
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 20, 20);\n\
|
||||
vc.run('shape.rectangle', {{x: 2, y: 2, width: 10, height: 10}});\n\
|
||||
d.exportFile(new File(dir + '/logo.svgz'), ExportType.SVG);\n\
|
||||
var o = new ExportOptionsSVG(); o.compressed = false;\n\
|
||||
d.exportFile(new File(dir + '/plain.SVGZ'), ExportType.SVG, o);\n\
|
||||
d.exportFile(new File(dir + '/page'), ExportType.SVG);\n\
|
||||
var a = new ExportOptionsSVG(); a.cssProperties = SVGCSSPropertyLocation.PRESENTATIONATTRIBUTES;\n\
|
||||
d.exportFile(new File(dir + '/attributes'), ExportType.SVG, a);"
|
||||
),
|
||||
);
|
||||
for name in ["logo.svgz", "plain.SVGZ"] {
|
||||
assert!(std::fs::read(dir.join(name)).unwrap().starts_with(&[0x1f, 0x8b]), "{name}");
|
||||
assert!(!dir.join(format!("{name}.svg")).exists(), "{name}");
|
||||
}
|
||||
let page = std::fs::read_to_string(dir.join("page.svg")).unwrap();
|
||||
assert!(page.contains("style=\"fill:"), "a new options object's cssProperties is STYLEATTRIBUTES: {page}");
|
||||
let attributes = std::fs::read_to_string(dir.join("attributes.svg")).unwrap();
|
||||
assert!(attributes.contains(" fill=\"") && !attributes.contains("style=\"fill:"), "{attributes}");
|
||||
}
|
||||
|
||||
/// A path whose real path has no UTF-8 form, through a link to a folder of such a name, is refused
|
||||
/// before anything is written there.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_real_path_that_is_not_unicode_is_refused() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let base = folder("not-unicode");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let odd = dir.join(std::ffi::OsStr::from_bytes(b"odd-\xff"));
|
||||
std::fs::create_dir_all(&odd).unwrap();
|
||||
std::os::unix::fs::symlink(&odd, dir.join("link")).unwrap();
|
||||
let link = quoted(&dir.join("link"));
|
||||
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
|
||||
for call in [
|
||||
format!("app.activeDocument.exportFile(new File({link} + '/out.png'), ExportType.PNG24)"),
|
||||
format!("app.activeDocument.saveAs(new File({link} + '/out.svg'))"),
|
||||
format!("app.activeDocument.exportForScreens(new Folder({link}), ExportForScreensType.SE_PNG24)"),
|
||||
] {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; {call};"));
|
||||
assert!(e.contains("Script file path is not valid UTF-8"), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&odd).unwrap().count(), 0, "nothing is written in the folder");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1356,7 +1431,7 @@ fn crop_only_options_apply_to_an_editable_pdf() {
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pDFCropToBox: PDFBoxType.PDFMEDIABOX}});", quoted(&pdf)));
|
||||
let cropped = s.active().unwrap().doc.artboards[0].rect;
|
||||
assert!(cropped.width() > original.width() && cropped.height() > original.height());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1388,7 +1463,7 @@ fn explicit_crop_box_opens_the_bleed_outside_an_editable_files_trim_box() {
|
||||
assert_eq!((default.width(), default.height()), (trim.width(), trim.height()), "{extension}");
|
||||
assert!(crop.width() > trim.width() && crop.height() > trim.height(), "{extension}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1404,7 +1479,7 @@ fn script_document_open_rejects_files_over_the_read_limit() {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file)));
|
||||
assert!(e.contains(crate::cmd::fileio::SCRIPT_OPEN_TOO_LARGE), "{e}");
|
||||
assert_eq!(s.documents().len(), count);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1432,7 +1507,7 @@ fn pdf_open_options_reject_other_detected_formats() {
|
||||
s.execute("file.saveCopy", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 1}});", quoted(&pdf)));
|
||||
assert_eq!(s.documents().len(), count + 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1451,7 +1526,7 @@ fn script_document_open_treats_null_pdf_options_as_omitted() {
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 1);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1484,7 +1559,7 @@ fn explicit_null_options_do_not_save_export_open_or_close() {
|
||||
assert_ne!(std::fs::read(&file).unwrap(), original);
|
||||
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(undefined);");
|
||||
assert!(s.documents().is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its
|
||||
@@ -1531,7 +1606,6 @@ fn full_name_path_saved_and_close_follow_the_documents_file() {
|
||||
assert!(s.documents().is_empty());
|
||||
let e = failure(&mut s, &base, "app.documents.add(); app.activeDocument.close('DONOTSAVECHANGES');");
|
||||
assert!(e.contains("SaveOptions"), "{e}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A document whose file was saved under a relative name is in the working folder the file was
|
||||
@@ -1599,7 +1673,6 @@ fn a_document_without_unsaved_changes_closes_with_any_save_options() {
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([[true, true, 2], 1, 0]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `close(SaveOptions.SAVECHANGES)` saves in the format the document was last saved in, not the
|
||||
@@ -1615,10 +1688,14 @@ 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());"
|
||||
),
|
||||
);
|
||||
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");
|
||||
let pdf = vectorcraft_pdf::import(&bytes).unwrap();
|
||||
@@ -1630,7 +1707,6 @@ fn closing_with_save_changes_keeps_the_documents_format() {
|
||||
assert!(sizes.iter().any(|&s| near(s, (5.0, 5.0))), "the file holds the rectangle drawn after the first save: {sizes:?}");
|
||||
assert!(sizes.iter().any(|&s| near(s, (50.0, 20.0))), "and the first one: {sizes:?}");
|
||||
assert!(s.documents().is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `close(SaveOptions.SAVECHANGES)` on a document whose last save named some of its artboards
|
||||
@@ -1661,7 +1737,7 @@ fn closing_with_save_changes_refuses_a_save_of_some_artboards() {
|
||||
}
|
||||
assert_eq!(drawn, 0, "the file is left as the first save wrote it");
|
||||
assert!(s.active().unwrap().is_dirty(), "the change is still unsaved");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1705,7 +1781,7 @@ fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() {
|
||||
assert!(e.contains("some of its artboards"), "{e}");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
assert_eq!(std::fs::read(dir.join("grown.pdf")).unwrap(), before);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// The artboard check of `close(SaveOptions.SAVECHANGES)` follows the file the save writes: a PDF
|
||||
@@ -1741,7 +1817,7 @@ fn closing_with_save_changes_checks_the_artboards_the_file_keeps() {
|
||||
);
|
||||
assert!(s.documents().is_empty(), "the .ai file keeps every artboard, so it closes");
|
||||
assert_ne!(std::fs::read(&ai).unwrap(), before, "and the change is saved");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// A native file and a `.ai` file saved without separate artboard files, and an SVG file that
|
||||
@@ -1777,7 +1853,7 @@ fn closing_with_save_changes_saves_files_that_keep_every_artboard() {
|
||||
s.execute("document.open", &json!({"path": file.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 2, "{name} keeps both artboards");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1814,7 +1890,7 @@ fn closing_with_save_changes_keeps_all_eps_artboards_for_subset_ranges() {
|
||||
assert!(s.active().unwrap().doc.node_count() > nodes, "{range}");
|
||||
logged(&mut s, &base, "app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1853,7 +1929,7 @@ fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() {
|
||||
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);");
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1873,7 +1949,7 @@ fn document_path_reflection_describes_folders_and_unsaved_strings() {
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([["Folder|string", true], ["Folder|string", "Folder"], [true, dir.to_string_lossy()]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// Setting `Document.saved` records the document's saved state without saving it: `true` lets
|
||||
@@ -1902,7 +1978,6 @@ fn setting_saved_records_the_saved_state() {
|
||||
assert_eq!(out[5][1], json!(1), "a document set as unsaved stays open");
|
||||
assert!(out[6].as_str().unwrap().contains("true or false"), "{}", out[6]);
|
||||
assert!(s.active().unwrap().is_dirty(), "the state stays after the run");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The warnings of a save go to the console after the method's name.
|
||||
@@ -1915,7 +1990,7 @@ fn save_as_writes_its_warnings_to_the_console() {
|
||||
let r = run(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("two.svg")))).unwrap();
|
||||
let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("saveAs: ")), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// A point change that waits to be written counts as an unsaved change for `saved` and `close`.
|
||||
@@ -1939,7 +2014,7 @@ fn waiting_point_changes_count_as_unsaved_changes() {
|
||||
assert_eq!(out[0], json!(false), "a waiting point change is unsaved");
|
||||
assert!(out[1][0].as_str().unwrap().contains("unsaved changes"), "{}", out[1]);
|
||||
assert_eq!(out[1][1], json!(1), "close() keeps the document open");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1957,7 +2032,7 @@ fn unchanged_saved_assignments_do_not_record_commands() {
|
||||
assert_eq!(out, json!([true, false, true]));
|
||||
let changes: Vec<_> = s.journal.iter().filter(|(id, _)| id == "document.setSaved").map(|(_, p)| p["saved"].clone()).collect();
|
||||
assert_eq!(changes, [json!(false), json!(true)]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// With automation read roots that leave out the document's file, `fullName` and `path` throw
|
||||
@@ -1994,7 +2069,6 @@ fn full_name_and_path_leave_out_a_file_outside_the_read_roots() {
|
||||
assert!(e.contains(DENIED) && !e.contains("outside"), "SAVECHANGES does not write a file the script may not: {e}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), before, "the file is left as it was");
|
||||
assert_eq!(s.documents().len(), 1, "the document stays open");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2023,7 +2097,7 @@ fn implicit_multifile_save_redacts_preflight_refusals_before_writing() {
|
||||
let explicit =
|
||||
crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({"path": path.to_string_lossy()}))).unwrap_err().to_string();
|
||||
assert!(explicit.contains(path.to_string_lossy().as_ref()), "{explicit}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
drop(base);
|
||||
}
|
||||
|
||||
/// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name
|
||||
@@ -2058,7 +2132,6 @@ fn a_bracketed_pdf_preset_names_the_built_in_preset() {
|
||||
);
|
||||
assert!(e.contains("unknown PDF preset"), "{bad}: {e}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A number given as `artboardRange` is read as `String(number)` reads it.
|
||||
@@ -2081,7 +2154,6 @@ fn a_number_artboard_range_names_that_artboard() {
|
||||
assert_eq!(pdf.artboards.len(), 1, "one page");
|
||||
let r = pdf.artboards[0].rect;
|
||||
assert!((r.width() - 60.0).abs() < 0.01 && (r.height() - 80.0).abs() < 0.01, "the second artboard: {r:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// With `saveMultipleArtboards`, a `.ai` or EPS save also writes a file for each artboard of
|
||||
@@ -2143,5 +2215,4 @@ fn save_multiple_artboards_writes_a_file_per_artboard() {
|
||||
assert!(e.contains("range"), "{bad}: {e}");
|
||||
}
|
||||
assert!(!dir.join("aioff/b.ai").exists(), "a bad range writes nothing");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
//! 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";
|
||||
|
||||
#[test]
|
||||
fn screen_width_and_height_reject_effective_scales_outside_the_encoder_range() {
|
||||
for mode in ["SCALEBYWIDTH", "SCALEBYHEIGHT"] {
|
||||
for pixels in [65.0, 0.001] {
|
||||
let base = vectorcraft_testkit::TempDir::new("screen-size-limit");
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let output = dir.join("scaled");
|
||||
let source = format!(
|
||||
"Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 1, 1); \
|
||||
var o = new ExportForScreensOptionsPNG24(); \
|
||||
o.scaleType = ExportForScreensScaleType.{mode}; o.scaleTypeValue = {pixels}; \
|
||||
d.exportForScreens(new Folder({}), ExportForScreensType.SE_PNG24, o);",
|
||||
quoted(&output)
|
||||
);
|
||||
let error = failure(&mut s, &base, &source);
|
||||
assert!(error.contains("scale"), "{mode}: {pixels}: {error}");
|
||||
assert!(!output.exists(), "{mode}: {pixels}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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 volume root the person picked is a folder the export may write into: the export goes on to
|
||||
/// the command, which here refuses an asset the document does not have, and writes nothing.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_picked_volume_root_is_a_folder_to_export_into() {
|
||||
let base = vectorcraft_testkit::TempDir::new("screen-root");
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
let mut s = session(&base);
|
||||
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
|
||||
s.script_frames = true;
|
||||
let main = base.join("main/main.jsx");
|
||||
let script = "var p = Folder.selectDialog('p'); var i = new ExportForScreensItemToExport(); i.artboards = ''; i.assets = [987654321];\n\
|
||||
try { app.activeDocument.exportForScreens(p, ExportForScreensType.SE_PNG24, undefined, i); vc.log('exported'); } catch (e) { vc.log(String(e)); }";
|
||||
std::fs::write(&main, script).unwrap();
|
||||
assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true);
|
||||
let mut picked = false;
|
||||
let mut report = None;
|
||||
for _ in 0..10_000 {
|
||||
if !picked && s.script_picker().is_some() {
|
||||
picked = true;
|
||||
assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec!["/".into()], always: false }));
|
||||
}
|
||||
if let Some(r) = s.script_pump() {
|
||||
report = Some(r.unwrap());
|
||||
break;
|
||||
}
|
||||
}
|
||||
let report = report.unwrap_or_else(|| panic!("the run neither ended nor waited"));
|
||||
assert!(picked, "{report}");
|
||||
let said = report["log"][0].as_str().unwrap_or_default().to_string();
|
||||
assert!(!said.contains(DENIED) && !said.contains("exported") && said.contains("987654321"), "{said}");
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// 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]
|
||||
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:?}");
|
||||
let entries: Vec<_> = std::fs::read_dir(dir.join("up")).unwrap().map(|e| e.unwrap()).collect();
|
||||
assert_eq!(entries.len(), 2, "{entries:?}");
|
||||
assert!(entries.iter().all(|e| e.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!("{e}({f}, ExportForScreensType.SE_PNG24, null);"), "the options must be an object"),
|
||||
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, null);"), "ExportForScreensItemToExport"),
|
||||
(format!("{e}({f}, ExportForScreensType.SE_PNG24, undefined, undefined, null);"), "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);
|
||||
}
|
||||
@@ -47,6 +47,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
("ExternalObject", "var lib = new ExternalObject(n);", "nativeCode"),
|
||||
("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"),
|
||||
("Document.prototype.imageCapture", "app.activeDocument.imageCapture(f);", "filesWritten"),
|
||||
("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"),
|
||||
];
|
||||
@@ -340,6 +341,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Document.prototype.", "rasterize windowCapture windowCapture="),
|
||||
("AntiAliasingMethod.", "ARTOPTIMIZED None TYPEOPTIMIZED"),
|
||||
("RasterizationColorModel.", "BITMAP DEFAULTCOLORMODEL GRAYSCALE"),
|
||||
// The enumerations of exporting for screens (`AntiAliasingMethod`, `SVGCSSPropertyLocation` and `SVGFontType` are above).
|
||||
("", "ExportForScreensScaleType ExportForScreensType JPEGCompressionMethodType RasterImageLocation SVGIdType"),
|
||||
("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"),
|
||||
("SVGIdType.", "SVGIDMINIMAL SVGIDREGULAR SVGIDUNIQUE"),
|
||||
// The enumerations of placed and raster items.
|
||||
("", "ImageColorSpace RasterLinkState"),
|
||||
("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"),
|
||||
@@ -435,6 +443,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"),
|
||||
("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"),
|
||||
("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"),
|
||||
// The text classes and their enumerations.
|
||||
(
|
||||
"",
|
||||
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
|
||||
@@ -572,7 +581,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \
|
||||
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \
|
||||
EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions \
|
||||
ImageCaptureOptions RasterizeOptions";
|
||||
ImageCaptureOptions RasterizeOptions \
|
||||
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.
|
||||
|
||||
@@ -80,6 +80,27 @@ impl Interp {
|
||||
})?;
|
||||
instance(self, proto, fs)
|
||||
}
|
||||
|
||||
/// The [`crate::Data`] for `id` when it is a `File` the `File` class made (its prototype is
|
||||
/// `File.prototype` and it holds its path in its [`Class::FsEntry`]), as [`file_ref_path`] reads
|
||||
/// it, 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)?;
|
||||
let key = if o.proto == Some(c.file_proto) {
|
||||
crate::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![(key.to_string(), crate::Data::String(s.to_rust_string()))])),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of `o` when the `File` or `Folder` class made it.
|
||||
@@ -147,21 +168,6 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of `id` when it is a `File` the `File` class made: its prototype is `File.prototype`
|
||||
/// and it holds its path in its [`Class::FsEntry`]. `None` for anything else, a `Folder` and an
|
||||
/// object made with `Object.create(File.prototype)` included.
|
||||
pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
|
||||
let Some(c) = &i.files else { return Ok(None) };
|
||||
let o = i.object(id)?;
|
||||
if o.proto != Some(c.file_proto) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(match own_path(i, id)? {
|
||||
Some(Value::String(s)) => Some(s.to_rust_string()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> {
|
||||
if let Value::String(s) = &value {
|
||||
i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?;
|
||||
|
||||
+11
-7
@@ -203,9 +203,9 @@ struct Reading {
|
||||
ancestors: Vec<ObjId>,
|
||||
path: Vec<Step>,
|
||||
function: Rc<str>,
|
||||
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under
|
||||
/// [`crate::FILE_REF_KEY`], and a plain object that has one of the keys, or
|
||||
/// [`crate::FOLDER_REF_KEY`], is refused.
|
||||
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` or a `Folder` as its
|
||||
/// path under [`crate::FILE_REF_KEY`] or [`crate::FOLDER_REF_KEY`], and a plain object that has
|
||||
/// one of those keys is refused.
|
||||
hosted: bool,
|
||||
}
|
||||
|
||||
@@ -276,12 +276,16 @@ 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(path) = crate::file_classes::file_path(self, id)?
|
||||
&& let Some(file) = self.file_ref_of(id)?
|
||||
{
|
||||
self.charge_reading(r, path.len().saturating_add(16))?;
|
||||
return Ok(Data::Object(vec![(crate::FILE_REF_KEY.to_string(), Data::String(path))]));
|
||||
let len: usize = 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_add(16))?;
|
||||
return Ok(file);
|
||||
}
|
||||
let shape = match &self.object(id)?.class {
|
||||
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
|
||||
|
||||
@@ -29,7 +29,8 @@
|
||||
//!
|
||||
//! `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.
|
||||
//!
|
||||
@@ -38,7 +39,7 @@
|
||||
//! told always matches what the class has. A class that names a member twice, or describes a member
|
||||
//! it does not have, is refused.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key};
|
||||
@@ -147,10 +148,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<u32>,
|
||||
/// The names of the members `hasOwnProperty` reports: every member but the unavailable ones.
|
||||
own: Rc<HashSet<Key>>,
|
||||
/// The names of the members this class declares as unavailable.
|
||||
unavailable: Rc<HashSet<Key>>,
|
||||
/// The names of the members the class declares, each with whether `hasOwnProperty` reports it:
|
||||
/// every member but the unavailable ones.
|
||||
own: Rc<HashMap<Key, bool>>,
|
||||
/// The class's own members as `reflect` lists them.
|
||||
members: Rc<[Reflected]>,
|
||||
}
|
||||
@@ -250,19 +250,15 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec<f64>)> {
|
||||
|
||||
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. The
|
||||
/// nearest class that declares `k` decides, so a member a class declares unavailable is not
|
||||
/// reported even when a class it descends from has it.
|
||||
/// 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<bool> {
|
||||
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 e.unavailable.contains(k) {
|
||||
return Ok(false);
|
||||
if let Some(available) = e.own.get(k) {
|
||||
return Ok(*available);
|
||||
}
|
||||
class = e.parent;
|
||||
}
|
||||
@@ -625,8 +621,7 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und
|
||||
let r = fill_class(i, proto, &class);
|
||||
i.temp_roots.truncate(mark);
|
||||
let ctor = r?;
|
||||
let (unavailable, own_members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_)));
|
||||
let names = |list: Vec<&(String, HostMember)>| list.into_iter().map(|(name, _)| key(name)).collect::<HashSet<Key>>();
|
||||
let own = 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,
|
||||
@@ -635,8 +630,7 @@ fn install_class(i: &mut Interp, class: HostClass, members: Rc<[Reflected]>, und
|
||||
index: class.index,
|
||||
family,
|
||||
parent: parent_class,
|
||||
own: Rc::new(names(own_members)),
|
||||
unavailable: Rc::new(names(unavailable)),
|
||||
own: Rc::new(own),
|
||||
members,
|
||||
});
|
||||
undo.define_global(i, &class.name, Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN })
|
||||
|
||||
@@ -1129,6 +1129,41 @@ 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())),
|
||||
],
|
||||
info: Vec::new(),
|
||||
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))],
|
||||
info: Vec::new(),
|
||||
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 an_unavailable_member_hides_the_member_its_parent_class_has() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
@@ -27,7 +27,10 @@ use crate::catalog::{self, FeatureId};
|
||||
use crate::directives;
|
||||
use crate::lex::{Lexer, T, Token, expr_after};
|
||||
use crate::report::{self, Acc, OutsideId};
|
||||
use sig::{COMPOUND, LineBreaks, NEWER, Read, Sig, ends_value, for_in, goes_on_after, goes_on_with, is, member_mark, newer_number, unquote, word};
|
||||
use sig::{
|
||||
COMPOUND, LineBreaks, NEWER, Read, Sig, ends_value, exact_unquote, for_in, goes_on_after, goes_on_with, is, member_mark, newer_number, unquote,
|
||||
word,
|
||||
};
|
||||
|
||||
mod declared;
|
||||
mod features;
|
||||
@@ -691,6 +694,18 @@ 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<String, u8>,
|
||||
/// 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<String, usize>,
|
||||
/// [`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 function body that the token being read closed (its `}`): how many bodies were open
|
||||
/// in it and the names it declared. A value read just before the `}` is read in that body.
|
||||
closed_body: Option<(usize, Vec<String>)>,
|
||||
/// The object literals being assigned to a variable, the innermost last, up to
|
||||
/// [`crate::Limits::nesting`] of them.
|
||||
objects: Vec<ObjectValue>,
|
||||
@@ -700,6 +715,29 @@ 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<usize>,
|
||||
/// The last token was the `]` that closes an index of the global object.
|
||||
global_index_closed: bool,
|
||||
/// The offset of the last `]` that closes an index of the global object by a string literal
|
||||
/// alone, with the variable name it reads (`$.global['local']`, `this['local']`), or `None` when
|
||||
/// the literal does not decode to one exact name.
|
||||
global_bracket: Option<(usize, Option<String>)>,
|
||||
/// The offset of the last name read as a property of the global object (`local` in
|
||||
/// `$.global.local`, `globalThis.local` or `this.local`).
|
||||
global_member: Option<usize>,
|
||||
/// The `with` statement whose head is being read: the bracket depth of its `with`, and whether
|
||||
/// its `)` was read.
|
||||
with_head: Option<(usize, bool)>,
|
||||
/// The bracket depths the bodies of the open `with` statements hold at, the innermost last, up
|
||||
/// to [`crate::Limits::nesting`] of them ([`Analyzer::with_step`]).
|
||||
withs: Vec<usize>,
|
||||
/// A `with` statement had no room in [`Analyzer::withs`]: no call of a literal's own method is
|
||||
/// known from then on.
|
||||
withs_full: bool,
|
||||
/// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`].
|
||||
others: bool,
|
||||
/// The variables that may get another value when code read elsewhere runs: assigned inside a
|
||||
@@ -786,9 +824,20 @@ 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(),
|
||||
shared_full: false,
|
||||
closed_body: None,
|
||||
objects: vec![],
|
||||
closed: None,
|
||||
index_receiver: 0,
|
||||
index_stable: false,
|
||||
global_indexes: vec![],
|
||||
global_index_closed: false,
|
||||
global_bracket: None,
|
||||
global_member: None,
|
||||
with_head: None,
|
||||
withs: vec![],
|
||||
withs_full: false,
|
||||
others: known.others || declared.includes,
|
||||
later: HashSet::new(),
|
||||
later_full: false,
|
||||
@@ -872,6 +921,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
|
||||
fn token(&mut self, mut t: Sig<'s>) {
|
||||
self.acc.steps = self.acc.steps.saturating_add(1);
|
||||
self.closed_body = None;
|
||||
// The name of a grouped value whose last `)` was read, or of a value without parentheses that
|
||||
// `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or
|
||||
// closes a function body.
|
||||
@@ -1195,7 +1245,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// in them gets back what it held outside them, and the `var` statement a body was in goes on.
|
||||
fn close_scopes(&mut self) {
|
||||
while self.scopes.last().is_some_and(|s| self.depth() < s.depth) {
|
||||
let open = self.scopes.len();
|
||||
let Some(scope) = self.scopes.pop() else { return };
|
||||
if self.closed_body.is_none() {
|
||||
self.closed_body = Some((open, scope.saved.keys().cloned().collect()));
|
||||
}
|
||||
self.var_depth = scope.var_depth;
|
||||
for (name, saved) in scope.saved {
|
||||
self.restore(name, saved);
|
||||
@@ -1491,6 +1545,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);
|
||||
@@ -1507,13 +1564,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.assign = Some(Assign { name: name.text.to_string(), after_new: false });
|
||||
}
|
||||
}
|
||||
if let Some((name, _)) = self.updated(t)
|
||||
&& !self.scopes.is_empty()
|
||||
&& !self.declared_in_body(name)
|
||||
{
|
||||
self.reassigned_later(name);
|
||||
let updated = self.updated(t);
|
||||
if let Some((name, _)) = updated {
|
||||
self.share_early(name);
|
||||
if !self.scopes.is_empty() && !self.declared_in_body(name) {
|
||||
self.reassigned_later(name);
|
||||
}
|
||||
}
|
||||
match self.updated(t) {
|
||||
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),
|
||||
@@ -1527,19 +1585,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// closes a function body, so a literal given to the body's own variable stays inside the body.
|
||||
/// No variable joins when code the scan does not follow at that point may give it another value:
|
||||
/// a function body that assigns its name ([`Declared::body_assigned`], [`Analyzer::later`]), a
|
||||
/// member assignment of a property of that name, which may be the global object's
|
||||
/// ([`Declared::rebound`]), a function body that assigns a `saveAs` or `exportFile` property of
|
||||
/// any object ([`Declared::body_writer_assigned`]), code given as text or a `with` statement
|
||||
/// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
|
||||
/// function body read before the literal that changes or shares the variable, or assigns a property
|
||||
/// of that name, which may be the global object's ([`Analyzer::shared_early`]), code given as text
|
||||
/// or a `with` statement ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
|
||||
/// assigns the variable use [`Declared::looped`] to classify its methods.
|
||||
fn settle_literal(&mut self, t: &Sig<'s>) {
|
||||
if let Some((name, bits)) = self.closed.take()
|
||||
&& (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t)))
|
||||
&& !self.shared_full
|
||||
&& self.shared_early.get(&name).is_none_or(|&open| open <= self.scopes.len())
|
||||
&& !self.unsure
|
||||
&& !self.others
|
||||
&& !self.declared.rebound.contains(&name)
|
||||
&& !self.declared.body_assigned.contains(name.as_str())
|
||||
&& !self.declared.body_writer_assigned
|
||||
&& !self.later_full
|
||||
&& !self.later.contains(&name)
|
||||
&& !self.declared.looped_full
|
||||
@@ -1586,8 +1643,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);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::{
|
||||
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark,
|
||||
unquote, word,
|
||||
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, exact_unquote, for_in, goes_on_after, goes_on_with, is,
|
||||
member_mark, unquote, word,
|
||||
};
|
||||
|
||||
/// The names that give variables values the analysis doesn't read: a `with` statement makes an
|
||||
@@ -76,11 +76,16 @@ pub(crate) struct Declared<'s> {
|
||||
/// also before its body in the text when it is a declaration, so a variable of that name may lose
|
||||
/// the value an assignment the analysis read gave it.
|
||||
pub(super) body_assigned: HashSet<&'s str>,
|
||||
/// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`]
|
||||
/// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is
|
||||
/// defined, and the object may be any variable's, so no variable's method of that name stays
|
||||
/// the script's own.
|
||||
pub(super) body_writer_assigned: bool,
|
||||
/// The variables whose document write method a function body may replace (`local.saveAs = …`,
|
||||
/// `local['saveAs'] += …`, `local[k] = …`, `var y = local`), unless the body declared the name
|
||||
/// before it, each by the offset of the `{` of the function body that declares it anywhere in
|
||||
/// the body (`None`: the global code's). The function may run at any time after it is defined,
|
||||
/// also before its body in the text when it is a declaration.
|
||||
pub(super) method_replaced: HashSet<(Option<usize>, &'s str)>,
|
||||
/// The variables of [`Declared::method_replaced`] whose declaring body is not known, because a
|
||||
/// body around the replacement is past [`crate::Limits::nesting`] or ran out of room for its
|
||||
/// names: the replacement counts for a variable of that name in any body.
|
||||
pub(super) method_replaced_any: HashSet<&'s str>,
|
||||
/// The file has an `#include` line: the included file's code may give its variables values.
|
||||
pub(super) includes: bool,
|
||||
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
|
||||
@@ -139,6 +144,9 @@ struct Declarations<'s, 'a, 'l> {
|
||||
brackets: Brackets,
|
||||
/// The three significant tokens before this one, the latest first.
|
||||
h: [Option<Sig<'s>>; 3],
|
||||
/// The two significant tokens before the three of `h`, the latest first.
|
||||
h3: Option<Sig<'s>>,
|
||||
h4: Option<Sig<'s>>,
|
||||
/// `function` was read at this bracket depth, and its body's `{` is still to come.
|
||||
function: Option<usize>,
|
||||
/// The bracket depth of the `var` statement being read.
|
||||
@@ -155,6 +163,20 @@ struct Declarations<'s, 'a, 'l> {
|
||||
keys: Vec<Key>,
|
||||
/// The loops being read, the innermost last, up to [`crate::Limits::nesting`].
|
||||
loops: Vec<Loop>,
|
||||
/// The replacements of a variable's methods ([`Declared::method_replaced`]) read so far, each with
|
||||
/// the entries of [`Declared::bodies`] around it, the outermost first. A `var` statement later in
|
||||
/// a body declares the name for the whole body, so the body that declares the variable is found
|
||||
/// once every body's names are known.
|
||||
replaced: HashSet<(Vec<usize>, &'s str)>,
|
||||
/// The entries of [`Declared::bodies`] whose names ran out of room: one of them may declare any
|
||||
/// name.
|
||||
names_full: HashSet<usize>,
|
||||
/// The parameters of the function whose parentheses are being read: the bracket depth inside
|
||||
/// them, the names so far, and whether they ran out of room.
|
||||
params: Option<(usize, Vec<&'s str>, bool)>,
|
||||
/// The parameters of each entry of [`Declared::bodies`], which are the body's own variables
|
||||
/// (ECMA-262 3rd edition, section 10.1.3).
|
||||
body_params: HashMap<usize, Vec<&'s str>>,
|
||||
out: Declared<'s>,
|
||||
}
|
||||
|
||||
@@ -200,6 +222,8 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
acc,
|
||||
brackets: Brackets::default(),
|
||||
h: [None; 3],
|
||||
h3: None,
|
||||
h4: None,
|
||||
function: None,
|
||||
var_depth: None,
|
||||
assign: None,
|
||||
@@ -207,6 +231,10 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
untracked: None,
|
||||
keys: vec![],
|
||||
loops: vec![],
|
||||
replaced: HashSet::new(),
|
||||
names_full: HashSet::new(),
|
||||
params: None,
|
||||
body_params: HashMap::new(),
|
||||
out: Declared::default(),
|
||||
};
|
||||
let mut breaks = LineBreaks::default();
|
||||
@@ -221,6 +249,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
while let Some(body) = d.bodies.pop() {
|
||||
d.settle_looped(body);
|
||||
}
|
||||
d.settle_replaced();
|
||||
let mut out = d.out;
|
||||
for ids in out.looped.values_mut() {
|
||||
ids.sort_unstable();
|
||||
@@ -255,6 +284,17 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
self.bracket(&t);
|
||||
} else if t.kind == T::Ident {
|
||||
self.declaration(&t);
|
||||
let depth = self.depth();
|
||||
if let Some((at, names, full)) = self.params.as_mut()
|
||||
&& *at == depth
|
||||
&& (is(h0, "(") || is(h0, ","))
|
||||
{
|
||||
if self.acc.room(names.len()) {
|
||||
names.push(t.text);
|
||||
} else {
|
||||
*full = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let depth = self.depth();
|
||||
self.loop_end(&t, depth);
|
||||
@@ -266,6 +306,27 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
{
|
||||
self.looped(name.text);
|
||||
}
|
||||
// `o.local = …` or `o['local'] = …` in a loop: the object may be the global object
|
||||
// ([`Declared::rebound`]), so the global variable of that name may get another value on each
|
||||
// pass. A key with an escape may spell any name: any variable may be assigned in a loop.
|
||||
if t.is("=") && !self.loops.is_empty() {
|
||||
let property = if member_mark(h1) {
|
||||
h0.filter(|s| s.kind == T::Ident).map(|s| s.text)
|
||||
} else if is(h0, "]") && is(self.h[2], "[") {
|
||||
let key = h1.filter(|s| s.kind == T::Str);
|
||||
if key.is_some_and(|s| s.text.contains('\\')) {
|
||||
self.out.looped_full = true;
|
||||
}
|
||||
key.filter(|s| s.text.len() >= 2 && !s.text.contains('\\')).and_then(|s| s.text.get(1..s.text.len() - 1))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = property {
|
||||
let id = self.out.loop_spans.len().saturating_sub(1);
|
||||
self.keep_looped(None, name, vec![id]);
|
||||
}
|
||||
}
|
||||
self.method_replacement(&t);
|
||||
if let Some(after_new) = self.assign.take() {
|
||||
if t.word("new") && !after_new {
|
||||
self.assign = Some(true);
|
||||
@@ -289,9 +350,123 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if !self.bodies.is_empty() || self.untracked.is_some() {
|
||||
self.body_assignment(&t, depth);
|
||||
}
|
||||
self.h4 = self.h3;
|
||||
self.h3 = self.h[2];
|
||||
self.h = [Some(t), h0, h1];
|
||||
}
|
||||
|
||||
/// `t` changes or shares a variable's methods, as [`Analyzer::writer_use`] reads it: `=`, a
|
||||
/// compound operator, `++` or `--` on `local.saveAs` or `local['saveAs']` (one of the document
|
||||
/// write methods), `++local.saveAs`, a key in brackets that is not one string literal
|
||||
/// (`local[k]`, `local['sa' + 'veAs']`), `delete local`, or `local` used as a value
|
||||
/// (`var y = local`, `f(local)`), where another name may hold its object. In a loop, `local` may
|
||||
/// hold another method when a call of it earlier in the loop runs again ([`Declared::looped`]); in
|
||||
/// a function body that does not declare `local`, the function may replace the method before any
|
||||
/// call of it runs ([`Declared::method_replaced`]).
|
||||
fn method_replacement(&mut self, t: &Sig<'s>) {
|
||||
let [h0, h1, h2] = self.h;
|
||||
let (h3, h4) = (self.h3, self.h4);
|
||||
let ident = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| s.kind == T::Ident && !member_mark(before));
|
||||
let write = |s: Option<Sig<'s>>| s.is_some_and(|s| s.kind == T::Ident && catalog::DOM_FILE_WRITES.contains(&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 receiver = if changes && is(h1, ".") && write(h0) {
|
||||
ident(h2, h3)
|
||||
} else if changes
|
||||
&& is(h0, "]")
|
||||
&& is(h2, "[")
|
||||
&& let Some(key) = h1.filter(|s| s.kind == T::Str)
|
||||
{
|
||||
// A key whose escapes do not decode to one exact name may spell any method's.
|
||||
let writes = exact_unquote(key.text).is_none_or(|m| catalog::DOM_FILE_WRITES.contains(&m.as_str()));
|
||||
ident(h3, h4).filter(|_| writes)
|
||||
} else if is(h0, ".") && (is(h2, "++") || is(h2, "--")) && write(Some(*t)) && (h2.is_some_and(|s| s.nl) || !h1.is_some_and(|s| s.nl)) {
|
||||
// `++local.saveAs`, not `n++` ending the line before `local.saveAs`.
|
||||
ident(h1, h2)
|
||||
} else if word(h0, "delete") {
|
||||
ident(Some(*t), h0)
|
||||
} else if let Some(name) = ident(h0, h1).filter(|_| !t.is(".") && !t.is("[") && !t.is("=") && !key) {
|
||||
// `local` used as a value, or changed by a compound or update operator.
|
||||
Some(name)
|
||||
} else if is(h0, "[") {
|
||||
// `local[k]`: a key that is not one string or number literal may name any method.
|
||||
ident(h1, h2).filter(|_| t.kind != T::Str && t.kind != T::Number)
|
||||
} else if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str || s.kind == T::Number) {
|
||||
// `local['sa' + k]`
|
||||
ident(h2, h3).filter(|_| !t.is("]"))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(name) = receiver.map(|s| s.text) else { return };
|
||||
if !self.loops.is_empty() {
|
||||
self.looped(name);
|
||||
}
|
||||
// Only the innermost body's own variable is not the one a nested function may reach from
|
||||
// outside before the call runs.
|
||||
let own = self.untracked.is_none()
|
||||
&& self.bodies.last().is_some_and(|b| b.names.contains(name) || self.body_params.get(&b.index).is_some_and(|p| p.contains(&name)));
|
||||
if (!self.bodies.is_empty() || self.untracked.is_some()) && !own {
|
||||
if self.untracked.is_some() {
|
||||
// A body past the nesting limit keeps no names, so any body around may declare the
|
||||
// variable.
|
||||
if self.out.method_replaced_any.contains(name) || self.acc.room(self.out.method_replaced_any.len()) {
|
||||
self.out.method_replaced_any.insert(name);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
} else {
|
||||
let key = (self.bodies.iter().map(|b| b.index).collect::<Vec<_>>(), name);
|
||||
if self.replaced.contains(&key) || self.acc.room(self.replaced.len()) {
|
||||
self.replaced.insert(key);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps each replacement in [`Self::replaced`] for the innermost body around it that declares
|
||||
/// the variable anywhere in the body, or as a parameter, or for the global code when none does.
|
||||
/// A replacement of a variable of the innermost body itself is not kept, as when the body
|
||||
/// declared it before the replacement. When a body around it ran out of room for its names, the
|
||||
/// body that declares the variable is not known, and the replacement counts for the variable of
|
||||
/// that name in every body ([`Declared::method_replaced_any`]).
|
||||
fn settle_replaced(&mut self) {
|
||||
for (around, name) in std::mem::take(&mut self.replaced) {
|
||||
let mut owner = None;
|
||||
let mut known = true;
|
||||
for (i, &index) in around.iter().enumerate().rev() {
|
||||
if self.out.bodies.get(index).is_some_and(|(_, names)| names.contains(&name))
|
||||
|| self.body_params.get(&index).is_some_and(|p| p.contains(&name))
|
||||
{
|
||||
owner = self.out.bodies.get(index).map(|(at, _)| (*at, i + 1 == around.len()));
|
||||
break;
|
||||
}
|
||||
if self.names_full.contains(&index) {
|
||||
known = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
if self.out.method_replaced_any.contains(name) || self.acc.room(self.out.method_replaced_any.len()) {
|
||||
self.out.method_replaced_any.insert(name);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if owner.is_some_and(|(_, innermost)| innermost) {
|
||||
continue;
|
||||
}
|
||||
let key = (owner.map(|(at, _)| at), name);
|
||||
if self.out.method_replaced.contains(&key) || self.acc.room(self.out.method_replaced.len()) {
|
||||
self.out.method_replaced.insert(key);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one
|
||||
/// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`].
|
||||
fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) {
|
||||
@@ -557,9 +732,6 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
None
|
||||
};
|
||||
if let Some(name) = property {
|
||||
if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) {
|
||||
self.out.body_writer_assigned = true;
|
||||
}
|
||||
if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) {
|
||||
self.out.rebound.insert(name);
|
||||
} else {
|
||||
@@ -579,7 +751,11 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
match t.text {
|
||||
"(" | "[" | "{" => {
|
||||
let body = t.text == "{" && self.function.take() == Some(self.depth());
|
||||
let params = t.text == "(" && self.function == Some(self.depth());
|
||||
self.brackets.open(t, self.acc.limits.nesting);
|
||||
if params {
|
||||
self.params = Some((self.depth(), vec![], false));
|
||||
}
|
||||
if t.text == "[" {
|
||||
// After a value, `[` starts a property's name in brackets (ECMA-262 3rd
|
||||
// edition, section 11.2.1); elsewhere it starts an array literal.
|
||||
@@ -593,8 +769,17 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if !body {
|
||||
return;
|
||||
}
|
||||
let params = self.params.take();
|
||||
if self.bodies.len() < self.acc.limits.nesting {
|
||||
let index = self.out.bodies.len();
|
||||
if let Some((_, names, full)) = params {
|
||||
if full {
|
||||
self.names_full.insert(index);
|
||||
}
|
||||
if !names.is_empty() {
|
||||
self.body_params.insert(index, names);
|
||||
}
|
||||
}
|
||||
self.out.bodies.push((t.start, vec![]));
|
||||
self.bodies.push(Body {
|
||||
depth: self.depth(),
|
||||
@@ -652,10 +837,14 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
return;
|
||||
}
|
||||
if let Some(body) = self.bodies.last_mut() {
|
||||
if (var || body.depth == depth) && !body.names.contains(t.text) && self.acc.room(body.names.len()) {
|
||||
body.names.insert(t.text);
|
||||
if let Some((_, names)) = self.out.bodies.get_mut(body.index) {
|
||||
names.push(t.text);
|
||||
if (var || body.depth == depth) && !body.names.contains(t.text) {
|
||||
if self.acc.room(body.names.len()) {
|
||||
body.names.insert(t.text);
|
||||
if let Some((_, names)) = self.out.bodies.get_mut(body.index) {
|
||||
names.push(t.text);
|
||||
}
|
||||
} else {
|
||||
self.names_full.insert(body.index);
|
||||
}
|
||||
}
|
||||
} else if function && depth == 0 && !self.out.global.contains(t.text) && self.acc.room(self.out.global.len()) {
|
||||
|
||||
@@ -1,6 +1,36 @@
|
||||
//! The platform features, menu commands and later syntax the analysis recognises.
|
||||
|
||||
use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word};
|
||||
use super::{
|
||||
Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, exact_unquote, 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 {
|
||||
@@ -85,6 +115,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.with_step(t);
|
||||
self.writer_use(t);
|
||||
match t.kind {
|
||||
T::Ident => self.name(t, line),
|
||||
@@ -292,7 +323,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
// `local['saveAs']`: what the object before the bracket defines, for a call that may follow.
|
||||
"[" => self.index_receiver = self.writer_bits(h0, h1, Some(t.start)),
|
||||
"[" => {
|
||||
self.index_receiver = self.writer_bits(h0, h1, Some(t.start));
|
||||
self.index_stable = h0.is_some_and(|r| self.stable(r.text));
|
||||
}
|
||||
"(" => self.call(t, line),
|
||||
// `Name.prototype["+"] = …` defines an operator.
|
||||
"=" => {
|
||||
@@ -338,15 +372,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
chain.and_then(|c| c.path.strip_suffix(called))
|
||||
}
|
||||
|
||||
/// `(` after a name: a call.
|
||||
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
||||
/// What the call whose `(` is the current token reaches.
|
||||
fn classify_call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
// `doc['saveAs'](f)`, `doc['exportVariables'](f)` and `app['open'](f)`: a method named by a string literal in brackets.
|
||||
if is(h0, "]")
|
||||
&& is(h2, "[")
|
||||
&& let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
|
||||
{
|
||||
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !Self::defines(self.index_receiver, &name))
|
||||
if (catalog::DOM_FILE_WRITES.contains(&name.as_str()) && !(self.index_stable && Self::defines(self.index_receiver, &name)))
|
||||
|| (name == catalog::DOM_PRINT && self.document_print("[]()"))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
@@ -388,7 +422,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
{
|
||||
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, Some(t.start)), n))
|
||||
|| (catalog::DOM_FILE_WRITES.contains(&n)
|
||||
&& !(h2.is_some_and(|r| self.stable(r.text)) && Self::defines(self.writer_bits(h2, h3, Some(t.start)), n)))
|
||||
|| (n == catalog::DOM_PRINT && self.document_print(".print()"))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
@@ -413,6 +448,113 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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. Inside the body of a
|
||||
/// `with` statement the name may be a property of the statement's object, so no call is known
|
||||
/// there ([`Analyzer::with_step`]).
|
||||
fn stable(&self, name: &str) -> bool {
|
||||
!self.withs_full && self.withs.is_empty() && self.scopes.last().is_none_or(|s| s.saved.contains_key(name))
|
||||
}
|
||||
|
||||
/// Follows the `with` statements around `t`. A body in braces ends with its `}`; a body without
|
||||
/// braces is taken to last until the block the statement is in closes.
|
||||
fn with_step(&mut self, t: &Sig<'s>) {
|
||||
let depth = self.depth();
|
||||
self.withs.retain(|d| *d <= depth);
|
||||
match self.with_head {
|
||||
Some((d, false)) if t.is(")") && depth == d => self.with_head = Some((d, true)),
|
||||
Some((d, true)) => {
|
||||
self.with_head = None;
|
||||
let body = if t.is("{") { depth } else { d };
|
||||
if self.withs.len() < self.acc.limits.nesting {
|
||||
self.withs.push(body);
|
||||
} else {
|
||||
self.withs_full = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if t.kind == T::Ident && t.text == "with" && !member_mark(self.h[0]) {
|
||||
self.with_head = Some((depth, false));
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` may have been given another value through the global object: neither the variable
|
||||
/// nor the outer variables of that name that the open function bodies and `catch` blocks keep
|
||||
/// to put back hold their literal's methods any longer.
|
||||
fn forget_writer(&mut self, name: &str) {
|
||||
self.writers.remove(name);
|
||||
for s in &mut self.scopes {
|
||||
if let Some(saved) = s.saved.get_mut(name) {
|
||||
saved.writer = 0;
|
||||
}
|
||||
}
|
||||
for c in self.catches.iter_mut().filter(|c| c.name == name) {
|
||||
c.saved.writer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The global variable `name` read through the global object may be held under another name
|
||||
/// ([`Self::forget_writer`]). A variable of that name that the innermost function body or a
|
||||
/// `catch` block declares is another variable, and keeps its literal's methods.
|
||||
fn forget_global_writer(&mut self, name: &str) {
|
||||
let shadowed = self.scopes.last().is_some_and(|s| s.saved.contains_key(name)) || self.catches.iter().any(|c| c.name == name);
|
||||
if !shadowed {
|
||||
self.forget_writer(name);
|
||||
return;
|
||||
}
|
||||
for s in &mut self.scopes {
|
||||
if let Some(saved) = s.saved.get_mut(name) {
|
||||
saved.writer = 0;
|
||||
}
|
||||
}
|
||||
for c in self.catches.iter_mut().filter(|c| c.name == name) {
|
||||
c.saved.writer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Any variable may have been given another value through the global object
|
||||
/// ([`Self::forget_writer`] for every name).
|
||||
fn forget_writers(&mut self) {
|
||||
self.writers.clear();
|
||||
for saved in self.scopes.iter_mut().flat_map(|s| s.saved.values_mut()) {
|
||||
saved.writer = 0;
|
||||
}
|
||||
for c in &mut self.catches {
|
||||
c.saved.writer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
self.share_early_as(name, false);
|
||||
}
|
||||
|
||||
/// [`Analyzer::share_early`], and with `global` set, for the global variable `name` read through
|
||||
/// the global object (`$.global.local`) even when the body declares a variable of that name.
|
||||
fn share_early_as(&mut self, name: &str, global: bool) {
|
||||
// A value read just before the `}` that closes a function body is read in that body.
|
||||
let (open, declared) = match &self.closed_body {
|
||||
Some((open, names)) => (*open, names.iter().any(|n| n == name)),
|
||||
None => match self.scopes.last() {
|
||||
Some(body) => (self.scopes.len(), body.saved.contains_key(name)),
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
if (declared && !global) || self.writers.contains_key(name) {
|
||||
return;
|
||||
}
|
||||
if self.shared_early.contains_key(name) || self.acc.room(self.shared_early.len()) {
|
||||
let seen = self.shared_early.entry(name.to_string()).or_insert(open);
|
||||
*seen = (*seen).max(open);
|
||||
} else {
|
||||
self.shared_full = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `receiver`, which `before` comes before, is the application object: the name `app`
|
||||
/// that no `.` comes before and that the script has not declared as its own.
|
||||
fn app_receiver(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> bool {
|
||||
@@ -430,9 +572,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) {
|
||||
return 0;
|
||||
}
|
||||
// A function body that replaces the method may run before the call, wherever it is in
|
||||
// the text. The replacement is kept for the body that declares the variable: the
|
||||
// innermost body around the call that declares it, or the global code.
|
||||
let looped = at.is_some_and(|at| {
|
||||
let owner = self.scopes.iter().rev().find(|s| s.saved.get(r.text).is_some_and(|v| v.local)).map(|s| s.start);
|
||||
self.declared.looped_full
|
||||
|| self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| {
|
||||
|| self.declared.method_replaced_any.contains(r.text)
|
||||
|| self.declared.method_replaced.contains(&(owner, r.text))
|
||||
|| self.declared.looped.get(&(owner, r.text)).is_some_and(|ids| {
|
||||
let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at);
|
||||
next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok())
|
||||
})
|
||||
@@ -447,9 +595,39 @@ 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. 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.kind == T::Ident
|
||||
&& is(h0, ".")
|
||||
&& ((word(h1, "global") && is(h2, ".") && word(h3, "$") && !member_mark(self.h4))
|
||||
|| ((word(h1, "this") || word(h1, "globalThis")) && !member_mark(h2)))
|
||||
{
|
||||
self.global_member = Some(t.start);
|
||||
}
|
||||
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);
|
||||
// `$.global['local']` or `this['local']`: the `]` reads the global variable `local`.
|
||||
if self.global_index_closed
|
||||
&& is(h1, "[")
|
||||
&& let Some(key) = h0.filter(|s| s.kind == T::Str)
|
||||
{
|
||||
self.global_bracket = Some((t.start, exact_unquote(key.text)));
|
||||
}
|
||||
}
|
||||
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
|
||||
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
|
||||
// `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a
|
||||
@@ -468,31 +646,166 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.reassigned_global(&name);
|
||||
}
|
||||
}
|
||||
let h4 = self.h4;
|
||||
// `$.global.local`, `globalThis.local` or `this.local`: `h2` names the global variable `local`.
|
||||
let global_member = h2.is_some_and(|s| self.global_member == Some(s.start));
|
||||
let writer = |s: Option<Sig<'s>>, before: Option<Sig<'s>>| s.filter(|s| self.writer_bits(Some(*s), before, None) != 0).map(|s| s.text);
|
||||
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'] = …`, not `other.local['saveAs'] = …`.
|
||||
writer(h3, self.h4)
|
||||
let escape = |writer: &dyn Fn(Option<Sig<'s>>, Option<Sig<'s>>) -> 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 = …` or `$.global.local.saveAs = …`
|
||||
writer(h2, if global_member { None } else { 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'] = …`, not `other.local['saveAs'] = …`.
|
||||
writer(h3, h4)
|
||||
} 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<Sig<'s>>, before: Option<Sig<'s>>| {
|
||||
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.share_early(name);
|
||||
}
|
||||
// `$.global['local']` or `this['local']` used as a value (`var alias = $.global['local']`,
|
||||
// `f(this['local'])`): another name may hold the global variable's object.
|
||||
if !changes
|
||||
&& !t.is(".")
|
||||
&& !t.is("[")
|
||||
&& let Some((_, name)) = self.global_bracket.as_ref().filter(|(at, _)| h0.is_some_and(|s| s.start == *at))
|
||||
{
|
||||
match name.clone() {
|
||||
Some(name) => {
|
||||
self.forget_global_writer(&name);
|
||||
self.share_early_as(&name, true);
|
||||
}
|
||||
None => self.forget_writers(),
|
||||
}
|
||||
}
|
||||
// `$.global.local`, `this.local` or `globalThis.local` used as a value (`var alias = this.local`),
|
||||
// not `holder.local`: another name may hold the global variable's object.
|
||||
if !changes
|
||||
&& !t.is(".")
|
||||
&& !t.is("[")
|
||||
&& let Some(m) = h0.filter(|s| s.kind == T::Ident && self.global_member == Some(s.start))
|
||||
{
|
||||
self.forget_global_writer(m.text);
|
||||
self.share_early_as(m.text, true);
|
||||
}
|
||||
// A document write method of a global variable replaced through a bracket form:
|
||||
// `$.global['local'].saveAs = …`, `this['local']['saveAs'] = …` or `$.global.local['saveAs'] = …`.
|
||||
if changes {
|
||||
let write_key = |s: Option<Sig<'s>>| s.is_some_and(|m| catalog::DOM_FILE_WRITES.contains(&unquote(m.text, 32).as_str()));
|
||||
let bracketed =
|
||||
|s: Option<Sig<'s>>| s.and_then(|s| self.global_bracket.as_ref().filter(|(at, _)| *at == s.start).map(|(_, name)| name.clone()));
|
||||
let global = if is(h1, ".") && h0.is_some_and(|m| m.kind == T::Ident) && write_key(h0) {
|
||||
bracketed(h2)
|
||||
} else if is(h0, "]") && is(h2, "[") && h1.is_some_and(|m| m.kind == T::Str) && write_key(h1) {
|
||||
bracketed(h3).or_else(|| h3.filter(|s| s.kind == T::Ident && self.global_member == Some(s.start)).map(|s| Some(s.text.to_string())))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match global {
|
||||
// The global variable's value may be saved under a body's or a `catch`'s own variable of
|
||||
// that name, so forget every value of the name.
|
||||
Some(Some(name)) => {
|
||||
self.forget_writer(&name);
|
||||
self.share_early_as(&name, true);
|
||||
}
|
||||
// A key that does not decode to one exact name may name any variable.
|
||||
Some(None) => self.forget_writers(),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
// A name read in a function body that the body does not declare, as a receiver or otherwise. A
|
||||
// receiver is settled once its member is read: assigning a property that is not one of the
|
||||
// document methods that write a file (`d.n = 1`) leaves its methods as they are.
|
||||
if let Some(r) = h0.filter(|r| r.kind == T::Ident && !member_mark(h1) && !RESERVED.contains(&r.text) && !t.is(".")) {
|
||||
self.share_early(r.text);
|
||||
}
|
||||
if let Some(r) = h2.filter(|r| is(h1, ".") && r.kind == T::Ident && (!member_mark(h3) || global_member) && !RESERVED.contains(&r.text)) {
|
||||
let own_property = t.is("=") && h0.is_some_and(|m| m.kind == T::Ident && !catalog::DOM_FILE_WRITES.contains(&m.text));
|
||||
if !own_property {
|
||||
self.share_early_as(r.text, global_member);
|
||||
}
|
||||
}
|
||||
if changes {
|
||||
// A member assignment of a property `local` (`o.local = …`, `o['local'] = …`): the object may
|
||||
// be the global object (`this`, `globalThis`, `$.global`, or any object holding it, as
|
||||
// `holder.this`), so the variable of that name may get another value.
|
||||
let rebound = if is(h1, ".") {
|
||||
h0.filter(|s| s.kind == T::Ident).map(|s| Some(s.text.to_string()))
|
||||
} else if is(h0, "]") && is(h2, "[") && h1.is_some_and(|s| s.kind == T::Str) {
|
||||
h1.filter(|s| s.kind == T::Str).map(|s| exact_unquote(s.text))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(Some(name)) = rebound {
|
||||
// In a function body: the function may run after a later literal gives the name methods.
|
||||
if !self.scopes.is_empty() {
|
||||
self.reassigned_later(&name);
|
||||
}
|
||||
self.forget_writer(&name);
|
||||
} else if global_index_closed || rebound.is_some() {
|
||||
// `$.global[key] = …`, or a key that does not decode to one exact name: the key may
|
||||
// name any of them.
|
||||
self.forget_writers();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `(` 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, t: &Sig<'s>, line: Option<usize>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
let bits = self.writer_bits(h2, h3, None);
|
||||
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(t, 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.
|
||||
|
||||
@@ -135,6 +135,34 @@ pub(super) fn newer_number(text: &str) -> bool {
|
||||
text.contains('_') || (b.len() > 1 && b.last() == Some(&b'n')) || matches!((b.first(), b.get(1)), (Some(b'0'), Some(b'b' | b'B' | b'o' | b'O')))
|
||||
}
|
||||
|
||||
/// A string literal's whole value ([`unquote`] without a length limit), or `None` when an escape
|
||||
/// does not decode to exactly one character: a `\x` without two hex digits, a `\u` without four
|
||||
/// (`\u{63}` included), or a code unit that is not a character on its own.
|
||||
pub(super) fn exact_unquote(text: &str) -> Option<String> {
|
||||
let b = text.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if b[i] == b'\\' {
|
||||
let digits = match b.get(i + 1) {
|
||||
Some(b'x') => 2,
|
||||
Some(b'u') => 4,
|
||||
_ => 0,
|
||||
};
|
||||
if digits > 0 {
|
||||
let hex = b.get(i + 2..i + 2 + digits).filter(|d| d.iter().all(u8::is_ascii_hexdigit))?;
|
||||
// A surrogate code unit (`\uD800` to `\uDFFF`) is not a character on its own.
|
||||
if digits == 4 && matches!(hex[0], b'd' | b'D') && matches!(hex[1], b'8'..=b'9' | b'a'..=b'f' | b'A'..=b'F') {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
i += 2;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Some(unquote(text, text.chars().count()))
|
||||
}
|
||||
|
||||
/// A string literal's value, its quotes removed and its escapes undone (`\n`, `\xHH`, `\uHHHH`,
|
||||
/// octal escapes, a backslash before a line break), up to `max` characters.
|
||||
pub(super) fn unquote(text: &str, max: usize) -> String {
|
||||
|
||||
@@ -76,8 +76,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", "exportVariables", "imageCapture", "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", "exportVariables", "imageCapture", "saveAs", "exportForScreens"];
|
||||
// Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
|
||||
pub(crate) const DOM_FILE_READS: &[&str] = &["open"];
|
||||
|
||||
|
||||
@@ -19,6 +19,20 @@ fn feature<'r>(r: &'r Report, id: &str) -> Option<&'r Feature> {
|
||||
r.features.iter().find(|f| f.id == id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_changes_text_requires_enumeration_member_context() {
|
||||
for source in ["vc.log('SAVECHANGES');", "var text = 'SAVECHANGES';", "other['SAVECHANGES'];"] {
|
||||
let r = report(source);
|
||||
assert!(feature(&r, "file.write").is_none(), "{source}");
|
||||
assert!(!r.outside.iter().any(|outside| outside.id == "filesWritten"), "{source}");
|
||||
}
|
||||
for source in ["SaveOptions['SAVECHANGES'];", "'SaveOptions.SAVECHANGES';"] {
|
||||
let r = report(source);
|
||||
assert!(feature(&r, "file.write").is_some(), "{source}");
|
||||
assert!(r.outside.iter().any(|outside| outside.id == "filesWritten"), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
fn problems(r: &Report) -> Vec<(&'static str, Option<usize>, Option<&str>)> {
|
||||
r.problems.iter().map(|p| (p.code, p.line, p.detail.as_deref())).collect()
|
||||
}
|
||||
@@ -588,6 +602,21 @@ fn export_variables_in_brackets_writes_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][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() {
|
||||
for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] {
|
||||
@@ -912,6 +941,627 @@ fn labels_hidden_globals_and_other_objects_keep_writes_known() {
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17, 20][..]));
|
||||
}
|
||||
|
||||
/// 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][..]));
|
||||
}
|
||||
|
||||
/// An assignment to a property under a key that is not one string literal may give any such variable
|
||||
/// another value through the global object, so every `saveAs` of such a variable writes the file,
|
||||
/// before the assignment too.
|
||||
#[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(&[5, 7, 10, 13][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 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);\n",
|
||||
"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, 8][..]));
|
||||
}
|
||||
|
||||
/// A loop that replaces a variable's `saveAs` (`local.saveAs = …`, `local['saveAs'] = …`) may run a
|
||||
/// call of it before the replacement in the text on a later pass: the call writes a file. A loop
|
||||
/// that only calls the method, or replaces it on another object, leaves it the script's own.
|
||||
#[test]
|
||||
fn an_own_save_as_replaced_later_in_a_loop_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"for (;;) { local.saveAs(f); local.saveAs = g; }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"while (n--) { other.saveAs(f); other['saveAs'] = g; }\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"for (;;) { calm.saveAs(f); holder.calm.saveAs = g; }\n",
|
||||
"for (;;) { calm.saveAs(f); }\n",
|
||||
"for (;;) { calm.saveAs(f); holder.calm['saveAs'] = g; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..]));
|
||||
}
|
||||
|
||||
/// A function declared after a call is hoisted, so it may replace the variable's `saveAs` before the
|
||||
/// call runs: the call writes a file. A function that only calls the method, or replaces it on a
|
||||
/// variable of its own, leaves it the script's own.
|
||||
#[test]
|
||||
fn a_hoisted_function_declared_later_that_replaces_the_method_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"install();\n",
|
||||
"function install() { local.saveAs = app.activeDocument.saveAs; }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function swap(w) { other['saveAs'] = w; }\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"calm.saveAs(f);\n",
|
||||
"function d() { calm.saveAs(f); }\n",
|
||||
"function e() { var calm = {}; calm.saveAs = 1; }\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"third.saveAs(f);\n",
|
||||
"function h(w) { third['save\\x41s'] = w; }\n",
|
||||
"function run() {\n",
|
||||
" var mine = {saveAs: function () {}};\n",
|
||||
" fix(); mine.saveAs(f);\n",
|
||||
" function fix() { mine.saveAs = app.activeDocument.saveAs; }\n",
|
||||
"}\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 7, 11, 14, 18][..]));
|
||||
}
|
||||
|
||||
/// A hoisted function declared after a call may also replace the variable's `saveAs` under a key
|
||||
/// the check can't read (`local[k] = w`, `local['sa' + 've' + 'As'] = w`), with a compound or update
|
||||
/// operator (`local.saveAs += w`, `local['saveAs']++`, `++local.saveAs`), or through another name
|
||||
/// that holds the object (`var y = local; y.saveAs = w`, `give(local)`): the call writes a file. The
|
||||
/// same holds in a loop, where the replacement may run before the call on a later pass.
|
||||
#[test]
|
||||
fn a_method_replaced_by_a_computed_key_an_operator_or_an_alias_ends_the_own_save_as() {
|
||||
let head = "var f = new File(p);\nvar local = {saveAs: function () {}};\n";
|
||||
let mut wrong = vec![];
|
||||
for (tail, lines) in [
|
||||
("local.saveAs(f);\nfunction h(w, k) { local[k] = w; }\n", &[3][..]),
|
||||
("local.saveAs(f);\nfunction h(w) { local['sa' + 've' + 'As'] = w; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h(w) { local.saveAs += w; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { local['saveAs']++; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { local.saveAs--; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { ++local.saveAs; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h(w) { var y = local; y.saveAs = w; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { give(local); }\n", &[3]),
|
||||
("for (;;) { local.saveAs(f); local[k] = w; }\n", &[3]),
|
||||
("for (;;) { local.saveAs(f); local.saveAs += w; }\n", &[3]),
|
||||
("for (;;) { local.saveAs(f); var z = local; }\n", &[3]),
|
||||
("local.saveAs(f);\nfunction h() { local.saveAs(f); local['name'] = 1; }\n", &[4]),
|
||||
("local.saveAs(f);\nfunction h() { return local[0]; }\n", &[]),
|
||||
] {
|
||||
let r = report(&format!("{head}{tail}"));
|
||||
if feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()) != lines || r.truncated {
|
||||
wrong.push((tail, feature(&r, "file.write").map(|f| f.lines.clone())));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// A function that replaces a variable's `saveAs` may stand before the `var` statement that declares
|
||||
/// the variable in the body around it, since `var` declares the name for the whole body: the call
|
||||
/// after the literal writes a file. A function whose own later `var` declares the name replaces
|
||||
/// the method on its own variable, which leaves the outer one the script's own.
|
||||
#[test]
|
||||
fn a_method_replaced_before_the_hoisted_var_that_declares_it_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function run() {\n",
|
||||
" function fix() { give(mine); }\n",
|
||||
" var mine = {saveAs: function () {}};\n",
|
||||
" mine.saveAs(f);\n",
|
||||
"}\n",
|
||||
"function late() {\n",
|
||||
" mine2 = {saveAs: function () {}};\n",
|
||||
" mine2.saveAs(f);\n",
|
||||
" function fix() { give(mine2); }\n",
|
||||
" var mine2;\n",
|
||||
"}\n",
|
||||
"function deep() {\n",
|
||||
" held = {saveAs: function () {}};\n",
|
||||
" held.saveAs(f);\n",
|
||||
" function a() { function b() { held.saveAs = w; } }\n",
|
||||
" var held;\n",
|
||||
"}\n",
|
||||
"function calm() {\n",
|
||||
" var quiet = {saveAs: function () {}};\n",
|
||||
" function g(w) { give(quiet); var quiet; }\n",
|
||||
" quiet.saveAs(f);\n",
|
||||
"}\n",
|
||||
"function own() {\n",
|
||||
" give(mine3);\n",
|
||||
" var mine3 = {saveAs: function () {}};\n",
|
||||
" mine3.saveAs(f);\n",
|
||||
"}\n",
|
||||
"function par() {\n",
|
||||
" function fix(mine4) { mine4.saveAs = w; }\n",
|
||||
" var mine4 = {saveAs: function () {}};\n",
|
||||
" mine4.saveAs(f);\n",
|
||||
"}\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"function h(a, local) { return local; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9, 15][..]));
|
||||
}
|
||||
|
||||
/// A call inside a nested function on a variable of the body around it, whose `saveAs` another
|
||||
/// function replaces, writes a file: the replacement is looked up for the body that declares the
|
||||
/// variable, not for the innermost body.
|
||||
#[test]
|
||||
fn a_call_in_a_nested_function_on_a_replaced_outer_variable_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function run() {\n",
|
||||
" var mine = {saveAs: function () {}};\n",
|
||||
" function use() { mine.saveAs(f); }\n",
|
||||
" function fix(w) { give(mine); }\n",
|
||||
"}\n",
|
||||
"var top = {saveAs: function () {}};\n",
|
||||
"function use2() { var other = 1; top.saveAs(f); }\n",
|
||||
"function fix2(w) { give(top); }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 8][..]));
|
||||
}
|
||||
|
||||
/// A global variable read through the global object as a value (`$.global.local`, `this.local`,
|
||||
/// `globalThis.local`) may be held under another name, also by a hoisted function declared before
|
||||
/// the literal: the variable's `saveAs` writes a file.
|
||||
#[test]
|
||||
fn a_global_member_used_as_a_value_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function a() { var alias = $.global.local; alias.saveAs = app.activeDocument.saveAs; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"var held = this.other;\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function b() { use(globalThis.third); }\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"third.saveAs(f);\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"use(holder.calm);\n",
|
||||
"calm.saveAs(f);\n",
|
||||
"function g() { var mine = {saveAs: function () {}}; var alias = $.global.mine; mine.saveAs(f); }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 10][..]));
|
||||
}
|
||||
|
||||
/// 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, 13][..]));
|
||||
}
|
||||
|
||||
/// A function body that declares the variable's name itself can still give the variable another
|
||||
/// value through the global object: the variable's methods are not put back when the body closes.
|
||||
/// A body that only declares the name leaves the methods the script's own.
|
||||
#[test]
|
||||
fn a_global_assignment_under_a_shadowing_declaration_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"function replace() { var local = 1; $.global.local = app.activeDocument; }\n",
|
||||
"replace();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var calm = {saveAs: function () {}};\n",
|
||||
"function keep() { var calm = 1; }\n",
|
||||
"keep();\n",
|
||||
"calm.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
|
||||
}
|
||||
|
||||
/// An assignment under a computed key of the global object may give any variable another value, so
|
||||
/// after one anywhere in the file every call is reported.
|
||||
#[test]
|
||||
fn a_computed_global_assignment_ends_every_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"function any() { var other = 1; $.global[k] = app.activeDocument; }\n",
|
||||
"any();\n",
|
||||
"other.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
|
||||
}
|
||||
|
||||
/// A function declared before the literal may run after it and give the variable another value
|
||||
/// through any form of a global object property: `$.global.name`, `globalThis.name` and
|
||||
/// `$.global['name']`. The literal's later calls keep reporting the write. An assignment in the
|
||||
/// global code runs once, before a later literal, and leaves that literal's methods the script's own.
|
||||
#[test]
|
||||
fn a_hoisted_global_property_assignment_ends_a_later_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function replace() { $.global.local = app.activeDocument; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"replace();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"function swap() { globalThis.other = app.activeDocument; }\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"swap();\n",
|
||||
"other.saveAs(f);\n",
|
||||
"function put() { $.global['third'] = app.activeDocument; }\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"put();\n",
|
||||
"third.saveAs(f);\n",
|
||||
"$.global.fresh = 1;\n",
|
||||
"var fresh = {saveAs: function () {}};\n",
|
||||
"fresh.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9, 13][..]));
|
||||
}
|
||||
|
||||
/// Inside the body of a `with` statement a name may be a property of the statement's object, so a
|
||||
/// call of a literal's method there is reported. A `with` statement also gives names values the
|
||||
/// check does not read, so the calls after its body are reported too.
|
||||
#[test]
|
||||
fn a_call_inside_a_with_body_is_not_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"with ({local: app.activeDocument}) {\n",
|
||||
" local.saveAs(f);\n",
|
||||
"}\n",
|
||||
"local.saveAs(f);\n",
|
||||
"if (x) { with (o) local.saveAs(f); }\n",
|
||||
"local.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6, 7, 8][..]));
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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][..]));
|
||||
}
|
||||
|
||||
/// A property assignment in a loop may give the global variable of that name another value on the
|
||||
/// next pass, so a call on it in the same loop may write a file.
|
||||
#[test]
|
||||
fn a_property_assignment_in_a_loop_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"for (var i = 0; i < 2; i++) {\n",
|
||||
" local.saveAs(f);\n",
|
||||
" $.global.local = app.activeDocument;\n",
|
||||
"}\n",
|
||||
"var other = {saveAs: function () {}};\n",
|
||||
"for (var j = 0; j < 2; j++) {\n",
|
||||
" other.saveAs(f);\n",
|
||||
" $.global['other'] = app.activeDocument;\n",
|
||||
"}\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9][..]));
|
||||
// The property names the global variable, not a function's own variable of the same name.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function g() {\n",
|
||||
" var local = {saveAs: function () {}};\n",
|
||||
" for (var i = 0; i < 2; i++) { local.saveAs(f); $.global.local = app.activeDocument; }\n",
|
||||
"}\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), None);
|
||||
// A key with an escape may name the variable.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"for (var i = 0; i < 2; i++) { local.saveAs(f); $.global['lo\\u0063al'] = app.activeDocument; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
// Hex escapes and a line continuation in the key.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"for (var i = 0; i < 2; i++) { local.saveAs(f); this['lo\\x63\\\n",
|
||||
"al'] = app.activeDocument; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
// A key longer than 256 characters names the variable of that whole name.
|
||||
let long = "v".repeat(300);
|
||||
let r = report(&format!(
|
||||
"var f = new File(p);\nvar {long} = {{saveAs: function () {{}}}};\nfor (var i = 0; i < 2; i++) {{ {long}.saveAs(f); $.global['{long}'] = app.activeDocument; }}\n"
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
let r = report(&format!("var f = new File(p);\nvar {long} = {{saveAs: function () {{}}}};\n$.global['{long}'].saveAs = w;\n{long}.saveAs(f);\n"));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
|
||||
// A key whose escape does not decode to one exact name may name any variable.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"this['lo\\u{63}al'] = app.activeDocument;\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var kept = {saveAs: function () {}};\n",
|
||||
"$.global['k\\uD800'].saveAs = w;\n",
|
||||
"kept.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..]));
|
||||
}
|
||||
|
||||
/// A function that replaces a method through the global object's property (`$.global.local.saveAs`)
|
||||
/// changes the variable's methods, as `local.saveAs = …` does.
|
||||
#[test]
|
||||
fn a_method_replaced_through_the_global_object_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function install() {\n",
|
||||
" $.global.local.saveAs = function (f) {\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
" };\n",
|
||||
"}\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"install();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var mine = {saveAs: function () {}};\n",
|
||||
"globalThis.mine.saveAs = w;\n",
|
||||
"mine.saveAs(f);\n",
|
||||
"function install2() { var kept; $.global.kept.saveAs = w; }\n",
|
||||
"var kept = {saveAs: function () {}};\n",
|
||||
"install2();\n",
|
||||
"kept.saveAs(f);\n",
|
||||
"var safe = {saveAs: function () {}};\n",
|
||||
"holder.global.safe.saveAs = w;\n",
|
||||
"safe.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9, 12, 16][..]));
|
||||
}
|
||||
|
||||
/// Bracket forms of the global object's property (`$.global['local'].saveAs`, `this['local'].saveAs`,
|
||||
/// `$.global.local['saveAs']`) change the variable's methods, as the dot forms do.
|
||||
#[test]
|
||||
fn a_method_replaced_through_a_bracketed_global_member_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function install() {\n",
|
||||
" $.global['local'].saveAs = function (f) {\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
" };\n",
|
||||
"}\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"install();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var mine = {saveAs: function () {}};\n",
|
||||
"this['mine'].saveAs = w;\n",
|
||||
"mine.saveAs(f);\n",
|
||||
"var third = {saveAs: function () {}};\n",
|
||||
"$.global.third['saveAs'] = w;\n",
|
||||
"third.saveAs(f);\n",
|
||||
"var fourth = {saveAs: function () {}};\n",
|
||||
"globalThis['fourth']['saveAs'] = w;\n",
|
||||
"fourth.saveAs(f);\n",
|
||||
"var safe = {saveAs: function () {}};\n",
|
||||
"holder.global['safe'].saveAs = w;\n",
|
||||
"safe.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 9, 12, 15, 18][..]));
|
||||
// A body's own variable of the same name does not keep the global variable's methods.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"function g() { var local = {saveAs: function () {}}; $.global['local'].saveAs = w; }\n",
|
||||
"g();\n",
|
||||
"local.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5][..]));
|
||||
}
|
||||
|
||||
/// A bracketed read of the global variable used as a value (`var alias = $.global['local']`) shares
|
||||
/// its object, so a later literal's `saveAs` is not the script's own.
|
||||
#[test]
|
||||
fn a_bracketed_global_member_used_as_a_value_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function install() {\n",
|
||||
" var alias = $.global['local'];\n",
|
||||
" alias.saveAs = function (f) {\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
" };\n",
|
||||
"}\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"install();\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var safe = {saveAs: function () {}};\n",
|
||||
"var other = holder['safe'];\n",
|
||||
"safe.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 10][..]));
|
||||
}
|
||||
|
||||
/// A hoisted function body whose last value, read without a `;` before its closing `}`, is the
|
||||
/// variable shares it with its caller, as one that ends with `;` does.
|
||||
#[test]
|
||||
fn a_variable_read_just_before_a_function_body_closes_ends_the_own_save_as() {
|
||||
for read in ["$.global['local']", "$.global.local", "this.local", "local"] {
|
||||
let r = report(&format!(
|
||||
concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function get() {{ return {} }}\n",
|
||||
"var local = {{saveAs: function () {{}}}};\n",
|
||||
"get().saveAs = function (f) {{\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
"}};\n",
|
||||
"local.saveAs(f);\n",
|
||||
),
|
||||
read
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 7][..]), "{read}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `$.global.local.saveAs = …` in a function whose parameter is named `local` replaces the global
|
||||
/// variable's method; the parameter alone leaves the outer literal's `saveAs` the script's own.
|
||||
#[test]
|
||||
fn a_dot_global_method_assignment_under_a_parameter_shadow_ends_the_own_save_as() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"function install(local) {\n",
|
||||
" $.global.local.saveAs = function (f) {\n",
|
||||
" app.activeDocument.saveAs(f);\n",
|
||||
" };\n",
|
||||
"}\n",
|
||||
"install(null);\n",
|
||||
"local.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 9][..]));
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function install(local) { local.n = 1; }\n",
|
||||
"var local = {saveAs: function () {}};\n",
|
||||
"install({});\n",
|
||||
"local.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), None);
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
+3
-2
@@ -870,8 +870,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
character and paragraph attributes, their links to each other and the stories they form, its character and
|
||||
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries.
|
||||
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
|
||||
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a
|
||||
document's `fullName`, `path` and `saved`, and close it with `Document.close`.
|
||||
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile`,
|
||||
`Document.exportForScreens` and `app.open`, read a document's `fullName`, `path` and `saved`, and close it with
|
||||
`Document.close`.
|
||||
Scripts also have each document's linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem`
|
||||
and `RasterItem`), and trace them with `trace()`, which gives the Image Trace object as a `PluginItem` with its
|
||||
`TracingObject` and `TracingOptions`; the tracing options VectorCraft has no setting for are still missing.
|
||||
|
||||
+50
-5
@@ -2821,7 +2821,7 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
|
||||
assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File
|
||||
object; the same objects left out are not counted for the File-only functions `open`, `read`, `readch`,
|
||||
`readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not
|
||||
have; a document's `saveAs`, `exportFile`, `imageCapture` or `exportVariables` counts too, and so do `print` called on
|
||||
have; a document's `saveAs`, `exportFile`, `exportForScreens`, `imageCapture` or `exportVariables` counts too, and so do `print` called on
|
||||
`app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or `app.open()`, or on a
|
||||
variable that holds one of them, and `SaveOptions.SAVECHANGES` wherever the script reads it, since `close` given
|
||||
it saves the document to its file), `filesOpened` (files opened in other apps), `network`,
|
||||
@@ -3520,7 +3520,7 @@ through `$`:
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/),
|
||||
with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to
|
||||
776.19; 100 writes one pixel per point whatever the raster effects resolution) for PNG24 and JPEG, `matteColor` (PNG24 and JPEG; only white, an `RGBColor` of 255, 255, 255, is accepted, and another color is an error), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and
|
||||
`coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and
|
||||
`coordinatePrecision` (1 to 7), `cssProperties`, `embedRasterImages`, `compressed`, `preserveEditability` and
|
||||
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `AutoCAD` (also written
|
||||
`ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/)
|
||||
and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version`
|
||||
@@ -3545,8 +3545,9 @@ through `$`:
|
||||
`"ExportType.PNG24"`. The enumerations of the options that keep their defaults (`OutputFlattening`,
|
||||
`CompressionQuality`, `ColorConversion`, `ColorDestination`, `ColorProfile`, `DownsampleMethod`,
|
||||
`MonochromeCompression`, `PageMarksTypes`, `PDFChangesAllowedEnum`, `PDFPrintAllowedEnum`, `PDFTrimMarkWeight`,
|
||||
`PDFXStandard`, `SVGCSSPropertyLocation`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and
|
||||
`SVGFontType`) are defined too: the default member is accepted, and another member throws as not available yet. A
|
||||
`PDFXStandard`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and `SVGFontType`) are defined too:
|
||||
the default member is accepted, and another member throws as not available yet. `SVGCSSPropertyLocation`, which
|
||||
`cssProperties` uses, is defined as well. A
|
||||
path whose real file name is not valid UTF-8 throws `Script file path is not valid UTF-8` before anything is written
|
||||
or opened.
|
||||
VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the
|
||||
@@ -3558,7 +3559,7 @@ through `$`:
|
||||
read and written only where the script's folders allow. `userInteractionLevel` does not change what a command
|
||||
does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the
|
||||
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with
|
||||
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
|
||||
`compressed`); an SVG to a name that ends with `.svgz` is compressed whatever `compressed` holds. It writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
|
||||
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and a
|
||||
DXF of a drawing with placed raster images writes each image it exports beside it as a PNG file, or a JPEG
|
||||
file with `rasterFormat` `AutoCADRasterFormat.JPEG`; those files must travel with the DXF. When the script's
|
||||
@@ -3599,6 +3600,50 @@ through `$`:
|
||||
show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that
|
||||
`saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name
|
||||
(`saveAs: …`).
|
||||
- `Document.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` 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).
|
||||
Width and height requests must imply a raster scale from 0.01 to 64 for every exported region; an invalid scale
|
||||
is rejected before that export command creates its output folder. Earlier artboard, asset or document exports in
|
||||
the same script call can have written files. 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`. 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
|
||||
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`. A volume root (`/`, `E:\`) is taken when the script's folders and the automation write roots hold it. 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. `null` in place of the options, `itemToExport` or `fileNamePrefix` throws a TypeError. A bad option value throws an error before anything is written. Each export checks the scale of
|
||||
each of its items before it writes, and an item too large to draw throws after the files before it are written. A
|
||||
size gives each region its own scale, so a size that only a later export's items make out of range throws after the
|
||||
earlier exports' files are written. The warnings of each export go to the console after `exportForScreens: `.
|
||||
- `Document.placedItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/) lists the document's linked
|
||||
images and `Document.rasterItems` (https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/) its embedded ones,
|
||||
topmost first as `pageItems` lists them, each with `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`. `placedItems.add()`
|
||||
|
||||
@@ -1118,6 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- 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.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. Raster width and height requests outside an effective scale of 0.01 to 64 pixels per point are rejected before the underlying export command writes output; files written by earlier exports in the same script call remain. SVG embeds raster images and rejects `RasterImageLocation.LINK`. `crates/engine/src/tests/script_screens.rs`.
|
||||
- Scripts: `Document.rasterize` replaces page items with an embedded image and `Document.imageCapture` writes a PNG of the art or of an area of the page, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterizeOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/ImageCaptureOptions/ describe; `object.rasterize` takes `ids` and `clipBounds` for them (`docs/mcp.md`). `Document.windowCapture` is not there yet. `crates/engine/src/tests/script_raster_capture.rs`.
|
||||
- Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). For ordinary layer placement, the creators use the topmost shown, unlocked layer when the active layer is locked or hidden. The call also throws and makes no path when the document has layers and every one is locked or hidden. `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked, is on a locked artboard or is a guide while guides are locked, or when it would delete or empty the clipping path of a group or layer that keeps other objects. It still deletes the paths of a group that is the clipping path when a visible text object that lays out glyphs stays inside that group, because the text then clips; text beside the clipping path does not count, and a clipping group nested in the mask counts only when its own clipping path keeps such geometry. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. A `PathPoint` of another Global Edit member goes stale when Global Edit changes its path's points. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`.
|
||||
|
||||
Reference in new issue
Block a user