mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 15:21:17 -05:00
Scripts: saveAs takes its format from the script's file name
Document.saveAs without options picks the format from the name the script gave, before a symbolic link is resolved, and a name without a known extension keeps the document's format. A save that writes several files refuses a destination that is a folder before it writes any of them. imageCapture leaves out source paths outside the automation read roots before it probes them. The host and scriptcheck name test lists saveAs as a method, which it is now.
This commit is contained in:
@@ -1074,10 +1074,14 @@ impl SaveJob {
|
||||
// written. A refused file goes to `write` first, which refuses it with the error the
|
||||
// caller gives (naming the path as the caller does), so none of the files is written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if files.len() > 1
|
||||
&& let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err())
|
||||
{
|
||||
write(p, bytes)?;
|
||||
if files.len() > 1 {
|
||||
for (p, bytes) in &files {
|
||||
if super::may_write(p).is_err() {
|
||||
write(p, bytes)?;
|
||||
} else if std::path::Path::new(p).is_dir() {
|
||||
return Err(crate::EngineError::Other(format!("{p}: is a folder, not a file")));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, (p, bytes)) in files.iter().enumerate() {
|
||||
if i == 0 {
|
||||
@@ -1383,7 +1387,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; 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",
|
||||
"{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 or is a directory, 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)
|
||||
),
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -26,6 +26,7 @@
|
||||
//! `matte`, and on white without. `matteColor` is a record with `red`, `green` and `blue` from 0
|
||||
//! to 255. The file is written only where the script's `File` objects may write, and never over
|
||||
//! an open document's file or a file one of them links.
|
||||
//! Source paths outside the automation read roots are excluded before filesystem probes.
|
||||
//! - An image of more than 64 megapixels or 32,768 pixels a side throws an error before anything is
|
||||
//! drawn; the resolution is never lowered to make it fit.
|
||||
//! - `windowCapture` throws an error that says it is not available yet.
|
||||
@@ -295,7 +296,12 @@ fn sources_on_disk(h: &Host) -> Vec<Placed> {
|
||||
paths.extend(st.path.clone());
|
||||
paths.extend(crate::cmd::links::link_read_places(&st.doc, crate::cmd::links::LinkBase::of(st)));
|
||||
}
|
||||
paths.iter().filter_map(|p| placed(std::path::Path::new(p))).collect()
|
||||
paths.iter().filter_map(|p| source_place(p)).collect()
|
||||
}
|
||||
|
||||
fn source_place(path: &str) -> Option<Placed> {
|
||||
crate::file_access::check_read(path).ok()?;
|
||||
placed(std::path::Path::new(path))
|
||||
}
|
||||
|
||||
/// A file as its folder's real path and its name.
|
||||
@@ -495,3 +501,24 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod source_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn capture_sources_exclude_files_outside_automation_roots() {
|
||||
let dir = vectorcraft_testkit::TempDir::new("capture-source-roots");
|
||||
let allowed = dir.join("allowed");
|
||||
std::fs::create_dir(&allowed).unwrap();
|
||||
let inside = allowed.join("doc.vectorcraft");
|
||||
let outside = dir.join("linked.png");
|
||||
std::fs::write(&inside, b"document").unwrap();
|
||||
std::fs::write(&outside, b"linked").unwrap();
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&allowed], &[&allowed]).unwrap();
|
||||
crate::file_access::confine(roots.as_ref(), || {
|
||||
assert!(source_place(&inside.to_string_lossy()).is_some());
|
||||
assert!(source_place(&outside.to_string_lossy()).is_none());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,9 @@
|
||||
//! commands may use.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - `saveAs` without options saves in the format the path's extension names; it writes the file
|
||||
//! at the path as given. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
|
||||
//! - `saveAs` without options selects the format from the script's file name before resolving
|
||||
//! symbolic links. A name without a recognized extension uses the document's current format.
|
||||
//! Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
|
||||
//! `exportFile` as PNG24, JPEG or SVG use the defaults a new options object of that class holds.
|
||||
//! `exportFile` adds the format's extension unless the name already ends
|
||||
//! with it (`.png`, `.jpg` or `.jpeg`, `.gif`, `.tif` or `.tiff`, `.svg`, `.svgz`), and writes
|
||||
@@ -617,6 +618,10 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
p.insert("options".into(), Value::Object(q));
|
||||
}
|
||||
}
|
||||
if !p.contains_key("format") {
|
||||
let format = crate::cmd::fileio::format_for_name(path).map_or_else(|| super::with_doc(h, doc, |_, st| st.format), |f| f.id);
|
||||
p.insert("format".into(), json!(format));
|
||||
}
|
||||
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(real)));
|
||||
let r = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?;
|
||||
|
||||
@@ -10,6 +10,54 @@ use crate::*;
|
||||
|
||||
const DENIED: &str = "Script file access denied";
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_as_uses_the_scripts_extension_before_following_a_link() {
|
||||
let base = folder("save-link-format");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let target = dir.join("target.vectorcraft");
|
||||
let alias = dir.join("alias.svg");
|
||||
std::fs::write(&target, b"keep").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &alias).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&alias)));
|
||||
assert!(std::fs::read_to_string(&target).unwrap().contains("<svg"));
|
||||
assert_eq!(s.active().unwrap().format, "svg");
|
||||
let extensionless = dir.join("no-extension");
|
||||
std::os::unix::fs::symlink(&target, &extensionless).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&extensionless)));
|
||||
assert!(std::fs::read_to_string(&target).unwrap().contains("<svg"));
|
||||
assert_eq!(s.active().unwrap().format, "svg");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_rejects_directory_sidecars_before_replacing_the_main_file() {
|
||||
for (format, options) in [("vectorcraft", json!({"separateArtboards": true})), ("eps", json!({"useArtboards": true}))] {
|
||||
let base = folder(&format!("save-directory-{format}"));
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
let path = dir.join(format!("art.{format}"));
|
||||
let mut params = options;
|
||||
params["path"] = json!(path.to_string_lossy());
|
||||
params["format"] = json!(format);
|
||||
let saved = s.execute("file.saveAs", ¶ms).unwrap();
|
||||
let sidecar = PathBuf::from(saved["files"].as_array().unwrap().last().unwrap().as_str().unwrap());
|
||||
std::fs::remove_file(&sidecar).unwrap();
|
||||
std::fs::create_dir(&sidecar).unwrap();
|
||||
let marker = sidecar.join("keep");
|
||||
std::fs::write(&marker, b"sidecar").unwrap();
|
||||
std::fs::write(&path, b"main").unwrap();
|
||||
let e = s.execute("file.saveAs", ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains("is a folder, not a file"), "{e}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"main");
|
||||
assert_eq!(std::fs::read(&marker).unwrap(), b"sidecar");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fresh folder for test `name`, by its real path, with `main` for the script.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let base = std::env::temp_dir().join(format!("vc-script-save-{name}-{}", std::process::id()));
|
||||
|
||||
@@ -112,7 +112,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
|
||||
documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \
|
||||
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \
|
||||
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs selection selection= stories swatches swatches= \
|
||||
symbols symbols= tags textFrames toString typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
|
||||
+5
-2
@@ -3272,7 +3272,8 @@ through `$`:
|
||||
`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
|
||||
without options the name supplied by the script picks the format before symbolic links are resolved.
|
||||
A name without a recognized extension uses the document's current format. Without options, `saveAs` to a `.ai`, `.eps` or `.pdf` path and
|
||||
`exportFile` as `PNG24`, `JPEG` or `SVG` use the defaults a new options object of that class holds. `saveAs` maps `compressed`, `pdfCompatible`, `embedICCProfile` and
|
||||
`compatibility` (`ILLUSTRATOR17` and `ILLUSTRATOR19`) of `.ai`; `cmykPostScript`, `includeDocumentThumbnails`,
|
||||
`postScript`, `preview`, `overprint` and `compatibility` of EPS; and `pDFPreset`, `compatibility` (`ACROBAT4` to
|
||||
@@ -3337,7 +3338,7 @@ through `$`:
|
||||
opened for writing is checked, and a path that is an open document's file or a file one of them links throws an
|
||||
error, also when that file is missing. The linked files are every place opening the document looks for a link's
|
||||
file (its stored path, its relative path from the file the document was read from, and its name in those files' folders), with a DCS
|
||||
image's plate files beside each. Paths rejected by the document's path restrictions are excluded before filesystem
|
||||
image's plate files beside each. Paths rejected by the document's path restrictions or the automation read roots are excluded before filesystem
|
||||
probes. The documents count whether they were open when the run started or were
|
||||
opened while it was paused. A name that differs from it only in letter case throws the same error in a
|
||||
folder whose names ignore case, and in a folder where that cannot be told. An image of more than 64 megapixels or
|
||||
@@ -12094,6 +12095,8 @@ or in `options` (`file.formatOptions {format}` lists them with their values):
|
||||
- `separateArtboards: true` also writes each artboard of `range` (`"1-3, 5"`, default `"all"`) to
|
||||
`<name>-<artboard>.<ext>` beside the file: that artboard and the art touching it. The result's `files` lists every
|
||||
file written, the master file first (without a path: `files: [{name, dataBase64}]`). 3 artboards give 4 files.
|
||||
The save checks every destination before writing. If any destination is a directory or access is refused,
|
||||
it leaves every file unwritten. The same check applies to EPS saves that write multiple files.
|
||||
- `includeLinked: true` keeps linked images' own pixels in the file (they stay linked), not just the previews. Linked
|
||||
images in the art of the stored brushes count as those in the layers do, and an image key that the layers or a
|
||||
brush's art shows embedded keeps its pixels either way. A `version` older than the current one saves the placed
|
||||
|
||||
Reference in New Issue
Block a user