mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
Merge pull request #9052 from dotCooCoo/feat/scripts-api-d6-save-export-open
Scripts: documents save, export and open through Document.saveAs, exportFile and app.open
This commit is contained in:
30 files changed
+4338
-68
No files matched your search
@@ -39,6 +39,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
doc_move
|
||||
),
|
||||
cmd!(
|
||||
"document.setSaved",
|
||||
"Set Saved State",
|
||||
[],
|
||||
None,
|
||||
"{index?: the document (default: the current one), saved: true or false} records the document as saved (true: Close asks nothing until the next edit) or as having unsaved changes (false), without saving it or adding an undo step; a document already in that state is left as it is",
|
||||
has_doc,
|
||||
doc_set_saved
|
||||
),
|
||||
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
|
||||
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
|
||||
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
|
||||
@@ -257,6 +266,26 @@ fn doc_activate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.set_active(i) { ok() } else { Err(bad("document.activate", "no such document")) }
|
||||
}
|
||||
|
||||
fn doc_set_saved(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.setSaved";
|
||||
let i = opt_u64(p, C, "index")?.map(index).or(s.active_index()).ok_or(EngineError::NoDocument)?;
|
||||
let saved = match p.get("saved") {
|
||||
None | Some(Value::Null) => return Err(bad(C, "missing `saved`: true or false")),
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(_) => return Err(bad(C, "`saved` must be true or false")),
|
||||
};
|
||||
let uid = s.documents().get(i).map(|d| d.uid).ok_or_else(|| bad(C, "no such document"))?;
|
||||
let st = s.document_mut(uid).ok_or_else(|| bad(C, "no such document"))?;
|
||||
if st.is_dirty() == saved {
|
||||
if saved {
|
||||
st.mark_saved();
|
||||
} else {
|
||||
st.mark_unsaved();
|
||||
}
|
||||
}
|
||||
ok()
|
||||
}
|
||||
|
||||
fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let n = s.documents().len();
|
||||
let from = match p.get("from") {
|
||||
|
||||
@@ -125,6 +125,13 @@ pub use screens::{
|
||||
builtin_presets as screen_export_builtin_presets, first_file as screen_first_file, preset_list as screen_export_preset_list,
|
||||
preset_rows as screen_preset_rows,
|
||||
};
|
||||
pub(crate) use svg::{lost_artboards_warning as svg_lost_artboards_warning, preserves_editing as svg_preserves_editing};
|
||||
|
||||
/// Does a save in `format` (a format id) with options `p` write a legacy version 7 `.ai` file,
|
||||
/// which holds the artboards its own options pick? An unknown version counts as one.
|
||||
pub(crate) fn saves_legacy_ai(format: &str, p: &serde_json::Value) -> bool {
|
||||
format == "ai" && formats::format(format).is_none_or(|f| legacy_ai::wanted("file.saveAs", f, p).unwrap_or(true))
|
||||
}
|
||||
pub use svg::options_map as svg_options;
|
||||
/// Atomic file writes (a temporary file renamed over the target: a failed write never damages the
|
||||
/// file it replaces), for the apps' own writers too.
|
||||
@@ -141,6 +148,8 @@ mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
pub(crate) use access::{SCRIPT_OPEN_MAX_BYTES, SCRIPT_OPEN_TOO_LARGE};
|
||||
pub(crate) use access::{check_images_in, check_scripts_of, with_readable_settings_folder};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
|
||||
@@ -267,14 +267,43 @@ pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
crate::file_access::check_write(path).map_err(EngineError::Other)
|
||||
}
|
||||
|
||||
/// The most a file read during a script command holds, the limit an importer reads.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX_INPUT_BYTES;
|
||||
/// The error of a file past [`SCRIPT_OPEN_MAX_BYTES`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
may_read(path)?;
|
||||
// A device or pipe may never end: only a regular file is read to its end.
|
||||
if !std::fs::metadata(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?.is_file() {
|
||||
return Err(EngineError::Other(format!("{path}: not a file")));
|
||||
}
|
||||
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
if crate::file_access::in_script_command() {
|
||||
let max = SCRIPT_OPEN_MAX_BYTES;
|
||||
let read = || -> std::io::Result<Vec<u8>> {
|
||||
let file = std::fs::File::open(path)?;
|
||||
let meta = file.metadata()?;
|
||||
if !meta.is_file() {
|
||||
return Err(std::io::Error::other("not a file"));
|
||||
}
|
||||
if meta.len() > max as u64 {
|
||||
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
file.take(max as u64 + 1).read_to_end(&mut bytes)?;
|
||||
if bytes.len() > max {
|
||||
return Err(std::io::Error::other(SCRIPT_OPEN_TOO_LARGE));
|
||||
}
|
||||
Ok(bytes)
|
||||
};
|
||||
read().map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
} else {
|
||||
std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))
|
||||
}
|
||||
}
|
||||
|
||||
/// The first `max` bytes of the file at `path` (all of it when it is shorter). Anything but a
|
||||
|
||||
@@ -73,7 +73,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`.
|
||||
/// → the same with `dataBase64` and `{name, dataBase64}` rows, named after `name`. Every path is
|
||||
/// checked against the file access in force before the first file is written, so a refused path
|
||||
/// writes none of them.
|
||||
pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_doc::Document, enc: &Encoded, extra: Value) -> Result<Value> {
|
||||
let files = enc.named(doc, path.unwrap_or(name));
|
||||
let (main, linked) = files.split_at(enc.files.len());
|
||||
@@ -82,6 +84,12 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
|
||||
None => json!({ "name": name, "dataBase64": vectorcraft_format::base64_encode(bytes) }),
|
||||
};
|
||||
if path.is_some() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1 {
|
||||
for (p, _) in &files {
|
||||
super::may_write(p)?;
|
||||
}
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
write_file(p, bytes)?;
|
||||
}
|
||||
|
||||
@@ -818,7 +818,7 @@ pub fn read_for_open_asking(
|
||||
(linked_pages(name, bytes, path.as_deref(), &opts)?, None)
|
||||
} else {
|
||||
match super::importer::pick(name, bytes, p)? {
|
||||
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None),
|
||||
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode),
|
||||
// The color mode `p` asks for converts the colors after the policies did, through the
|
||||
// profiles the document keeps.
|
||||
None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
|
||||
@@ -1096,6 +1096,21 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
source(p, "document.open")?
|
||||
}
|
||||
};
|
||||
let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
|
||||
let (options, aliases) = (given(&["page", "cropTo"]), given(&["pages", "crop"]));
|
||||
if crate::file_access::in_script_command() && (options || aliases) {
|
||||
// An importer plug-in receives only the params, so it cannot apply the pages or the crop
|
||||
// box; `linkPages` reads the file with the built-in reader before any importer.
|
||||
let link_pages = p.get("linkPages").and_then(Value::as_bool) == Some(true);
|
||||
let built_in = link_pages || super::importer::pick(src.name, &src.bytes, p)?.is_none();
|
||||
let pdf = built_in
|
||||
&& (!options
|
||||
|| (detect(src.name, &src.bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait"))
|
||||
&& !vectorcraft_pdf::is_postscript(&src.bytes)));
|
||||
if !pdf {
|
||||
return Err(bad("document.open", "PDF open options require a PDF file"));
|
||||
}
|
||||
}
|
||||
// A relative path is the file in the working directory: its folder is where relative links
|
||||
// are found (a bare file name has no folder of its own).
|
||||
let path = src.path.map(super::absolute_path);
|
||||
|
||||
@@ -22,6 +22,8 @@ pub struct LoadOptions {
|
||||
pub pages: Option<String>,
|
||||
/// The box each page's artboard (or placed frame) gets.
|
||||
pub crop: CropTo,
|
||||
/// Whether the options explicitly request the crop box.
|
||||
pub explicit_crop_box: bool,
|
||||
/// The password of an encrypted PDF.
|
||||
pub password: Option<String>,
|
||||
/// The colour mode the document opens in, its colours converted as Document Color Mode does
|
||||
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
|
||||
Self {
|
||||
pages: None,
|
||||
crop: CropTo::default(),
|
||||
explicit_crop_box: false,
|
||||
password: None,
|
||||
color_mode: None,
|
||||
grays: Grays::default(),
|
||||
@@ -147,6 +150,7 @@ impl LoadOptions {
|
||||
Ok(Self {
|
||||
pages,
|
||||
crop,
|
||||
explicit_crop_box: crop == CropTo::Crop && crop_to.or(crop_alias).is_some(),
|
||||
password,
|
||||
color_mode,
|
||||
grays,
|
||||
@@ -173,14 +177,14 @@ impl LoadOptions {
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
|
||||
/// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes,
|
||||
/// its editor's artboards, with the bleed round them (its crop box takes the bleed in).
|
||||
/// `.ai`, or a PDF saved with its editing data, opens on its trim boxes by default,
|
||||
/// with the bleed around them. An explicit crop-box request uses its crop box.
|
||||
fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result<ImportOptions> {
|
||||
let pages = match &self.pages {
|
||||
None => None,
|
||||
Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?),
|
||||
};
|
||||
let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data();
|
||||
let is_ai = !self.explicit_crop_box && self.crop == CropTo::Crop && opened.has_illustrator_data();
|
||||
Ok(ImportOptions {
|
||||
pages,
|
||||
crop: if is_ai { CropTo::Trim } else { self.crop },
|
||||
|
||||
@@ -602,6 +602,7 @@ pub struct SaveJob {
|
||||
stamped: Option<i64>,
|
||||
/// The artboards also saved to files of their own (`separateArtboards`).
|
||||
boards: Vec<usize>,
|
||||
redact_paths: bool,
|
||||
}
|
||||
|
||||
/// Writes the file at a path with what the filler it is given writes into it
|
||||
@@ -963,7 +964,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
};
|
||||
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
|
||||
super::access::check_native_images(cmd, plan.format.id, &st.doc, crate::cmd::links::LinkBase::of(st), &checked)?;
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
|
||||
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards, redact_paths: false })
|
||||
}
|
||||
|
||||
impl SaveJob {
|
||||
@@ -1044,7 +1045,8 @@ impl SaveJob {
|
||||
}
|
||||
|
||||
/// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in
|
||||
/// order: when `stop` returns a value, nothing is written and that value is returned. Work
|
||||
/// order: when `stop` returns a value, nothing is written and that value is returned. When a
|
||||
/// save writes several files and the file access in force refuses one, none is written. Work
|
||||
/// canceled ([`crate::cancel`]) before the first file is written returns
|
||||
/// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the
|
||||
/// others are written too.
|
||||
@@ -1069,6 +1071,18 @@ impl SaveJob {
|
||||
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
|
||||
return Ok(stopped);
|
||||
}
|
||||
// Every path is checked against the file access in force before the first file is
|
||||
// written. A refused file is not handed to `write`, so a writer that does not check the
|
||||
// file access writes none of the files; the error is the file access's own refusal, as
|
||||
// the writers that check it give.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1
|
||||
&& let Some(refused) = files
|
||||
.iter()
|
||||
.find_map(|(p, _)| super::may_write(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e }))
|
||||
{
|
||||
return Err(refused);
|
||||
}
|
||||
for (i, (p, bytes)) in files.iter().enumerate() {
|
||||
if i == 0 {
|
||||
write(p, bytes)?;
|
||||
@@ -1229,9 +1243,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8])
|
||||
/// A save command: plan, then write with the file system (a native file as it is encoded).
|
||||
pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
|
||||
let plan = save_plan(s, mode, p)?;
|
||||
let job = save_job(s, plan)?;
|
||||
let mut job = save_job(s, plan)?;
|
||||
let uid = s.doc()?.uid;
|
||||
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
job.redact_paths = !given;
|
||||
// Without a path, the files written are the document's own file and those beside it.
|
||||
let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
|
||||
super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })
|
||||
@@ -1373,7 +1388,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard; when one of a save's files may not be written, none is written. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -172,14 +172,19 @@ pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Docu
|
||||
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
|
||||
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
|
||||
/// Editing Capabilities).
|
||||
pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
|
||||
pub(crate) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option<String> {
|
||||
let n = doc.artboards.len();
|
||||
let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing);
|
||||
(n > 1 && !preserved).then(|| {
|
||||
(n > 1 && !preserves_editing(doc, p)).then(|| {
|
||||
format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.")
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a save of `doc` as SVG with options `p` (flat or nested in `svg`) embeds the native
|
||||
/// document (Preserve Editing Capabilities), which keeps every artboard.
|
||||
pub(crate) fn preserves_editing(doc: &Document, p: &Value) -> bool {
|
||||
plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing)
|
||||
}
|
||||
|
||||
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
|
||||
/// outside the read roots of the request being served (the open document keeps it).
|
||||
fn native_attachment(doc: &Document) -> Vec<u8> {
|
||||
|
||||
@@ -312,6 +312,9 @@ pub(crate) struct ScriptGate {
|
||||
/// The paths of the open documents' files, as the documents held them when the person last
|
||||
/// opened or saved them. A document a script's command opened has none here.
|
||||
pub(crate) documents: Vec<String>,
|
||||
/// The real paths of the files the script's `File` objects hold open for writing, which a
|
||||
/// command does not write: the run's end would write the objects' bytes over them.
|
||||
pub(crate) held: Vec<PathBuf>,
|
||||
/// The files the documents link to as the person left them when the run began: readable, not
|
||||
/// writable.
|
||||
pub(crate) linked: LinkedFiles,
|
||||
@@ -373,8 +376,11 @@ impl ScriptGate {
|
||||
Access::Read => self.read.allows(&real) || self.write.allows(&real),
|
||||
Access::Write => self.write.allows(&real),
|
||||
};
|
||||
// A read-only file is not written over, also where a rename could replace it.
|
||||
let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
|
||||
let held = matches!(access, Access::Write) && self.held.contains(&real);
|
||||
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
|
||||
scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked
|
||||
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
|
||||
});
|
||||
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
|
||||
}
|
||||
@@ -1026,6 +1032,7 @@ mod tests {
|
||||
read: ScriptScope::of_folder(&base.join(dir)),
|
||||
write: ScriptScope::default(),
|
||||
documents: vec![],
|
||||
held: vec![],
|
||||
linked: LinkedFiles::default(),
|
||||
also: None,
|
||||
};
|
||||
@@ -1055,6 +1062,7 @@ mod tests {
|
||||
read: ScriptScope::of_folder(dir),
|
||||
write: ScriptScope::default(),
|
||||
documents: vec![],
|
||||
held: vec![],
|
||||
linked: LinkedFiles::default(),
|
||||
also: None,
|
||||
};
|
||||
@@ -1083,8 +1091,14 @@ mod tests {
|
||||
let later = base.join("outside/later.svg");
|
||||
let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]);
|
||||
assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}");
|
||||
let gate =
|
||||
ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None };
|
||||
let gate = ScriptGate {
|
||||
read: ScriptScope::of_folder(&base.join("in")),
|
||||
write: ScriptScope::default(),
|
||||
documents: vec![],
|
||||
held: vec![],
|
||||
linked,
|
||||
also: None,
|
||||
};
|
||||
std::fs::write(&later, "<svg/>").unwrap();
|
||||
let (read, write) =
|
||||
(|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok());
|
||||
@@ -1115,6 +1129,7 @@ mod tests {
|
||||
read,
|
||||
write: ScriptScope::default(),
|
||||
documents: vec![],
|
||||
held: vec![],
|
||||
linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]),
|
||||
also: None,
|
||||
};
|
||||
@@ -1150,6 +1165,7 @@ mod tests {
|
||||
read: ScriptScope::default(),
|
||||
write: ScriptScope::default(),
|
||||
documents: vec![],
|
||||
held: vec![],
|
||||
linked: ScriptGate::real_files([doc.clone()]),
|
||||
also: None,
|
||||
};
|
||||
@@ -1171,7 +1187,7 @@ mod tests {
|
||||
std::fs::write(&other, "<svg/>").unwrap();
|
||||
std::os::unix::fs::symlink(&secret, &link).unwrap();
|
||||
let linked = ScriptGate::real_files([s(link.clone())]);
|
||||
let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None };
|
||||
let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], held: vec![], linked, also: None };
|
||||
assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok());
|
||||
std::fs::remove_file(&link).unwrap();
|
||||
std::os::unix::fs::symlink(&other, &link).unwrap();
|
||||
@@ -1180,6 +1196,38 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_gate_does_not_write_over_a_read_only_file() {
|
||||
let (base, _) = folders("gate-read-only");
|
||||
let out = base.join("out/kept.svg");
|
||||
std::fs::write(&out, "<svg/>").unwrap();
|
||||
let gate = ScriptGate {
|
||||
read: ScriptScope::default(),
|
||||
write: ScriptScope::of_folder(&base.join("out")),
|
||||
documents: vec![],
|
||||
held: vec![],
|
||||
linked: LinkedFiles::default(),
|
||||
also: None,
|
||||
};
|
||||
let (kept, fresh) = (s(out.clone()), s(base.join("out/new.svg")));
|
||||
let check = |p: &str| with_script_gate(gate.clone(), || (check_write(p).is_ok(), check_read(p).is_ok()));
|
||||
// The open document's file is the only grant: no folder scope covers it.
|
||||
let documents = ScriptGate { write: ScriptScope::default(), documents: vec![kept.clone()], ..gate.clone() };
|
||||
let document_write = || with_script_gate(documents.clone(), || check_write(&kept).is_ok());
|
||||
assert_eq!(check(&kept), (true, true));
|
||||
assert!(document_write(), "an open document's file is written");
|
||||
let mut perms = std::fs::metadata(&out).unwrap().permissions();
|
||||
perms.set_readonly(true);
|
||||
std::fs::set_permissions(&out, perms.clone()).unwrap();
|
||||
assert_eq!(check(&kept), (false, true), "a read-only file is read but not written");
|
||||
assert!(check(&fresh).0, "a new file next to it is written");
|
||||
assert!(!document_write(), "also when it is an open document's file");
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
std::fs::set_permissions(&out, perms).unwrap();
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_paths_are_told_by_name() {
|
||||
for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] {
|
||||
|
||||
@@ -97,6 +97,7 @@ use vectorcraft_js::{
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
mod variables;
|
||||
@@ -206,6 +207,8 @@ pub(super) struct State {
|
||||
editing: Cell<Option<Item>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
/// `app.userInteractionLevel` ([`save_open`]).
|
||||
save_options: save_open::State,
|
||||
text: text::TextState,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
preset_bytes: Cell<u64>,
|
||||
@@ -2898,7 +2901,7 @@ 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 {
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS) {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
@@ -2936,6 +2939,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
application.extend(save_open::application_members(l));
|
||||
application.extend(super::actions::app_members(l));
|
||||
let preset = {
|
||||
let l = link.clone();
|
||||
@@ -3013,9 +3017,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
document.extend(defaults::document_members(l));
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(
|
||||
["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
|
||||
document.extend(save_open::document_members(l));
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
@@ -3126,6 +3129,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.extend(colors::classes(l));
|
||||
classes.extend(text::classes(l));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.extend(save_open::classes(l));
|
||||
classes.push(class(
|
||||
"Layer",
|
||||
None,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -124,6 +124,8 @@ pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many step
|
||||
pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing";
|
||||
pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text";
|
||||
pub(crate) const WRITE_FAILED: &str = "Script file could not be written";
|
||||
pub(crate) const READ_ONLY: &str = "Script file is read-only";
|
||||
pub(crate) const OPEN_FOR_WRITING: &str = "Script file is open for writing";
|
||||
pub(crate) const NOT_EMPTY: &str = "Script folder is not empty";
|
||||
pub(crate) const NAME_TAKEN: &str = "Script file name is already in use";
|
||||
pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder";
|
||||
@@ -281,6 +283,9 @@ pub(crate) struct Disk {
|
||||
/// when they were last written to the grants file.
|
||||
kept: Vec<(std::path::PathBuf, bool, bool)>,
|
||||
recorded: usize,
|
||||
/// While set, the gate of a command the script runs leaves out the files of the open documents
|
||||
/// ([`Disk::gate`]): the command reads and writes only where the script's `File` objects may.
|
||||
pub(crate) exact: bool,
|
||||
/// The write bits setting `readonly` cleared from each file in this run, by its device and
|
||||
/// inode, which a rename keeps, at most [`MAX_ENTRIES`] files: clearing `readonly` gives them back.
|
||||
#[cfg(unix)]
|
||||
@@ -334,6 +339,7 @@ impl Disk {
|
||||
ran_too_much: setup.engine_code.1,
|
||||
kept: Vec::new(),
|
||||
recorded: 0,
|
||||
exact: false,
|
||||
#[cfg(unix)]
|
||||
cleared: HashMap::new(),
|
||||
};
|
||||
@@ -466,9 +472,12 @@ impl Disk {
|
||||
|
||||
/// The gate for a command the script runs: the places it reads and writes now, the files the
|
||||
/// person gave the open documents, `documents`, and the files it may only read because the documents open when
|
||||
/// the run began link to them, `linked`.
|
||||
/// the run began link to them, `linked`, but not the files its `File` objects hold open for writing.
|
||||
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
|
||||
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None }
|
||||
// A save, export or open of a `File` the script names reads and writes as its `File` would.
|
||||
let (documents, linked) = if self.exact { (Vec::new(), Default::default()) } else { (documents, linked) };
|
||||
let held = self.open.values().filter_map(|o| o.target.clone()).collect();
|
||||
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, held, linked, also: None }
|
||||
}
|
||||
|
||||
/// The files written since this was last asked, to name in the report.
|
||||
@@ -687,6 +696,39 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
/// The real path a save or export of the document to `path` writes, as a `File` opened for
|
||||
/// writing would write it ([`Disk::target`]), or why it may not: a folder is not a file, a
|
||||
/// read-only file is not written over, and neither is a file a `File` object holds open for
|
||||
/// writing, whose bytes the run's end would write over the saved file.
|
||||
pub(crate) fn save_target(&self, path: &str) -> Result<std::path::PathBuf, &'static str> {
|
||||
let real = self.target(path, true)?;
|
||||
if self.open.values().any(|o| o.target.as_deref() == Some(real.as_path())) {
|
||||
return Err(OPEN_FOR_WRITING);
|
||||
}
|
||||
match std::fs::metadata(&real) {
|
||||
Ok(m) if !m.is_file() => Err(NOT_REGULAR),
|
||||
Ok(m) if m.permissions().readonly() => Err(READ_ONLY),
|
||||
_ => Ok(real),
|
||||
}
|
||||
}
|
||||
|
||||
/// The real path of the file `path` that opening it as a document reads, as a `File` reads it
|
||||
/// ([`ScriptScope::locate`]), or why it may not: it is not there, it is not a regular file, or
|
||||
/// the script may not read it.
|
||||
pub(crate) fn open_target(&self, path: &str) -> Result<std::path::PathBuf, &'static str> {
|
||||
let p = self.checked(path)?;
|
||||
let real = match self.scope.locate(p) {
|
||||
Ok(real) => real,
|
||||
Err(ScriptRead::Missing) => return Err(NOT_FOUND),
|
||||
Err(ScriptRead::Refused | ScriptRead::TooLarge) => return Err(ACCESS_DENIED),
|
||||
Err(ScriptRead::Failed(_)) => return Err(READ_FAILED),
|
||||
};
|
||||
if !real.is_file() {
|
||||
return Err(NOT_REGULAR);
|
||||
}
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// Counts `n` more bytes written in the run, which ends past [`MAX_RUN_BYTES`].
|
||||
fn charge_write(&mut self, n: usize) -> Result<(), HostError> {
|
||||
self.written = self.written.saturating_add(n);
|
||||
|
||||
@@ -191,6 +191,7 @@ mod script_include;
|
||||
mod script_io;
|
||||
mod script_modules;
|
||||
mod script_run;
|
||||
mod script_save_open;
|
||||
mod script_scriptui;
|
||||
mod script_styles;
|
||||
mod script_tags;
|
||||
|
||||
@@ -2256,6 +2256,7 @@ fn a_script_loads_no_plugin_from_outside_its_folder_through_a_name_that_is_not_t
|
||||
read: ScriptScope::of_folder(&inside),
|
||||
write: ScriptScope::default(),
|
||||
documents: vec![],
|
||||
held: vec![],
|
||||
linked: Default::default(),
|
||||
also: None,
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -39,12 +39,17 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"),
|
||||
("Document.prototype.exportVariables", "app.activeDocument.exportVariables(f);", "filesWritten"),
|
||||
("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"),
|
||||
("SaveOptions.SAVECHANGES", "app.activeDocument.close(SaveOptions.SAVECHANGES);", "filesWritten"),
|
||||
];
|
||||
|
||||
/// The names the host adds that stay inside the document and the run, by the object that has them.
|
||||
/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not
|
||||
/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on
|
||||
/// the open documents; `Document.saveAs` and `close` throw "not available yet".
|
||||
/// the open documents; `Document.close` closes a document, and saves it to its own file only when it
|
||||
/// is given `SaveOptions.SAVECHANGES`, which has its row above. `Document.fullName` and
|
||||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "alert confirm length prompt prototype"),
|
||||
@@ -91,8 +96,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= selectTool textFonts toString \
|
||||
typename undo unloadAction unloadAction=",
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= open redo redraw selection selection= selectTool textFonts \
|
||||
toString typename undo unloadAction unloadAction= userInteractionLevel userInteractionLevel=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
@@ -107,14 +112,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Document.", "prototype"),
|
||||
(
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close constructor convertCoordinate \
|
||||
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
|
||||
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
|
||||
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
|
||||
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace groupItems \
|
||||
groupItems= height layers layers= name pageItems paragraphStyles parent pathItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits saveAs saveAs= scaleFactor selection selection= stories swatches swatches= \
|
||||
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
|
||||
groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems rulerOrigin \
|
||||
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
@@ -184,6 +189,58 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
|
||||
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
|
||||
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
|
||||
// The enumerations of saving, exporting and opening.
|
||||
(
|
||||
"",
|
||||
"ColorConversion ColorDestination ColorProfile Compatibility CompressionQuality DownsampleMethod EPSPostScriptLevelEnum \
|
||||
EPSPreview ExportType MonochromeCompression OutputFlattening PDFBoxType PDFChangesAllowedEnum PDFCompatibility \
|
||||
PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \
|
||||
SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel",
|
||||
),
|
||||
("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"),
|
||||
(
|
||||
"ColorDestination.",
|
||||
"COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \
|
||||
COLORDESTINATIONWORKINGRGB None",
|
||||
),
|
||||
("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"),
|
||||
(
|
||||
"CompressionQuality.",
|
||||
"AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM AUTOMATICJPEG2000MEDIUM \
|
||||
AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM \
|
||||
JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM \
|
||||
JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT",
|
||||
),
|
||||
("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"),
|
||||
("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"),
|
||||
("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"),
|
||||
(
|
||||
"PDFChangesAllowedEnum.",
|
||||
"CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE CHANGE40ANYCHANGES \
|
||||
CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT",
|
||||
),
|
||||
("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"),
|
||||
("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"),
|
||||
("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"),
|
||||
("PageMarksTypes.", "Japanese Roman"),
|
||||
("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"),
|
||||
("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"),
|
||||
("SVGDocumentEncoding.", "ASCII UTF16 UTF8"),
|
||||
("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"),
|
||||
("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"),
|
||||
(
|
||||
"Compatibility.",
|
||||
"ILLUSTRATOR10 ILLUSTRATOR11 ILLUSTRATOR12 ILLUSTRATOR13 ILLUSTRATOR14 ILLUSTRATOR15 ILLUSTRATOR16 ILLUSTRATOR17 \
|
||||
ILLUSTRATOR19 ILLUSTRATOR8 ILLUSTRATOR9 JAPANESEVERSION3",
|
||||
),
|
||||
("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"),
|
||||
("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"),
|
||||
("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"),
|
||||
("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"),
|
||||
("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"),
|
||||
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
|
||||
("SaveOptions.", "DONOTSAVECHANGES PROMPTTOSAVECHANGES"),
|
||||
("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"),
|
||||
(
|
||||
"",
|
||||
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
|
||||
@@ -314,10 +371,11 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
];
|
||||
|
||||
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
|
||||
/// other than `PathItem`, and the color classes.
|
||||
/// other than `PathItem`, the color classes, and the save and export option classes.
|
||||
const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \
|
||||
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \
|
||||
SymbolItem cmykColor";
|
||||
SymbolItem cmykColor EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \
|
||||
PDFSaveOptions";
|
||||
|
||||
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
|
||||
/// own API, and what `vc.run` does depends on the command it runs.
|
||||
|
||||
@@ -88,6 +88,66 @@ fn path_of(p: &std::path::Path) -> String {
|
||||
p.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripted_open_converts_importer_output_to_the_requested_color_space() {
|
||||
let mut s = Session::new();
|
||||
install(&mut s, &tpl::returning(&tpl::importer("test.scriptcolorspace", r#"["tscmyk"]"#, "{}"), RECT));
|
||||
let dir = tmp_dir("scriptcolorspace");
|
||||
s.attach_script_data(dir.join("settings/Script Data"));
|
||||
let file = dir.join("drawing.tscmyk");
|
||||
std::fs::write(&file, b"importer input").unwrap();
|
||||
let script = dir.join("main.jsx");
|
||||
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
|
||||
for (argument, mode) in [
|
||||
("", vectorcraft_doc::ColorMode::Rgb),
|
||||
(", DocumentColorSpace.CMYK", vectorcraft_doc::ColorMode::Cmyk),
|
||||
(", DocumentColorSpace.RGB", vectorcraft_doc::ColorMode::Rgb),
|
||||
] {
|
||||
std::fs::write(&script, format!("Folder.userData; var d = app.open(new File({path}){argument}); vc.log(d.documentColorSpace);")).unwrap();
|
||||
let count = s.documents().len();
|
||||
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()})).unwrap();
|
||||
assert_eq!(s.documents().len(), count + 1);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.color_mode, mode, "{argument}: {out}");
|
||||
let color = doc.layers[0].children().unwrap()[0].appearance.fill_paint().color().unwrap();
|
||||
if mode == vectorcraft_doc::ColorMode::Cmyk {
|
||||
assert!(matches!(color, vectorcraft_color::Color::Cmyk { .. }), "{color:?}");
|
||||
assert_eq!(out["log"], json!(["DocumentColorSpace.CMYK"]));
|
||||
} else {
|
||||
assert!(matches!(color, vectorcraft_color::Color::Rgb { .. }), "{color:?}");
|
||||
assert_eq!(out["log"], json!(["DocumentColorSpace.RGB"]));
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A script's PDF open options are refused for a file the named importer reads, which is given
|
||||
/// only the params, even when the file's extension is a PDF one.
|
||||
#[test]
|
||||
fn scripted_pdf_open_options_are_refused_for_an_importer() {
|
||||
let mut s = Session::new();
|
||||
install(&mut s, &tpl::returning(&tpl::importer("test.scriptpdfoptions", r#"["ai"]"#, "{}"), RECT));
|
||||
let dir = tmp_dir("scriptpdfoptions");
|
||||
s.attach_script_data(dir.join("settings/Script Data"));
|
||||
let file = dir.join("x.ai");
|
||||
std::fs::write(&file, b"importer input").unwrap();
|
||||
let script = dir.join("main.jsx");
|
||||
let path = serde_json::to_string(&file.to_string_lossy()).unwrap();
|
||||
for option in ["page: 1", "cropTo: 'media'", "pages: '1'", "crop: 'media'"] {
|
||||
std::fs::write(
|
||||
&script,
|
||||
format!("Folder.userData; vc.run('document.open', {{path: {path}, importer: 'plugin.test.scriptpdfoptions', {option}}});"),
|
||||
)
|
||||
.unwrap();
|
||||
let count = s.documents().len();
|
||||
let out = s.execute("script.run", &json!({"path": script.to_string_lossy()}));
|
||||
let text = format!("{out:?}");
|
||||
assert!(text.contains("PDF open options require a PDF file"), "{option}: {text}");
|
||||
assert_eq!(s.documents().len(), count, "{option}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_importer_adds_a_read_only_format_while_it_is_installed() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -7,8 +7,10 @@
|
||||
//! `File` and `new Folder(path)` always a `Folder`, while `File(path)` gives a `Folder` when the
|
||||
//! host's `stat` says the path is a folder, and `Folder(path)` a `File` when it is a file. Two
|
||||
//! objects for one path are different objects. An object keeps its path in the host's platform
|
||||
//! form, its `error` text, the id of the file it has open (or -1), the encoding set before `open`
|
||||
//! and its line feed, in properties that are not enumerable; every name the getters give comes from
|
||||
//! form in an internal slot that only the classes' own methods set ([`Class::FsEntry`]), so an
|
||||
//! object a script makes with `Object.create(File.prototype)` is not a `File`. It keeps its `error`
|
||||
//! text, the id of the file it has open (or -1), the encoding set before `open` and its line feed
|
||||
//! in properties that are not enumerable; every name the getters give comes from
|
||||
//! the host's `parse` of that path. `Folder.current` is kept in the realm and starts at the host's
|
||||
//! `current`.
|
||||
//!
|
||||
@@ -47,7 +49,59 @@ impl Classes {
|
||||
}
|
||||
}
|
||||
|
||||
const PATH: &str = "__vcPath";
|
||||
/// The one key of the [`crate::Data`] object a host gives for a `Folder`, with the folder's path in
|
||||
/// the host's platform form as its value. A plain object a script made that carries the key is
|
||||
/// refused.
|
||||
pub const FOLDER_REF_KEY: &str = "\u{0}folderRef";
|
||||
|
||||
/// What a host gives for a `File` at `path`, in the host's platform form ([`crate::FILE_REF_KEY`]):
|
||||
/// the script receives a `File` object for it.
|
||||
pub fn file_ref(path: &str) -> crate::Data {
|
||||
crate::Data::Object(vec![(crate::FILE_REF_KEY.to_string(), crate::Data::String(path.to_string()))])
|
||||
}
|
||||
|
||||
/// What a host gives for a `Folder` at `path`, in the host's platform form: the script receives a
|
||||
/// `Folder` object for it.
|
||||
pub fn folder_ref(path: &str) -> crate::Data {
|
||||
crate::Data::Object(vec![(FOLDER_REF_KEY.to_string(), crate::Data::String(path.to_string()))])
|
||||
}
|
||||
|
||||
impl Interp {
|
||||
/// A new `File` (or, with `folder`, a `Folder`) for `path`, a path in the host's platform form
|
||||
/// that a host gave ([`file_ref`], [`folder_ref`]). The host's `parse` reads it from
|
||||
/// `Folder.current`, as it reads the path of `new File()`, so a relative path names a file there.
|
||||
pub(crate) fn write_fs_ref(&mut self, path: &str, folder: bool) -> JsResult<Value> {
|
||||
let c = classes(self)?;
|
||||
let proto = if folder { c.folder_proto } else { c.file_proto };
|
||||
let text = Value::str(path);
|
||||
let fs = self.rooted(std::slice::from_ref(&text), |i| {
|
||||
let p = parse_text(i, text.clone(), true)?;
|
||||
i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))
|
||||
})?;
|
||||
instance(self, proto, fs)
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of `o` when the `File` or `Folder` class made it.
|
||||
fn own_path(i: &Interp, o: ObjId) -> JsResult<Option<Value>> {
|
||||
Ok(match &i.object(o)?.class {
|
||||
Class::FsEntry(s) => Some(Value::String(s.clone())),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the path of the `File` or `Folder` `o` to `fs`, a path the host gave.
|
||||
fn set_path(i: &mut Interp, o: ObjId, fs: Value) -> JsResult<()> {
|
||||
let Value::String(s) = fs else { return Err(i.type_error("File: the host gave no path")) };
|
||||
i.rooted(&[Value::Object(o), Value::String(s.clone())], |i| i.reserve_heap(string_bytes(s.len())))?;
|
||||
if let Some(ob) = i.heap.object_mut(o)
|
||||
&& let Class::FsEntry(path) = &mut ob.class
|
||||
{
|
||||
*path = s;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const ERROR: &str = "__vcError";
|
||||
const HANDLE: &str = "__vcHandle";
|
||||
const RUN: &str = "__vcRun";
|
||||
@@ -92,15 +146,16 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of `id` when it is a `File`: an object whose prototype is `File.prototype` and whose
|
||||
/// path is in its own slot. `None` for anything else, a `Folder` included.
|
||||
/// 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) };
|
||||
if i.object(id)?.proto != Some(c.file_proto) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(match slot(i, id, PATH)? {
|
||||
Value::String(s) => Some(s.to_rust_string()),
|
||||
Ok(match own_path(i, id)? {
|
||||
Some(Value::String(s)) => Some(s.to_rust_string()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
@@ -116,7 +171,7 @@ fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()>
|
||||
/// `Folder`.
|
||||
fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value)> {
|
||||
if let Some(o) = this.as_object()
|
||||
&& let path @ Value::String(_) = slot(i, o, PATH)?
|
||||
&& let Some(path) = own_path(i, o)?
|
||||
{
|
||||
return Ok((o, path));
|
||||
}
|
||||
@@ -127,7 +182,7 @@ fn this_path(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Value
|
||||
/// `Folder`, or `String(x)`, which may hold URI escapes.
|
||||
fn path_text(i: &mut Interp, x: &Value) -> JsResult<(Value, bool)> {
|
||||
if let Some(o) = x.as_object()
|
||||
&& let path @ Value::String(_) = slot(i, o, PATH)?
|
||||
&& let Some(path) = own_path(i, o)?
|
||||
{
|
||||
return Ok((path, true));
|
||||
}
|
||||
@@ -179,12 +234,12 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult<Valu
|
||||
|
||||
/// A new object with prototype `proto` for the path `fs`, already in the platform's form.
|
||||
fn instance(i: &mut Interp, proto: ObjId, fs: Value) -> JsResult<Value> {
|
||||
let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) };
|
||||
let line_feed = host_value(i, "lineFeed")?;
|
||||
i.rooted(&[fs.clone(), line_feed.clone()], |i| {
|
||||
i.reserve_heap(OBJECT_BYTES + 6 * PROP_BYTES)?;
|
||||
let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)));
|
||||
i.rooted(&[fs, line_feed.clone()], |i| {
|
||||
i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?;
|
||||
let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto)));
|
||||
i.rooted(&[Value::Object(o)], |i| {
|
||||
set_slot(i, o, PATH, fs.clone())?;
|
||||
set_slot(i, o, ERROR, Value::str(""))?;
|
||||
set_slot(i, o, HANDLE, Value::Number(-1.0))?;
|
||||
set_slot(i, o, RUN, Value::Number(-1.0))?;
|
||||
@@ -435,7 +490,7 @@ fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult
|
||||
}
|
||||
let p = parse(i, &arg(args, 0))?;
|
||||
let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?;
|
||||
set_slot(i, o, PATH, fs)?;
|
||||
set_path(i, o, fs)?;
|
||||
Ok(Value::Bool(true))
|
||||
}
|
||||
|
||||
@@ -508,7 +563,7 @@ fn set_hidden(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<
|
||||
if outcome(i, o, &r)? {
|
||||
let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?;
|
||||
if matches!(fs, Value::String(_)) {
|
||||
set_slot(i, o, PATH, fs)?;
|
||||
set_path(i, o, fs)?;
|
||||
}
|
||||
}
|
||||
Ok(Value::Undefined)
|
||||
@@ -537,7 +592,7 @@ fn rename(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Valu
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?;
|
||||
set_slot(i, o, PATH, fs)?;
|
||||
set_path(i, o, fs)?;
|
||||
Ok(Value::Bool(true))
|
||||
}
|
||||
|
||||
@@ -715,7 +770,7 @@ fn wrap(i: &mut Interp, folder: bool, me: &Value, answer: Value) -> JsResult<Val
|
||||
let error = i.rooted(std::slice::from_ref(&answer), |i| field(i, &answer, "error"))?;
|
||||
if matches!(error, Value::String(_)) {
|
||||
if let Some(o) = me.as_object()
|
||||
&& matches!(slot(i, o, PATH)?, Value::String(_))
|
||||
&& own_path(i, o)?.is_some()
|
||||
{
|
||||
set_slot(i, o, ERROR, error)?;
|
||||
}
|
||||
@@ -1374,4 +1429,21 @@ mod tests {
|
||||
let e = r.run("File.prototype.read.call({})").unwrap_err();
|
||||
assert!(e.message.contains("is not a File or a Folder"), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_classes_set_an_objects_path() {
|
||||
let mut r = realm();
|
||||
for forged in [
|
||||
"var x = Object.create(File.prototype); x.__vcPath = '/x';",
|
||||
"function F() { this.__vcPath = '/x'; } F.prototype = File.prototype; var x = new F();",
|
||||
] {
|
||||
let e = r.run(&format!("{forged} x.fsName")).unwrap_err();
|
||||
assert!(e.message.contains("is not a File or a Folder"), "{forged}: {e:?}");
|
||||
}
|
||||
let v = r.run(
|
||||
"var f = new File('a'); f.__vcPath = '/b'; Object.defineProperty(f, '__vcPath', {value: '/c'}); \
|
||||
var g = new File(f); [f.fsName, f.name, g.fsName, f.changePath('d'), f.fsName].join()",
|
||||
);
|
||||
assert_eq!(v.unwrap(), JsValue::String("/a,a,/a,true,/d".into()));
|
||||
}
|
||||
}
|
||||
@@ -277,6 +277,9 @@ pub(crate) enum Class {
|
||||
ModuleNamespace(Box<ModuleExports>),
|
||||
/// An object of a class a host defined ([`crate::host_classes`]).
|
||||
Host(crate::host_classes::HostObj),
|
||||
/// A `File` or `Folder` ([`crate::file_classes`]) and its path in the host's platform form,
|
||||
/// which only the classes' own methods set.
|
||||
FsEntry(Str),
|
||||
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
|
||||
UnitValue(Box<crate::unit_value::Measure>),
|
||||
/// A promise (ECMA-262 11th edition, section 25.6) and its state.
|
||||
@@ -588,6 +591,7 @@ impl Class {
|
||||
Class::Ordinary
|
||||
| Class::ForIn(_)
|
||||
| Class::Host(_)
|
||||
| Class::FsEntry(_)
|
||||
| Class::Symbol(_)
|
||||
| Class::Iterator(_)
|
||||
| Class::IterRecord(_)
|
||||
@@ -1150,7 +1154,7 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
}
|
||||
extra = PROP_BYTES * exports.bindings.len();
|
||||
}
|
||||
Class::String(s) => strings.add(s),
|
||||
Class::String(s) | Class::FsEntry(s) => strings.add(s),
|
||||
Class::RegExp(re) => {
|
||||
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
|
||||
strings.bytes += re.heap_bytes();
|
||||
|
||||
+11
-2
@@ -275,6 +275,7 @@ impl Interp {
|
||||
if r.ancestors.len() >= r.limits.depth {
|
||||
return Err(self.data_error(r, ErrorType::Range, "is nested too deep"));
|
||||
}
|
||||
// A `File` reads as its path ([`crate::FILE_REF_KEY`]).
|
||||
if r.hosted
|
||||
&& let Some(path) = crate::file_classes::file_path(self, id)?
|
||||
{
|
||||
@@ -285,7 +286,7 @@ impl Interp {
|
||||
Class::Host(_) if r.hosted => return self.read_host_ref(id, r),
|
||||
Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")),
|
||||
Class::Array { length, .. } => Shape::Array(*length),
|
||||
Class::Ordinary => {
|
||||
Class::Ordinary | Class::FsEntry(_) => {
|
||||
let o = self.object(id)?;
|
||||
if o.props.len() > r.limits.entries {
|
||||
return Err(self.data_error(r, ErrorType::Range, "has too many entries"));
|
||||
@@ -349,7 +350,7 @@ impl Interp {
|
||||
self.use_fuel()?;
|
||||
self.charge_reading(r, k.len().saturating_mul(3).saturating_add(8))?;
|
||||
let name = String::from_utf16_lossy(&k);
|
||||
if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY) {
|
||||
if r.hosted && (name == crate::HOST_REF_KEY || name == crate::FILE_REF_KEY || name == crate::FOLDER_REF_KEY) {
|
||||
return Err(self.data_error(r, ErrorType::Type, "is not plain data"));
|
||||
}
|
||||
r.path.push(Step::Name(k));
|
||||
@@ -373,6 +374,14 @@ impl Interp {
|
||||
if depth > self.data_limits.depth {
|
||||
return Err(self.throw(ErrorType::Range, "a host value is nested too deep"));
|
||||
}
|
||||
// A host member's `File` or `Folder` ([`crate::file_ref`], [`crate::folder_ref`]).
|
||||
if self.write_hosted
|
||||
&& let Data::Object(items) = &d
|
||||
&& let [(k, Data::String(path))] = items.as_slice()
|
||||
&& (k == crate::FILE_REF_KEY || k == crate::FOLDER_REF_KEY)
|
||||
{
|
||||
return self.write_fs_ref(path, k == crate::FOLDER_REF_KEY);
|
||||
}
|
||||
Ok(match d {
|
||||
Data::Undefined => Value::Undefined,
|
||||
Data::Null => Value::Null,
|
||||
|
||||
@@ -168,6 +168,7 @@ pub use ast::{
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use file_classes::{FOLDER_REF_KEY, file_ref, folder_ref};
|
||||
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
|
||||
pub use host_classes::{ArgInfo, FILE_REF_KEY, HOST_REF_KEY, HostClass, HostMember, MemberInfo, file_ref_path, host_ref, host_ref_parts};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
|
||||
@@ -277,6 +277,65 @@ struct Assign {
|
||||
after_new: bool,
|
||||
}
|
||||
|
||||
/// `name = {`: an object literal assigned to a variable.
|
||||
struct ObjectValue {
|
||||
name: String,
|
||||
/// The bracket depth inside its `{`.
|
||||
depth: usize,
|
||||
/// The document methods writing a file that it defines with a single function expression as the
|
||||
/// key's whole value, a bit each ([`Analyzer::writers`]).
|
||||
bits: u8,
|
||||
/// It is the value of the first name a `var` statement declares, and the statement is directly
|
||||
/// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or
|
||||
/// a loop's parentheses: only then does the variable hold `bits` after it.
|
||||
whole: bool,
|
||||
/// The bit of the method whose value is being read, and how far that value has been read.
|
||||
value: Option<(u8, Value)>,
|
||||
}
|
||||
|
||||
/// How far the value of an object literal's key that names a document method writing a file has been
|
||||
/// read, by the tokens directly inside the literal's braces.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Value {
|
||||
/// `function`.
|
||||
Function,
|
||||
/// The function expression's name.
|
||||
Name,
|
||||
/// The `(` of its parameters.
|
||||
Params,
|
||||
/// The `{` of its body: the value is the function expression when `,` or the literal's `}` comes
|
||||
/// next.
|
||||
Body,
|
||||
/// Anything else, or anything after the body.
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ObjectValue {
|
||||
/// `t`, a token directly inside the literal's braces: a `,` or the closing `}` ends the value
|
||||
/// being read, and gives the literal the method only when the value is a single function
|
||||
/// expression (`function () {} && d.saveAs`, `function () {}(f)` and `function () {}.call` give
|
||||
/// it nothing).
|
||||
fn step(&mut self, t: &Sig) {
|
||||
let Some((bit, value)) = self.value else { return };
|
||||
if t.is(",") || t.is("}") {
|
||||
if value == Value::Body {
|
||||
self.bits |= bit;
|
||||
} else {
|
||||
self.bits &= !bit;
|
||||
}
|
||||
self.value = None;
|
||||
return;
|
||||
}
|
||||
let next = match value {
|
||||
Value::Function if t.kind == T::Ident => Value::Name,
|
||||
Value::Function | Value::Name if t.is("(") => Value::Params,
|
||||
Value::Params if t.is("{") => Value::Body,
|
||||
_ => Value::Other,
|
||||
};
|
||||
self.value = Some((bit, next));
|
||||
}
|
||||
}
|
||||
|
||||
/// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it
|
||||
/// is a Folder object whatever the path names: [`Operand::file_step`]).
|
||||
enum Held {
|
||||
@@ -472,6 +531,8 @@ impl Chain {
|
||||
/// member chain or a File object assigned in it to an outer name stays.
|
||||
struct Scope {
|
||||
depth: usize,
|
||||
/// The offset of the body's `{` in the text, which [`Declared::looped`] names it by.
|
||||
start: usize,
|
||||
saved: HashMap<String, Saved>,
|
||||
/// The bracket depth of the `var` statement the body is in, if any: it goes on when the body
|
||||
/// closes.
|
||||
@@ -507,6 +568,8 @@ struct Saved {
|
||||
shadowed: Option<bool>,
|
||||
/// It was a platform name the script had a meaning of its own for.
|
||||
own: bool,
|
||||
/// What it held in [`Analyzer::writers`], 0 for nothing.
|
||||
writer: u8,
|
||||
}
|
||||
|
||||
/// The open brackets and their lines, up to [`crate::Limits::nesting`]; the brackets past that are
|
||||
@@ -556,6 +619,8 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
file: Option<&'a str>,
|
||||
/// The four significant tokens before this one, the latest first.
|
||||
h: [Option<Sig<'s>>; 4],
|
||||
/// The significant token before the four of [`Self::h`].
|
||||
h4: Option<Sig<'s>>,
|
||||
brackets: Brackets,
|
||||
/// Nesting too deep to follow was reported: it is reported once.
|
||||
deep: bool,
|
||||
@@ -578,6 +643,25 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
maybe_files: HashSet<String>,
|
||||
/// `maybe_files` ran out of room: no variable counts as holding a Folder object.
|
||||
maybe_files_full: bool,
|
||||
/// The variables holding an object literal of the script's own that defines a method named as a
|
||||
/// document method that writes a file (`{saveAs: …}`), each with a bit per method it defines (bit
|
||||
/// `i` for `catalog::DOM_FILE_WRITES[i]`): a call of that method on them writes nothing.
|
||||
writers: HashMap<String, u8>,
|
||||
/// The object literals being assigned to a variable, the innermost last, up to
|
||||
/// [`crate::Limits::nesting`] of them.
|
||||
objects: Vec<ObjectValue>,
|
||||
/// An object literal whose `}` the last token was, with the methods it defines: the variable
|
||||
/// holds them when the next token ends the `var` statement's value.
|
||||
closed: Option<(String, u8)>,
|
||||
/// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver
|
||||
/// that is not such a variable.
|
||||
index_receiver: u8,
|
||||
/// The variables that may get another value when code read elsewhere runs: assigned inside a
|
||||
/// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]).
|
||||
/// None of them joins [`Analyzer::writers`].
|
||||
later: HashSet<String>,
|
||||
/// `later` ran out of room: no variable joins [`Analyzer::writers`].
|
||||
later_full: bool,
|
||||
/// This file or what the scan started with gives names values the analysis doesn't read
|
||||
/// ([`Declared::unsure`]): no object counts as a Folder object whatever the path names.
|
||||
unsure: bool,
|
||||
@@ -641,6 +725,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
acc,
|
||||
file,
|
||||
h: [None; 4],
|
||||
h4: None,
|
||||
brackets: Brackets::default(),
|
||||
deep: false,
|
||||
active: None,
|
||||
@@ -654,6 +739,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
// property of the global object.
|
||||
maybe_files: known.files.difference(&known.folders).chain(declared.rebound.iter()).cloned().collect(),
|
||||
maybe_files_full: false,
|
||||
writers: HashMap::new(),
|
||||
objects: vec![],
|
||||
closed: None,
|
||||
index_receiver: 0,
|
||||
later: HashSet::new(),
|
||||
later_full: false,
|
||||
unsure: known.unsure || declared.unsure,
|
||||
own_names: HashSet::new(),
|
||||
scopes: vec![],
|
||||
@@ -738,6 +829,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
// `t` ends, holds the value, or nothing the check follows, before `t` starts a member chain or
|
||||
// closes a function body.
|
||||
self.settle_groups(&t);
|
||||
self.settle_literal(&t);
|
||||
// A line break ends a `var` statement when it is outside the statement's brackets, and the
|
||||
// tokens on either side of it don't go on with the expression.
|
||||
if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(self.h[0]) && !goes_on_with(&t) {
|
||||
@@ -760,9 +852,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.group_step(&t, started, before);
|
||||
self.paren_step(&t, before);
|
||||
self.assignment(&t, started);
|
||||
self.object_key(&t, before);
|
||||
self.features(&t);
|
||||
self.newer(&t);
|
||||
self.module_check(&t);
|
||||
self.h4 = self.h[3];
|
||||
self.h = [Some(t), self.h[0], self.h[1], self.h[2]];
|
||||
}
|
||||
|
||||
@@ -859,6 +953,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
fn bind(&mut self, name: String, path: String) {
|
||||
self.files.remove(&name);
|
||||
self.folders.remove(&name);
|
||||
self.writers.remove(&name);
|
||||
if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) {
|
||||
self.bound.insert(name, path);
|
||||
}
|
||||
@@ -868,6 +963,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
fn hold_file(&mut self, name: String, folder: bool) {
|
||||
self.bound.remove(&name);
|
||||
self.folders.remove(&name);
|
||||
self.writers.remove(&name);
|
||||
if !folder && !self.maybe_files.contains(&name) {
|
||||
if self.acc.room(self.maybe_files.len()) {
|
||||
self.maybe_files.insert(name.clone());
|
||||
@@ -991,6 +1087,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
local: false,
|
||||
shadowed,
|
||||
own: self.own_names.contains(name),
|
||||
writer: self.writers.get(name).copied().unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1025,6 +1122,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
} else {
|
||||
self.own_names.remove(&name);
|
||||
}
|
||||
// An outer variable the body assigned keeps only the methods it still has: the body may have
|
||||
// given it another value.
|
||||
let writer = if saved.local { saved.writer } else { saved.writer & self.writers.get(&name).copied().unwrap_or(0) };
|
||||
if writer != 0 {
|
||||
self.writers.insert(name.clone(), writer);
|
||||
} else {
|
||||
self.writers.remove(&name);
|
||||
}
|
||||
if let Some(hidden) = saved.shadowed
|
||||
&& let Some(i) = catalog::DOM_ROOTS.iter().position(|r| *r == name)
|
||||
&& let Some(s) = self.shadowed.get_mut(i)
|
||||
@@ -1074,6 +1179,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.bound.remove(name);
|
||||
self.files.remove(name);
|
||||
self.folders.remove(name);
|
||||
self.writers.remove(name);
|
||||
self.hide_root(name);
|
||||
}
|
||||
|
||||
@@ -1134,7 +1240,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
if body {
|
||||
let params = self.params.take().map(|(_, names)| names).unwrap_or_default();
|
||||
if self.scopes.len() < self.acc.limits.nesting {
|
||||
self.scopes.push(Scope { depth: self.depth(), saved: HashMap::new(), var_depth: self.var_depth.take() });
|
||||
self.scopes.push(Scope { depth: self.depth(), start: t.start, saved: HashMap::new(), var_depth: self.var_depth.take() });
|
||||
// The parameters are the body's own names, and so are the names it declares.
|
||||
for name in params {
|
||||
self.acc.steps = self.acc.steps.saturating_add(1);
|
||||
@@ -1267,6 +1373,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
local: false,
|
||||
shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true),
|
||||
own: platform_name(name),
|
||||
writer: 0,
|
||||
};
|
||||
let outside = std::mem::replace(&mut c.saved, empty);
|
||||
if let Some(scope) = self.scopes.last_mut() {
|
||||
@@ -1290,6 +1397,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.start_value(a.name, Operand::Done(Held::File { folder: false }));
|
||||
} else if !a.after_new && t.is("(") {
|
||||
self.start_group(a.name);
|
||||
} else if !a.after_new && t.is("{") {
|
||||
// An object literal: its keys are read at the depth inside its `{` ([`Self::object_key`]).
|
||||
self.unbind(&a.name);
|
||||
let [_, _, declaration, before] = self.h;
|
||||
let depth = self.depth();
|
||||
let body = self.scopes.last().map_or(0, |s| s.depth);
|
||||
let starts = before.is_none()
|
||||
|| [";", "{", "}"].iter().any(|p| is(before, p))
|
||||
// A line break after a label's `:` does not end the statement the label may be
|
||||
// the body of (`if (c) l:` before the line).
|
||||
|| (declaration.is_some_and(|d| d.nl) && !is(before, ")") && !is(before, ":") && !word(before, "else") && !word(before, "do"));
|
||||
let whole = word(declaration, "var") && starts && depth.checked_sub(1) == Some(body);
|
||||
if self.objects.len() < self.acc.limits.nesting {
|
||||
self.objects.push(ObjectValue { name: a.name, depth, bits: 0, whole, value: None });
|
||||
}
|
||||
} else {
|
||||
self.unbind(&a.name);
|
||||
}
|
||||
@@ -1316,9 +1438,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
// A name after `.`, `..`, `.@`, `::` or `@` is a property's or an attribute's; any other
|
||||
// name before `=` is a variable, at the start of a statement or inside an expression.
|
||||
if !member_mark(h1) && !is(h1, "@") {
|
||||
if !self.scopes.is_empty() && !self.declared_in_body(name.text) {
|
||||
self.reassigned_later(name.text);
|
||||
}
|
||||
self.assign = Some(Assign { name: name.text.to_string(), after_new: false });
|
||||
}
|
||||
}
|
||||
if let Some((name, _)) = self.updated(t)
|
||||
&& !self.scopes.is_empty()
|
||||
&& !self.declared_in_body(name)
|
||||
{
|
||||
self.reassigned_later(name);
|
||||
}
|
||||
match self.updated(t) {
|
||||
// The value on the right is read at this depth, and the name holds nothing the check
|
||||
// follows once that value ends ([`Analyzer::settle_groups`]).
|
||||
@@ -1328,6 +1459,85 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins
|
||||
/// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t`
|
||||
/// closes a function body, so a literal given to the body's own variable stays inside the body.
|
||||
/// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods.
|
||||
fn settle_literal(&mut self, t: &Sig<'s>) {
|
||||
if let Some((name, bits)) = self.closed.take()
|
||||
&& (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t)))
|
||||
&& !self.later_full
|
||||
&& !self.later.contains(&name)
|
||||
&& !self.declared.looped_full
|
||||
&& (self.writers.contains_key(&name) || self.acc.room(self.writers.len()))
|
||||
{
|
||||
self.writers.insert(name, bits);
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` may get another value when code read elsewhere runs: a function body assigns it without
|
||||
/// declaring it, and the function may be called before or after any line, or it is assigned as a
|
||||
/// property of `this`. Its object literal's methods are no longer known, now or later.
|
||||
fn reassigned_later(&mut self, name: &str) {
|
||||
self.writers.remove(name);
|
||||
if !self.later.contains(name) {
|
||||
if self.acc.room(self.later.len()) {
|
||||
self.later.insert(name.to_string());
|
||||
} else {
|
||||
self.later_full = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The global variable `name` is assigned as a property of `this`: as [`Self::reassigned_later`],
|
||||
/// and when a function body's own variable hides it, the global's methods saved for the body's
|
||||
/// end are no longer known either.
|
||||
pub(super) fn reassigned_global(&mut self, name: &str) {
|
||||
self.reassigned_later(name);
|
||||
if let Some(saved) = self.scopes.iter_mut().find_map(|s| s.saved.get_mut(name)) {
|
||||
saved.writer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` is declared in the innermost function body (`var name`, `function
|
||||
/// name`, a parameter).
|
||||
fn declared_in_body(&self, name: &str) -> bool {
|
||||
self.scopes.last().is_some_and(|s| s.saved.get(name).is_some_and(|v| v.local))
|
||||
}
|
||||
|
||||
/// `t` in an object literal assigned to a variable, `before` the bracket depth before `t`: a single
|
||||
/// function expression directly inside its braces as the whole value of a key that names a
|
||||
/// document method writing a file (`{saveAs: function … {…}, …}`, `{'exportFile': function … {…}}`)
|
||||
/// counts the method for the literal, and any other value of that key (`{saveAs: d.saveAs}`,
|
||||
/// `{saveAs: function () {} && d.saveAs}`) takes it out again ([`ObjectValue::step`]). A closing
|
||||
/// brace ends the literals it closes. The variable joins [`Analyzer::writers`] only after the
|
||||
/// literal ([`Analyzer::settle_literal`]), so a call inside the literal, and a value that goes on
|
||||
/// (`{…} && d`), see the variable as it was.
|
||||
fn object_key(&mut self, t: &Sig<'s>, before: usize) {
|
||||
if let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) {
|
||||
o.step(t);
|
||||
}
|
||||
let depth = self.depth();
|
||||
while let Some(o) = self.objects.pop_if(|o| o.depth > depth) {
|
||||
if o.whole && o.bits != 0 && o.depth == depth.saturating_add(1) {
|
||||
self.closed = Some((o.name, o.bits));
|
||||
}
|
||||
}
|
||||
let [h0, h1, h2, _] = self.h;
|
||||
if !is(h0, ":") || !(is(h2, "{") || is(h2, ",")) {
|
||||
return;
|
||||
}
|
||||
let key = match h1 {
|
||||
Some(k) if k.kind == T::Ident => Cow::Borrowed(k.text),
|
||||
Some(k) if k.kind == T::Str => Cow::Owned(unquote(k.text, 32)),
|
||||
_ => return,
|
||||
};
|
||||
let Some(i) = catalog::DOM_FILE_WRITES.iter().position(|m| *m == key.as_ref()) else { return };
|
||||
// A value that starts with a bracket has opened it already: the key is at the depth before it.
|
||||
let Some(o) = self.objects.last_mut().filter(|o| o.depth == before) else { return };
|
||||
o.value = Some((1 << i, if t.word("function") { Value::Function } else { Value::Other }));
|
||||
}
|
||||
|
||||
/// The variable that `t` changes to a number or a string, nothing the check follows, and whether
|
||||
/// the change waits for the value on the right. `name += …` and the other compound assignments
|
||||
/// (ECMA-262 3rd edition, section 11.13.2) store their result after that value is read, so the
|
||||
@@ -1542,6 +1752,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.var_depth = None;
|
||||
self.conds.clear();
|
||||
self.h = [None; 4];
|
||||
self.h4 = None;
|
||||
self.acc.steps = self.acc.steps.saturating_add(1);
|
||||
let d = directives::parse(t.text);
|
||||
let Some(name) = d.known else {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The names declared, read before the analysis.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word};
|
||||
|
||||
@@ -14,10 +14,41 @@ const UNREAD_BINDINGS: &[&str] = &["with", "eval", "Function", catalog::DOLLAR_E
|
||||
/// The property a function reaches `Function` through.
|
||||
const CONSTRUCTOR: &str = "constructor";
|
||||
|
||||
/// The statements whose parentheses the rest of the statement follows, so a line break after them
|
||||
/// does not end a loop's body without braces.
|
||||
const HEADS: &[&str] = &["if", "while", "for", "with", "switch"];
|
||||
|
||||
/// The longest property name, in characters, that [`Declared::rebound`] keeps. A string literal in
|
||||
/// brackets that spells a longer one sets [`Declared::unsure`].
|
||||
const PROPERTY_CHARS: usize = 256;
|
||||
|
||||
#[cfg(not(test))]
|
||||
type LoopSpans = Vec<(usize, usize)>;
|
||||
|
||||
#[cfg(test)]
|
||||
#[derive(Default)]
|
||||
pub(super) struct LoopSpans {
|
||||
spans: Vec<(usize, usize)>,
|
||||
reads: std::cell::Cell<usize>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl std::ops::Deref for LoopSpans {
|
||||
type Target = Vec<(usize, usize)>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.reads.set(self.reads.get() + 1);
|
||||
&self.spans
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl std::ops::DerefMut for LoopSpans {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.spans
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a file's function bodies and its global code declare, read before the analysis. A
|
||||
/// function's `var` statements and the function declarations directly in its body make the names
|
||||
/// they declare the function's own before any statement in it runs, and the function declarations
|
||||
@@ -36,6 +67,16 @@ pub(crate) struct Declared<'s> {
|
||||
/// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be
|
||||
/// the global object, so a variable of that name may get a value the analysis doesn't read.
|
||||
pub(super) rebound: HashSet<String>,
|
||||
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
|
||||
/// offset of the `{` of the function body that declares it (`None`: the global code's), with the
|
||||
/// outermost loops that assign it, entries of `loop_spans`.
|
||||
pub(super) looped: HashMap<(Option<usize>, &'s str), Vec<usize>>,
|
||||
/// For each outermost loop, the offsets in the text where it starts and ends (`usize::MAX`: at
|
||||
/// the end of the text).
|
||||
pub(super) loop_spans: LoopSpans,
|
||||
/// `looped` or `loop_spans` ran out of room, or loops nest past [`crate::Limits::nesting`]: any
|
||||
/// variable may be assigned in a loop.
|
||||
pub(super) looped_full: bool,
|
||||
/// The file gives names values the analysis doesn't read in other ways ([`UNREAD_BINDINGS`] or
|
||||
/// a `constructor` property used, a property read, called or assigned whose name in brackets is
|
||||
/// not one string or number literal, which may be a variable's name on the global object
|
||||
@@ -46,14 +87,23 @@ pub(crate) struct Declared<'s> {
|
||||
pub(super) unsure: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl Declared<'_> {
|
||||
pub(crate) fn loop_span_reads(&self) -> usize {
|
||||
self.loop_spans.reads.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// A function body [`Declarations`] is reading: the bracket depth inside it, its entry in
|
||||
/// [`Declared::bodies`], the names it declares so far, and the bracket depth of the `var` statement
|
||||
/// the body is in, which goes on when the body closes.
|
||||
/// the body is in, which goes on when the body closes, and the names assigned in a loop inside it
|
||||
/// so far, each with its loops ([`Declared::looped`]).
|
||||
struct Body<'s> {
|
||||
depth: usize,
|
||||
index: usize,
|
||||
names: HashSet<&'s str>,
|
||||
var_depth: Option<usize>,
|
||||
looped: HashMap<&'s str, Vec<usize>>,
|
||||
}
|
||||
|
||||
/// A `[` [`Declarations`] is reading: the bracket depth inside it, whether a property's name in
|
||||
@@ -87,9 +137,46 @@ struct Declarations<'s, 'a, 'l> {
|
||||
untracked: Option<usize>,
|
||||
/// The `[` brackets being read, the innermost last, up to [`crate::Limits::nesting`].
|
||||
keys: Vec<Key>,
|
||||
/// The loops being read, the innermost last, up to [`crate::Limits::nesting`].
|
||||
loops: Vec<Loop>,
|
||||
out: Declared<'s>,
|
||||
}
|
||||
|
||||
/// A loop [`Declarations`] is reading: the bracket depth of its keyword, how far it has been read,
|
||||
/// and, for a body without braces, whether the last `{` at that depth opened a block (not an object
|
||||
/// literal), whether an `if`, `while`, `for` or `with` at that depth waits for its `)`, and whether
|
||||
/// the last token was that `)`.
|
||||
struct Loop {
|
||||
depth: usize,
|
||||
stage: Stage,
|
||||
block: bool,
|
||||
head: bool,
|
||||
after_head: bool,
|
||||
/// The loop starts with `do` and has a trailing condition.
|
||||
do_loop: bool,
|
||||
}
|
||||
|
||||
/// How far a [`Loop`] has been read.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Stage {
|
||||
/// The parentheses after `for` or `while`.
|
||||
Head,
|
||||
/// The parentheses after the `while` of a `do` loop.
|
||||
DoHead,
|
||||
/// The `)` of a `do` loop's `while` was read: the loop ends with the `;` after it, or before the
|
||||
/// next token.
|
||||
DoEnd,
|
||||
/// The body's first token is next.
|
||||
Start,
|
||||
/// A body in braces.
|
||||
Block,
|
||||
/// A body that is one statement without braces.
|
||||
Statement,
|
||||
/// The statement of a body without braces has reached its end: the loop ends at the next token,
|
||||
/// unless it is `else`, `catch` or `finally`, which go on with the statement.
|
||||
Tail,
|
||||
}
|
||||
|
||||
/// What `src` declares ([`Declared`]), read in one pass over its tokens.
|
||||
pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
let mut lexer = Lexer::new(src, acc.limits.nesting);
|
||||
@@ -103,6 +190,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
bodies: vec![],
|
||||
untracked: None,
|
||||
keys: vec![],
|
||||
loops: vec![],
|
||||
out: Declared::default(),
|
||||
};
|
||||
let mut breaks = LineBreaks::default();
|
||||
@@ -113,7 +201,15 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
Read::Token(sig) => d.token(sig),
|
||||
}
|
||||
}
|
||||
// A body the file does not close keeps its names assigned in a loop as well.
|
||||
while let Some(body) = d.bodies.pop() {
|
||||
d.settle_looped(body);
|
||||
}
|
||||
let mut out = d.out;
|
||||
for ids in out.looped.values_mut() {
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
}
|
||||
out.unsure |= out.rebound.contains(catalog::FOLDER);
|
||||
acc.steps = acc.steps.saturating_add(lexer.steps);
|
||||
out
|
||||
@@ -138,12 +234,22 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if t.nl && self.var_depth == Some(self.depth()) && !goes_on_after(h0) && !goes_on_with(&t) {
|
||||
self.var_depth = None;
|
||||
}
|
||||
self.loop_start(&t);
|
||||
if t.kind == T::Punct {
|
||||
self.bracket(&t);
|
||||
} else if t.kind == T::Ident {
|
||||
self.declaration(&t);
|
||||
}
|
||||
let depth = self.depth();
|
||||
self.loop_end(&t, depth);
|
||||
if t.is("=")
|
||||
&& !self.loops.is_empty()
|
||||
&& !member_mark(h1)
|
||||
&& !is(h1, "@")
|
||||
&& let Some(name) = h0.filter(|s| s.kind == T::Ident)
|
||||
{
|
||||
self.looped(name.text);
|
||||
}
|
||||
if let Some(after_new) = self.assign.take() {
|
||||
if t.word("new") && !after_new {
|
||||
self.assign = Some(true);
|
||||
@@ -167,6 +273,209 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
self.h = [Some(t), h0, h1];
|
||||
}
|
||||
|
||||
/// `t`, a token before the brackets are followed past it: the body of the innermost loop starts
|
||||
/// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any
|
||||
/// variable may be assigned in one ([`Declared::looped_full`]).
|
||||
fn loop_start(&mut self, t: &Sig<'s>) {
|
||||
let [h0, h1, ..] = self.h;
|
||||
let depth = self.depth();
|
||||
while let Some(l) = self.loops.last_mut() {
|
||||
let after_head = std::mem::take(&mut l.after_head);
|
||||
match l.stage {
|
||||
Stage::Start => {
|
||||
l.stage = if t.is("{") { Stage::Block } else { Stage::Statement };
|
||||
l.head = HEADS.iter().any(|w| t.word(w)) && !member_mark(h0);
|
||||
break;
|
||||
}
|
||||
// A line break ends a body of one statement where the tokens on either side of it
|
||||
// don't go on with it, as in [`Analyzer::token`], and it does not follow the
|
||||
// parentheses of an `if` or another statement that the body goes on with.
|
||||
Stage::Statement
|
||||
if t.nl
|
||||
&& depth == l.depth
|
||||
&& !goes_on_after(h0)
|
||||
&& !goes_on_with(t)
|
||||
&& !after_head
|
||||
&& !["else", "do", "catch", "finally"].iter().any(|w| word(h0, w) && !member_mark(h1)) =>
|
||||
{
|
||||
l.stage = Stage::Tail;
|
||||
}
|
||||
Stage::Statement => {
|
||||
if depth == l.depth {
|
||||
if t.is("{") {
|
||||
l.block = t.stmt || after_head || word(h0, "else") || (word(h0, "finally") && !member_mark(h1));
|
||||
} else if HEADS.iter().any(|w| t.word(w)) && !member_mark(h0) {
|
||||
l.head = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
Stage::Tail if l.do_loop && t.word("while") => {
|
||||
l.stage = Stage::DoHead;
|
||||
return;
|
||||
}
|
||||
Stage::Tail if t.word("else") => {
|
||||
l.stage = Stage::Statement;
|
||||
break;
|
||||
}
|
||||
// The `catch` and `finally` of a `try` statement that is the body go on with it.
|
||||
Stage::Tail if t.word("catch") || t.word("finally") => {
|
||||
l.stage = Stage::Statement;
|
||||
l.head = t.word("catch");
|
||||
break;
|
||||
}
|
||||
Stage::DoEnd if t.is(";") && depth == l.depth => break,
|
||||
Stage::Tail | Stage::DoEnd => {
|
||||
self.pop_loop(t.start);
|
||||
// A body of one statement that is this loop ends with it.
|
||||
if let Some(outer) = self.loops.last_mut()
|
||||
&& outer.stage == Stage::Statement
|
||||
&& outer.depth == depth
|
||||
{
|
||||
outer.stage = Stage::Tail;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
let stage = if (t.word("for") || t.word("while")) && !member_mark(h0) {
|
||||
Stage::Head
|
||||
} else if t.word("do") && !member_mark(h0) {
|
||||
Stage::Start
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
if self.loops.len() >= self.acc.limits.nesting || (self.loops.is_empty() && !self.acc.room(self.out.loop_spans.len())) {
|
||||
self.out.looped_full = true;
|
||||
} else {
|
||||
if self.loops.is_empty() {
|
||||
self.out.loop_spans.push((t.start, usize::MAX));
|
||||
}
|
||||
self.loops.push(Loop { depth, stage, block: false, head: false, after_head: false, do_loop: t.word("do") });
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the innermost loop at offset `at`, which ends the outermost one in
|
||||
/// [`Declared::loop_spans`].
|
||||
fn pop_loop(&mut self, at: usize) {
|
||||
self.loops.pop();
|
||||
if self.loops.is_empty()
|
||||
&& let Some((_, end)) = self.out.loop_spans.last_mut()
|
||||
{
|
||||
*end = at;
|
||||
}
|
||||
}
|
||||
|
||||
/// `t`, after the brackets are followed past it to `depth`: the parentheses of a loop end at the
|
||||
/// `)` back at its depth, and a body in braces at the `}` back at it. A body of one statement
|
||||
/// reaches its end ([`Stage::Tail`]) at a `;` at the loop's depth, at a `}` there that closes a
|
||||
/// block, or with a loop that is that statement. A bracket closing below a loop's depth ends it.
|
||||
fn loop_end(&mut self, t: &Sig<'s>, depth: usize) {
|
||||
let mut inner = false;
|
||||
while let Some(l) = self.loops.last_mut() {
|
||||
let ended = depth < l.depth
|
||||
|| match l.stage {
|
||||
Stage::Head => {
|
||||
if t.is(")") && depth == l.depth {
|
||||
l.stage = Stage::Start;
|
||||
}
|
||||
false
|
||||
}
|
||||
Stage::DoHead => {
|
||||
if t.is(")") && depth == l.depth {
|
||||
l.stage = Stage::DoEnd;
|
||||
}
|
||||
false
|
||||
}
|
||||
Stage::DoEnd => t.is(";") && depth == l.depth,
|
||||
Stage::Block => {
|
||||
if t.is("}") && depth == l.depth && l.do_loop {
|
||||
l.stage = Stage::Tail;
|
||||
false
|
||||
} else {
|
||||
t.is("}") && depth == l.depth
|
||||
}
|
||||
}
|
||||
Stage::Statement => {
|
||||
if depth == l.depth {
|
||||
if t.is(";") || (t.is("}") && l.block) || inner {
|
||||
l.stage = Stage::Tail;
|
||||
} else if t.is(")") && l.head {
|
||||
l.head = false;
|
||||
l.after_head = true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
Stage::Start | Stage::Tail => false,
|
||||
};
|
||||
if !ended {
|
||||
break;
|
||||
}
|
||||
self.pop_loop(t.start);
|
||||
inner = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` is assigned in the loops being read: kept with the outermost one for the innermost
|
||||
/// function body that declares it when that body closes ([`Self::settle_looped`]), or for the
|
||||
/// global code.
|
||||
fn looped(&mut self, name: &'s str) {
|
||||
let id = self.out.loop_spans.len().saturating_sub(1);
|
||||
match self.bodies.last_mut() {
|
||||
Some(body) if body.looped.contains_key(name) || self.acc.room(body.looped.len()) => {
|
||||
let ids = body.looped.entry(name).or_default();
|
||||
if !ids.contains(&id) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
Some(_) => self.out.looped_full = true,
|
||||
None => self.keep_looped(None, name, vec![id]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The names assigned in a loop inside `body`, which is closing: the body's own are kept for it,
|
||||
/// and the others go to the body around it, or to the global code.
|
||||
fn settle_looped(&mut self, body: Body<'s>) {
|
||||
let start = self.out.bodies.get(body.index).map(|(at, _)| *at);
|
||||
for (name, ids) in body.looped {
|
||||
if body.names.contains(name) {
|
||||
self.keep_looped(start, name, ids);
|
||||
} else if let Some(outer) = self.bodies.last_mut() {
|
||||
if outer.looped.contains_key(name) || self.acc.room(outer.looped.len()) {
|
||||
let kept = outer.looped.entry(name).or_default();
|
||||
for id in ids {
|
||||
if !kept.contains(&id) {
|
||||
kept.push(id);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.out.looped_full = true;
|
||||
}
|
||||
} else {
|
||||
self.keep_looped(None, name, ids);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps `name` of `body` as assigned in outermost loops `ids`.
|
||||
fn keep_looped(&mut self, body: Option<usize>, name: &'s str, ids: Vec<usize>) {
|
||||
let len = self.out.looped.len();
|
||||
match self.out.looped.get_mut(&(body, name)) {
|
||||
Some(kept) => {
|
||||
for id in ids {
|
||||
if !kept.contains(&id) {
|
||||
kept.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
None if self.acc.room(len) => {
|
||||
self.out.looped.insert((body, name), ids);
|
||||
}
|
||||
None => self.out.looped_full = true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `t`, a token before the brackets are followed past it: notes in [`Declared::rebound`] and
|
||||
/// [`Declared::unsure`] the ways the file gives names values the analysis doesn't read.
|
||||
fn unread_binding(&mut self, t: &Sig<'s>) {
|
||||
@@ -234,7 +543,13 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if self.bodies.len() < self.acc.limits.nesting {
|
||||
let index = self.out.bodies.len();
|
||||
self.out.bodies.push((t.start, vec![]));
|
||||
self.bodies.push(Body { depth: self.depth(), index, names: HashSet::new(), var_depth: self.var_depth.take() });
|
||||
self.bodies.push(Body {
|
||||
depth: self.depth(),
|
||||
index,
|
||||
names: HashSet::new(),
|
||||
var_depth: self.var_depth.take(),
|
||||
looped: HashMap::new(),
|
||||
});
|
||||
} else if self.untracked.is_none() {
|
||||
self.untracked = Some(self.depth());
|
||||
}
|
||||
@@ -261,6 +576,7 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
}
|
||||
while let Some(body) = self.bodies.pop_if(|b| depth < b.depth) {
|
||||
self.var_depth = body.var_depth;
|
||||
self.settle_looped(body);
|
||||
}
|
||||
if self.untracked.is_some_and(|d| depth < d) {
|
||||
self.untracked = None;
|
||||
|
||||
@@ -85,6 +85,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.writer_use(t);
|
||||
match t.kind {
|
||||
T::Ident => self.name(t, line),
|
||||
T::Punct => self.punct(t, line),
|
||||
@@ -130,6 +131,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `SaveOptions.SAVECHANGES` read at `line`: a `Document.close` given it saves the document to
|
||||
/// its own file, and the value may reach `close` through a variable or an argument.
|
||||
fn save_changes(&mut self, line: Option<usize>) {
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
}
|
||||
|
||||
/// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes.
|
||||
fn file_setter(&mut self, line: Option<usize>) {
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
@@ -200,6 +208,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
} else if of(catalog::FOLDER) && catalog::FOLDER_PLACES.contains(&n) {
|
||||
self.acc.feature(FeatureId::FilePlaces, line);
|
||||
}
|
||||
if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) {
|
||||
self.save_changes(line);
|
||||
}
|
||||
if n == catalog::ON_DRAW {
|
||||
self.acc.feature(FeatureId::ScriptuiDrawing, line);
|
||||
}
|
||||
@@ -272,8 +283,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
"]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => {
|
||||
let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default();
|
||||
self.setter(&name, h2, h3, line);
|
||||
if name == catalog::SAVE_CHANGES
|
||||
&& word(h2, catalog::SAVE_OPTIONS)
|
||||
&& !member_mark(h3)
|
||||
&& !self.own_names.contains(catalog::SAVE_OPTIONS)
|
||||
{
|
||||
self.save_changes(line);
|
||||
}
|
||||
}
|
||||
"(" => self.call(line),
|
||||
// `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.call(t, line),
|
||||
// `Name.prototype["+"] = …` defines an operator.
|
||||
"=" => {
|
||||
let operator = || h1.filter(|s| s.kind == T::Str).is_some_and(|s| catalog::OPERATORS.contains(&unquote(s.text, 4).as_str()));
|
||||
@@ -288,13 +308,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
|
||||
/// `(` after a name: a call.
|
||||
fn call(&mut self, line: Option<usize>) {
|
||||
fn call(&mut self, t: &Sig<'s>, line: Option<usize>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
// `doc['exportVariables'](f)`: a document method named by a string literal in brackets.
|
||||
// `doc['saveAs'](f)`: a document method named by a string literal in brackets.
|
||||
if is(h0, "]")
|
||||
&& is(h2, "[")
|
||||
&& let Some(name) = h1.filter(|s| s.kind == T::Str)
|
||||
&& catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str())
|
||||
&& let Some(method) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
|
||||
&& catalog::DOM_FILE_WRITES.contains(&method.as_str())
|
||||
&& !Self::defines(self.index_receiver, &method)
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
@@ -320,7 +341,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
self.acc.feature(FeatureId::FileDialog, line);
|
||||
} else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) {
|
||||
self.acc.feature(FeatureId::FileRead, line);
|
||||
} else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) {
|
||||
} else if (file && catalog::FILE_WRITES.contains(&n))
|
||||
|| (catalog::DOM_FILE_WRITES.contains(&n) && !Self::defines(self.writer_bits(h2, h3, Some(t.start)), n))
|
||||
{
|
||||
self.acc.feature(FeatureId::FileWrite, line);
|
||||
self.acc.outside(OutsideId::FilesWritten, line, None);
|
||||
} else if n == catalog::EXECUTE {
|
||||
@@ -343,6 +366,87 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The methods that `receiver`, which `before` comes before, defines when it is a variable holding
|
||||
/// an object literal of the script's own ([`Analyzer::writers`]), not a property of the same name;
|
||||
/// 0 for anything else. A receiver the check does not follow may be a document.
|
||||
/// At call offset `at`, a variable assigned in a loop containing that offset may be a document.
|
||||
fn writer_bits(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>, at: Option<usize>) -> u8 {
|
||||
match receiver {
|
||||
Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => {
|
||||
let Some(bits) = self.writers.get(r.text).copied() else { return 0 };
|
||||
if at.is_some() && !self.scopes.is_empty() && !self.declared_in_body(r.text) {
|
||||
return 0;
|
||||
}
|
||||
let looped = at.is_some_and(|at| {
|
||||
self.declared.looped_full
|
||||
|| self.declared.looped.get(&(self.scopes.last().map(|s| s.start), r.text)).is_some_and(|ids| {
|
||||
let next = self.declared.loop_spans.partition_point(|(start, _)| *start <= at);
|
||||
next.checked_sub(1).is_some_and(|id| at < self.declared.loop_spans[id].1 && ids.binary_search(&id).is_ok())
|
||||
})
|
||||
});
|
||||
if looped { 0 } else { bits }
|
||||
}
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable of [`Analyzer::writers`] used before `t` in any way but a member (`local.name`,
|
||||
/// `local['name']`) or an assignment to it ([`Analyzer::assignment`]), or whose `saveAs` or
|
||||
/// `exportFile` is assigned: another name may hold its object, or its methods may change, so its
|
||||
/// own methods are no longer known (`var b = local`, `f(local)`, `local.saveAs = w`,
|
||||
/// `local[k] = w`, `delete local.saveAs`).
|
||||
fn writer_use(&mut self, t: &Sig<'s>) {
|
||||
let [h0, h1, h2, h3] = self.h;
|
||||
let changes = t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--"));
|
||||
let key = t.is(":") && (is(h1, "{") || is(h1, ","));
|
||||
// `this.local = …` or `this['local'] = …`: `this` is the global object in the global code and in a
|
||||
// function called without a receiver (ECMA-262 3rd edition, sections 10.2.1 and 10.2.3), so the
|
||||
// global variable of that name may get another value.
|
||||
if changes {
|
||||
// `this`, not a property named `this` (`holder.this.d`).
|
||||
let global = if is(h1, ".") && word(h2, "this") && !member_mark(h3) {
|
||||
h0.filter(|s| s.kind == T::Ident).map(|s| s.text.to_string())
|
||||
} else if is(h0, "]") && is(h2, "[") && word(h3, "this") && !member_mark(self.h4) {
|
||||
h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 64))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = global {
|
||||
self.reassigned_global(&name);
|
||||
}
|
||||
}
|
||||
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)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(name) = escaped {
|
||||
self.writers.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `bits` ([`Self::writer_bits`]) has `method`: the receiver's own `method` is called.
|
||||
fn defines(bits: u8, method: &str) -> bool {
|
||||
catalog::DOM_FILE_WRITES.iter().position(|m| *m == method).is_some_and(|i| bits & (1 << i) != 0)
|
||||
}
|
||||
|
||||
/// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object
|
||||
/// (not a property of the same name), or a File or Folder object made in place or held in
|
||||
/// grouping parentheses ([`Sig::file`]): `Some(true)` for a Folder object whatever the path names
|
||||
@@ -365,6 +469,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
if t.text.contains(catalog::ACTION_TEXT) {
|
||||
self.acc.feature(FeatureId::Actions, line);
|
||||
}
|
||||
// The value written as the string `"SaveOptions.SAVECHANGES"`.
|
||||
let value = unquote(t.text, 32);
|
||||
if value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES) {
|
||||
self.save_changes(line);
|
||||
}
|
||||
let compares = h0.is_some_and(|s| s.kind == T::Punct && matches!(s.text, "==" | "===" | "!=" | "!=="));
|
||||
if compares && word(h1, "typename") && is(h2, ".") {
|
||||
let name = unquote(t.text, self.acc.limits.echo.saturating_add(1));
|
||||
|
||||
@@ -77,7 +77,13 @@ pub(crate) const REFLECT: &str = "reflect";
|
||||
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] = &["exportVariables"];
|
||||
pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "exportVariables", "saveAs"];
|
||||
|
||||
// The save option of `Document.close` that saves the document to its own file:
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and
|
||||
// https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ (SaveOptions).
|
||||
pub(crate) const SAVE_CHANGES: &str = "SAVECHANGES";
|
||||
pub(crate) const SAVE_OPTIONS: &str = "SaveOptions";
|
||||
|
||||
// Application methods that page doesn't list, named in public forum posts:
|
||||
// https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand,
|
||||
|
||||
@@ -537,6 +537,19 @@ fn the_scripts_own_platform_names_are_not_the_platforms() {
|
||||
assert_eq!(r.outside.iter().map(|o| o.id).collect::<Vec<_>>(), ["filesWritten"]);
|
||||
}
|
||||
|
||||
/// A document's `saveAs` and `exportFile` write the file they are given; `app.open` only reads one.
|
||||
#[test]
|
||||
fn save_as_and_export_file_write_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var d = app.open(f);\n",
|
||||
"d.saveAs(f);\n",
|
||||
"app.activeDocument.exportFile(f, ExportType.PNG24);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
|
||||
}
|
||||
|
||||
/// A document's `exportVariables` writes the file it is given; `importVariables` only reads one.
|
||||
#[test]
|
||||
fn export_variables_writes_a_file() {
|
||||
@@ -560,6 +573,408 @@ 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][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evaluated_code_keeps_warnings_for_rebound_writer_receivers() {
|
||||
for call in ["local.exportVariables(f);", "local['exportVariables'](f);", "local.saveAs(f);", "local['exportFile'](f);"] {
|
||||
let r = report(&format!(
|
||||
"var local = {{exportVariables: function () {{}}, saveAs: function () {{}}, exportFile: function () {{}}}};\n\
|
||||
eval('local = app.activeDocument');\n{call}\n"
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]), "{call}");
|
||||
let written = r.outside.iter().find(|o| o.id == "filesWritten");
|
||||
assert_eq!(written.map(|o| o.lines.as_slice()), Some(&[3][..]), "{call}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `SaveOptions.SAVECHANGES` makes a document's `close` save it to its own file, read directly, in
|
||||
/// brackets, as a string or through a variable; closing without it, and the other save options,
|
||||
/// write nothing.
|
||||
#[test]
|
||||
fn closing_with_save_changes_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"app.activeDocument.close();\n",
|
||||
"app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);\n",
|
||||
"app.activeDocument.close(SaveOptions.PROMPTTOSAVECHANGES);\n",
|
||||
"app.activeDocument.close(SaveOptions.SAVECHANGES);\n",
|
||||
"var how = SaveOptions['SAVECHANGES'];\n",
|
||||
"documents[0].close(how);\n",
|
||||
"documents[1].close('SaveOptions.SAVECHANGES');\n",
|
||||
"var w = new Window('dialog'); w.close(1);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 7][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[4, 5, 7][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_save_changes_properties_and_strings_do_not_report_writes() {
|
||||
let r = report(concat!(
|
||||
"var a = other.SAVECHANGES;\n",
|
||||
"var b = other['SAVECHANGES'];\n",
|
||||
"app.activeDocument.close('SAVECHANGES');\n",
|
||||
"var c = holder.SaveOptions.SAVECHANGES;\n",
|
||||
"var d = holder.SaveOptions['SAVECHANGES'];\n",
|
||||
"var e = 'SAVECHANGES';\n",
|
||||
"var key = SaveOptions['SAVECHANGES' + suffix];\n",
|
||||
"var f = SaveOptions.SAVECHANGES;\n",
|
||||
"var g = SaveOptions['SAVECHANGES'];\n",
|
||||
"var h = 'SaveOptions.SAVECHANGES';\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[8, 9, 10][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[8, 9, 10][..])]);
|
||||
}
|
||||
|
||||
/// `saveAs` and `exportFile` called with their names as string literals in brackets write the file
|
||||
/// too; reading the method without calling it does not.
|
||||
#[test]
|
||||
fn save_as_and_export_file_in_brackets_write_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"app.activeDocument['open'](f);\n",
|
||||
"app.activeDocument[\"saveAs\"](f);\n",
|
||||
"var d = app.activeDocument; d['exportFile'] (f, ExportType.SVG);\n",
|
||||
"var n = d['saveAs'];\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 4][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[3, 4][..])]);
|
||||
}
|
||||
|
||||
/// `saveAs` and `exportFile` called on an object literal of the script's own that defines them write
|
||||
/// nothing, with `.` or in brackets. On a document, on a variable the check does not follow, on one
|
||||
/// assigned something else since, and for a method the literal does not define, they write the file.
|
||||
#[test]
|
||||
fn the_scripts_own_save_as_writes_no_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var local = {saveAs: function () {}, 'n': 1};\n",
|
||||
"local.saveAs(f);\n",
|
||||
"local['saveAs'](f);\n",
|
||||
"app.activeDocument.saveAs(f);\n",
|
||||
"local.exportFile(f);\n",
|
||||
"other.saveAs(f);\n",
|
||||
"local = app.activeDocument;\n",
|
||||
"local.saveAs(f);\n",
|
||||
"var t = {x: 1, a: ok ? saveAs : 0, 'exportFile': function () {}};\n",
|
||||
"t['exportFile'](f);\n",
|
||||
"t.saveAs(f);\n",
|
||||
"var activeDocument = {saveAs: function () {}};\n",
|
||||
"app.activeDocument['saveAs'](f);\n",
|
||||
"app.activeDocument.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 6, 7, 9, 12, 14, 15][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 6, 7, 9, 12, 14, 15][..])]);
|
||||
}
|
||||
|
||||
/// Once the script replaces or deletes such a method, indexes the object with a computed key, or
|
||||
/// lets another name hold the object, its `saveAs` may write a file again, and so may a `saveAs` key
|
||||
/// whose last value in the literal is not a function expression.
|
||||
#[test]
|
||||
fn a_changed_or_shared_own_save_as_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
|
||||
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f); b['saveAs'](f); a.n = 1; a.n;\n",
|
||||
"a.saveAs = app.activeDocument.saveAs;\n",
|
||||
"b['saveAs'] = w;\n",
|
||||
"delete d.saveAs;\n",
|
||||
"var h = e;\n",
|
||||
"use(g);\n",
|
||||
"a.saveAs(f);\n",
|
||||
"b.saveAs(f);\n",
|
||||
"d.saveAs(f);\n",
|
||||
"e.saveAs(f);\n",
|
||||
"g['saveAs'](f);\n",
|
||||
"var m = {saveAs: d.saveAs}; var n = {saveAs: function () {}, saveAs: d.saveAs};\n",
|
||||
"m.saveAs(f);\n",
|
||||
"n.saveAs(f);\n",
|
||||
"var q = {saveAs: function () {}, saveAs: (d.saveAs)}; var s = {saveAs: function () {}, saveAs: [w][0]};\n",
|
||||
"q['saveAs'](f);\n",
|
||||
"s.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 14, 16, 17, 19, 20][..]));
|
||||
// A computed key may name any variable, so every `saveAs` in the script may write, the ones
|
||||
// before the computed key included.
|
||||
let r = report("var f = new File(p);\nvar c = {saveAs: function () {}};\nc.saveAs(f);\nc[k] = w;\nc.saveAs(f);\n");
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3, 5][..]));
|
||||
}
|
||||
|
||||
/// A variable assigned in a loop may hold a document when a later iteration calls its `saveAs`,
|
||||
/// before the assignment in the text: the call writes a file. One assigned only after a loop does
|
||||
/// not.
|
||||
#[test]
|
||||
fn an_own_save_as_reassigned_later_in_a_loop_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}}; var c = {saveAs: function () {}};\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"for (var i = 0; i < 2; i++) { a.saveAs(f); a = app.activeDocument; }\n",
|
||||
"while (n--) b.saveAs(f), b = app.activeDocument;\n",
|
||||
"do { c.saveAs(f); } while ((c = next()));\n",
|
||||
"for (;;) { d.saveAs(f); break; }\n",
|
||||
"d = app.activeDocument;\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 6][..]));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[4, 5, 6][..])]);
|
||||
// The `else` of a body without braces is in the loop; a statement after a line break that ends
|
||||
// such a body is not, and neither is a variable of the same name that a function declares.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var e = {saveAs: function () {}}; var g = {saveAs: function () {}}; var h = {saveAs: function () {}};\n",
|
||||
"while (n--) if (n) e.saveAs(f); else e = app.activeDocument;\n",
|
||||
"while (n--) g.saveAs(f), n\n",
|
||||
"g = app.activeDocument\n",
|
||||
"function k() { var h; for (;;) h = app.activeDocument; }\n",
|
||||
"h.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
// An object literal's `}` does not end a body without braces, a call's `)` before a line break
|
||||
// does, and a literal given after the last loop that assigns its variable is the script's own.
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
|
||||
"while (n--) a.saveAs(f), t = {}, a = app.activeDocument;\n",
|
||||
"b.saveAs(f);\n",
|
||||
"while (n--) tick()\n",
|
||||
"b = app.activeDocument\n",
|
||||
"for (;;) { c = app.activeDocument; }\n",
|
||||
"var c = {saveAs: function () {}};\n",
|
||||
"c.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[3][..]));
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}};\n",
|
||||
"while (n--) if (n)\n",
|
||||
" a.saveAs(f), a = app.activeDocument;\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4][..]));
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {}}; var b = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f); b['saveAs'](f);\n",
|
||||
"while (n--) { a.saveAs(f); a = app.activeDocument; }\n",
|
||||
"while (n--) { b['saveAs'](f); b = app.activeDocument; }\n",
|
||||
"var a = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f);\n",
|
||||
"while (n--) { a.saveAs(f); a = app.activeDocument; }\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 5, 8][..]));
|
||||
}
|
||||
|
||||
/// The `catch` and `finally` of a `try` body, and an `else` after a `do` loop inside a body without
|
||||
/// braces, are in the loop; a statement after the whole loop is not.
|
||||
#[test]
|
||||
fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var d = {saveAs: function () {}}; var e = {saveAs: function () {}}; var g = {saveAs: function () {}};\n",
|
||||
"var h = {saveAs: function () {}};\n",
|
||||
"while (i++ < 2) try { d.saveAs(f); } finally { d = app.activeDocument; }\n",
|
||||
"while (i++ < 2)\n",
|
||||
" if (i === 2) do e.saveAs(f); while (false);\n",
|
||||
" else e = app.activeDocument;\n",
|
||||
"while (n--) do g.saveAs(f); while (false);\n",
|
||||
"g = app.activeDocument;\n",
|
||||
"while (n--) h.saveAs(f), holder.finally\n",
|
||||
"h = app.activeDocument;\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 6][..]));
|
||||
}
|
||||
|
||||
/// A literal after a label's line break may not run, a `this` assignment in a function whose own
|
||||
/// variable hides the global one changes the global, and a property `d` of another object is not
|
||||
/// the variable `d`.
|
||||
#[test]
|
||||
fn labels_hidden_globals_and_other_objects_keep_writes_known() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = app.activeDocument;\n",
|
||||
"if (no) l:\n",
|
||||
"var a = {saveAs: function () {}};\n",
|
||||
"a.saveAs(f);\n",
|
||||
"var b = {saveAs: function () {}};\n",
|
||||
"function change() { var b; this.b = app.activeDocument; }\n",
|
||||
"change(); b.saveAs(f);\n",
|
||||
"var c = {saveAs: function () {}};\n",
|
||||
"function keep() { var c; c = 1; }\n",
|
||||
"keep(); c.saveAs(f);\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"holder.d['saveAs'] = 1;\n",
|
||||
"d.saveAs(f);\n",
|
||||
"var e = {saveAs: function () {}};\n",
|
||||
"e['saveAs'] = app.activeDocument.saveAs;\n",
|
||||
"e.saveAs(f);\n",
|
||||
"var g = {saveAs: function () {}};\n",
|
||||
"function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n",
|
||||
"other(); g.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17][..]));
|
||||
}
|
||||
|
||||
/// Only a `var` statement directly in a function body or the global code that gives its first name
|
||||
/// the literal as its whole value makes the literal's `saveAs` the script's own, from the end of the
|
||||
/// statement. A literal given in a branch, one the value goes on from, one given by an assignment
|
||||
/// or to a later name of the statement, a call inside the literal, and a variable a function gave
|
||||
/// another value keep reporting the write.
|
||||
#[test]
|
||||
fn only_a_whole_var_value_makes_save_as_the_scripts_own() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"function choose() { d = null; d = app.activeDocument; }\n",
|
||||
"d.saveAs(f);\n",
|
||||
"var e = app.activeDocument;\n",
|
||||
"if (flag) var e = {saveAs: function () {}};\n",
|
||||
"e.saveAs(f);\n",
|
||||
"if (flag) { var e2 = {saveAs: function () {}}; }\n",
|
||||
"e2.saveAs(f);\n",
|
||||
"var g = {saveAs: function () {}} && app.activeDocument;\n",
|
||||
"g.saveAs(f);\n",
|
||||
"var h = app.activeDocument;\n",
|
||||
"h = {saveAs: function () {}, value: h.saveAs(f)};\n",
|
||||
"var k = {saveAs: function () {}, value: k.saveAs(f)};\n",
|
||||
"k.saveAs(f);\n",
|
||||
"var x = 1, y = {saveAs: function () {}};\n",
|
||||
"y.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_calls_after_many_assignment_loops_have_bounded_work() {
|
||||
for reinitialize in [false, true] {
|
||||
let mut src = "var d = {saveAs: function () {}};\n".to_string();
|
||||
for _ in 0..512 {
|
||||
src.push_str("while (n--) { d = next(); }\n");
|
||||
}
|
||||
if reinitialize {
|
||||
src.push_str("var d = {saveAs: function () {}};\n");
|
||||
}
|
||||
src.push_str("var local = {saveAs: function () {}};\n");
|
||||
for _ in 0..2048 {
|
||||
src.push_str("d.saveAs(f); local.saveAs(f);\n");
|
||||
}
|
||||
let limits = Limits::default();
|
||||
let mut acc = report::Acc::new(&limits);
|
||||
let declared = analyze::declarations(&src, &mut acc);
|
||||
let before = declared.loop_span_reads();
|
||||
analyze::scan(&src, &declared, &[], None, std::rc::Rc::from([]), &analyze::Known::default(), &mut acc);
|
||||
let reads = declared.loop_span_reads() - before;
|
||||
if reinitialize {
|
||||
assert!(reads < 16 * 2048, "{reads} span accesses for 2048 calls on d");
|
||||
} else {
|
||||
assert_eq!(reads, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A function body read before the literal that assigns its variable without declaring it may run
|
||||
/// after the literal, so the literal's `saveAs` keeps reporting the write; a body that declares the
|
||||
/// name assigns its own variable.
|
||||
#[test]
|
||||
fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function choose() { d = app.activeDocument; }\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"choose(); d.saveAs(f);\n",
|
||||
"function bump() { e++; }\n",
|
||||
"var e = {saveAs: function () {}};\n",
|
||||
"e.saveAs(f);\n",
|
||||
"function own() { var g; g = app.activeDocument; }\n",
|
||||
"var g = {saveAs: function () {}};\n",
|
||||
"g.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_writer_receivers_can_change_before_each_call() {
|
||||
for method in ["saveAs", "exportFile"] {
|
||||
for call in [format!("d.{method}(f)"), format!("d['{method}'](f)")] {
|
||||
for (prefix, suffix) in [("", ""), ("function outer() {\n", "}\nouter();\n")] {
|
||||
let src = format!(
|
||||
"{prefix}var d = {{{method}: function () {{}}}};\n\
|
||||
function save(f) {{ {call}; }}\n\
|
||||
d = app.activeDocument; save(f);\n{suffix}"
|
||||
);
|
||||
let r = report(&src);
|
||||
let line = if prefix.is_empty() { 2 } else { 3 };
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[line][..]), "{src}");
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[line][..])], "{src}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_reassignments_keep_save_as_writing_after_a_later_initializer() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"function outer() {\n",
|
||||
" function choose() { d = app.activeDocument; }\n",
|
||||
" var d = {saveAs: function () {}};\n",
|
||||
" choose(); d.saveAs(f);\n",
|
||||
" function bump() { e++; }\n",
|
||||
" var e = {saveAs: function () {}};\n",
|
||||
" bump(); e.saveAs(f);\n",
|
||||
" function own() { var g; g = app.activeDocument; }\n",
|
||||
" var g = {saveAs: function () {}};\n",
|
||||
" own(); g.saveAs(f);\n",
|
||||
"}\n",
|
||||
"outer();\n",
|
||||
));
|
||||
assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::<Vec<_>>(), [("filesWritten", &[5, 8][..])]);
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8][..]));
|
||||
}
|
||||
|
||||
/// Assigning a property of `this`, the global object in the global code and in a function called
|
||||
/// without a receiver, may give the global variable of that name another value, before or after
|
||||
/// its literal.
|
||||
#[test]
|
||||
fn assigning_a_property_of_this_keeps_save_as_writing() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var d = {saveAs: function () {}};\n",
|
||||
"this.d = app.activeDocument;\n",
|
||||
"d.saveAs(f);\n",
|
||||
"function swap() { this['e'] = app.activeDocument; }\n",
|
||||
"var e = {saveAs: function () {}};\n",
|
||||
"swap(); e.saveAs(f);\n",
|
||||
"var g = {saveAs: function () {}};\n",
|
||||
"this.other = 1;\n",
|
||||
"g.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
|
||||
}
|
||||
|
||||
/// A `saveAs` key's value is a method of the script's own only when the whole value is one function
|
||||
/// expression: a value that goes on after the function's body, and a literal inside another, leave
|
||||
/// `saveAs` writing the file. A literal given to a function body's own variable at the end of the body
|
||||
/// leaves the outer variable as it was.
|
||||
#[test]
|
||||
fn a_value_that_goes_on_after_the_function_writes_a_file() {
|
||||
let r = report(concat!(
|
||||
"var f = new File(p);\n",
|
||||
"var a = {saveAs: function () {} && app.activeDocument.saveAs};\n",
|
||||
"var b = {saveAs: function () {}(f), n: 1};\n",
|
||||
"var c = {saveAs: function () {} ? x : y};\n",
|
||||
"var e = {saveAs: function () {}.call};\n",
|
||||
"var k = {exportFile: function w(x) { return x; }, saveAs: function () {}};\n",
|
||||
"var m = {o: {saveAs: function () {}}};\n",
|
||||
"var q = app.activeDocument; function r() { var q = {saveAs: function () {}}\n",
|
||||
"}\n",
|
||||
"a.saveAs(f);\n",
|
||||
"b.saveAs(f);\n",
|
||||
"c.saveAs(f);\n",
|
||||
"e.saveAs(f);\n",
|
||||
"k.saveAs(f); k.exportFile(f);\n",
|
||||
"m.saveAs(f);\n",
|
||||
"q.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[10, 11, 12, 13, 15, 16][..]));
|
||||
}
|
||||
|
||||
/// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing
|
||||
/// them and setting them on another object does not.
|
||||
#[test]
|
||||
|
||||
@@ -853,6 +853,8 @@ 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, and
|
||||
`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`.
|
||||
File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
|
||||
runs a script in a named engine whose globals last between runs,
|
||||
File › Scripts lists the scripts of the Scripts folder, and
|
||||
|
||||
+94
-4
@@ -2749,9 +2749,11 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
|
||||
while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256
|
||||
characters, assign properties of more than 1,000 different names on members (`o.d = …`, `o['d'] = …`), or
|
||||
assign or declare `Folder`; a variable whose name a member assignment writes counts as one that may hold a File
|
||||
object; a document's `exportVariables` counts too; 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), `filesOpened` (files opened in other apps), `network`,
|
||||
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` or `exportVariables` counts too, and so does `SaveOptions.SAVECHANGES`
|
||||
wherever the script reads it, since `close` given it saves the document to its file), `filesOpened` (files opened
|
||||
in other apps), `network`,
|
||||
`nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`,
|
||||
`new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed).
|
||||
- `problems` lists what would stop the script loading as written (strings, comments, regular expressions,
|
||||
@@ -3106,6 +3108,92 @@ through `$`:
|
||||
strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. Other members
|
||||
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
|
||||
themselves that this page does not describe are not defined yet and read as `undefined`.
|
||||
- `Document.saveAs(file, options?)` runs `file.saveAs`, and the document then has the new file.
|
||||
When the format is selected by a `.vctemplate` path, `saveAs` writes a template copy and leaves the document's
|
||||
file and saved state unchanged.
|
||||
`Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is.
|
||||
`app.open(file, documentColorSpace?, options?)` runs `document.open` and gives the new `Document`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/).
|
||||
`file` is a `File`. `new IllustratorSaveOptions()`, `new EPSSaveOptions()` and `new PDFSaveOptions()` pick the
|
||||
format (https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/);
|
||||
without options the path's extension picks it. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
|
||||
`exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and
|
||||
`compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`), `saveMultipleArtboards` and `artboardRange` of `.ai`;
|
||||
`cmykPostScript`, `includeDocumentThumbnails`, `postScript`, `preview`, `overprint`, `compatibility`,
|
||||
`saveMultipleArtboards` and `artboardRange` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to
|
||||
`ACROBAT8` as PDF 1.3 to 1.7), `artboardRange`, `preserveEditability`, `acrobatLayers` and `compressArt` of PDF.
|
||||
As the `.ai` and EPS help pages say, `artboardRange` is used only with `saveMultipleArtboards` true, and an
|
||||
empty range means every artboard. `Document.fullName` is a `File` for the document's file, `Document.saved` is
|
||||
true when the document has no unsaved changes and can be set, and `Document.close(saveOptions?)` closes the
|
||||
document with the given `SaveOptions` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/).
|
||||
`exportType` is an `ExportType`: `PNG24`, `JPEG` and `SVG` take `new ExportOptionsPNG24()`, `new ExportOptionsJPEG()`
|
||||
and `new ExportOptionsSVG()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/),
|
||||
with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to
|
||||
776.19; 100 writes one pixel per point whatever the raster effects resolution), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and
|
||||
`coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and
|
||||
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s
|
||||
`options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with
|
||||
`pageToOpen` and `pDFCropToBox`. These options require PDF content, including PDF-compatible `.ai` and `.ait` files.
|
||||
`app.open` rejects a file over 128 MiB before reading it.
|
||||
Optional arguments to `saveAs`, `exportFile`, `app.open` and `close` use defaults when omitted or `undefined`;
|
||||
explicit `null` throws a type error. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of
|
||||
each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`,
|
||||
`EPSPostScriptLevelEnum`, `PDFOverprint`, `SaveOptions` and `UserInteractionLevel` hold strings such as
|
||||
`"ExportType.PNG24"`. The enumerations of the options that keep their defaults (`OutputFlattening`,
|
||||
`CompressionQuality`, `ColorConversion`, `ColorDestination`, `ColorProfile`, `DownsampleMethod`,
|
||||
`MonochromeCompression`, `PageMarksTypes`, `PDFChangesAllowedEnum`, `PDFPrintAllowedEnum`, `PDFTrimMarkWeight`,
|
||||
`PDFXStandard`, `SVGCSSPropertyLocation`, `SVGDocumentEncoding`, `SVGDTDVersion`, `SVGFontSubsetting` and
|
||||
`SVGFontType`) are defined too: the default member is accepted, and another member throws as not available yet. A
|
||||
path whose real file name is not valid UTF-8 throws `Script file path is not valid UTF-8` before anything is written
|
||||
or opened.
|
||||
VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the
|
||||
command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open
|
||||
document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is
|
||||
read-only`; a file a `File` object holds open for writing throws `Script file is open for writing` on `saveAs`
|
||||
and `exportFile`, and `Script file access denied` when a command would write it besides the file named; and the
|
||||
files a command reads or writes besides the one named, such as an SVG's linked files, are
|
||||
read and written only where the script's folders allow. `userInteractionLevel` does not change what a command
|
||||
does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the
|
||||
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with
|
||||
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
|
||||
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and
|
||||
when the script's folders refuse one of those files, none of them is written; a write that fails once the
|
||||
first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws
|
||||
an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help
|
||||
pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and
|
||||
`parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
|
||||
keeps the preset's value. A `pDFPreset` in square brackets, such as `[Smallest File Size]`, names the built-in
|
||||
preset of the name inside them; the default preset's name in brackets names VectorCraft Default, and
|
||||
`[PDF/X-4:2008]` names PDF/X-4:2010. Any other name throws `unknown PDF preset`. `artboardRange` takes
|
||||
a whole number from 1 as well as a string, read as `String(number)` reads it; any other number throws. With `saveMultipleArtboards` true, a `.ai` range
|
||||
(every artboard when it is empty) goes to `file.saveAs`'s `separateArtboards`, which also writes each of its
|
||||
artboards to `<name>-<artboard name>.ai`, and an EPS range goes to `useArtboards`, which writes
|
||||
`<name>_<artboard name>.eps` for each of two or more artboards beside the file at the path, and for one artboard
|
||||
writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS
|
||||
`artboardRange` is not checked against the document's artboards, but one that is not written as a range of
|
||||
artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's
|
||||
file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of
|
||||
`""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw
|
||||
`Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved
|
||||
without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an
|
||||
undo step. Assigning its current value runs no command and adds no journal entry.
|
||||
With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`;
|
||||
`SaveOptions.SAVECHANGES` first saves them to the document's file with `file.saveAs`, in the format the document
|
||||
was last saved in and after the same write-access check of the path as `saveAs`, and throws an error
|
||||
and leaves the document open when the document has no file (a converted or recovered document included) or when
|
||||
the save would omit artboards. These refusals occur before writing any files. An SVG or SVGZ save of several
|
||||
artboards requires Preserve Editing Capabilities to close with `SaveOptions.SAVECHANGES`. A PDF last saved with
|
||||
`useArtboards: false` omits artboards; a native file saved with `separateArtboards` and a `.ai` or `.ait` file other
|
||||
than a version 7 `.ai` file keep every artboard whatever their range names. An SVG file saved with Preserve
|
||||
Editing Capabilities carries the native document with every artboard, so `close(SaveOptions.SAVECHANGES)` does not
|
||||
refuse it for omitted artboards. The SVG drawing still shows one artboard, or the art bounds with
|
||||
`useArtboards: false`, and the SVG save still refuses a range that selects several artboards.
|
||||
`SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot
|
||||
show the prompt. A bad value throws an error before anything is written. The warnings of the save or export that
|
||||
`saveAs`, `exportFile`, `app.open` and `close` run go to the console, each after the method's name
|
||||
(`saveAs: …`).
|
||||
- `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the
|
||||
order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`,
|
||||
`getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new
|
||||
@@ -10548,7 +10636,9 @@ document. With no document open they fail with "no document open". `document.act
|
||||
the current one. `document.move {from?, to}` reorders open documents the way dragging a document tab along the tab strip
|
||||
does: `from` defaults to the current document, `to` is the destination index, documents between them shift by one, the
|
||||
current document stays current, and each document keeps its own view (#5663). It is an engine command, so headless and
|
||||
remote `command_list` both list it. `file.close {index}` on a document other than the current one leaves the current
|
||||
remote `command_list` both list it. `document.setSaved {index?, saved}` records a document as saved (`true`) or as
|
||||
having unsaved changes (`false`) without saving it and without an undo step; a script's `Document.saved = value` runs
|
||||
it. `file.close {index}` on a document other than the current one leaves the current
|
||||
document current, and its tool keeps its state; closing the current document makes the document in the next tab
|
||||
current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first,
|
||||
to ask whether to save it.
|
||||
|
||||
+1
-1
@@ -208,7 +208,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
|
||||
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
|
||||
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 |
|
||||
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
|
||||
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
|
||||
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
|
||||
|
||||
@@ -1130,6 +1130,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
|
||||
|
||||
Reference in new issue
Block a user