mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
Scripts: tighten save, open and close edge cases
- saveAs picks the encoder from the requested name, so a link to a file of another format writes the format the name asks for. - fullName, path and close(SaveOptions.SAVECHANGES) resolve a relative saved path against the working directory. - close(SAVECHANGES) accepts an artboard range that covers every artboard and keeps the document open when the save would drop artboards. - app.open keeps the requested file name, rejects a file over 128 MiB before reading it, applies the requested color space to plug-in imports, and rejects PDF options for files that are not PDF content; null PDF options keep their defaults. - Explicit null options throw; assigning the current Document.saved value runs no command; Document.path reflects as Folder or string. - An implicit multi-file save names no refused path in its error. - The script checker counts SAVECHANGES only on SaveOptions and keeps write warnings for receivers that evaluated code can rebind.
This commit is contained in:
1 parent
eb41460cd5
commit
043650d794
13 files changed
+563
-47
No files matched your search
@@ -125,6 +125,7 @@ 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;
|
||||
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 +142,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
|
||||
|
||||
@@ -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,12 @@ pub(super) fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
source(p, "document.open")?
|
||||
}
|
||||
};
|
||||
if crate::file_access::in_script_command() && ["page", "cropTo"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
let pdf = 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);
|
||||
|
||||
@@ -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 {
|
||||
@@ -1076,7 +1077,9 @@ impl SaveJob {
|
||||
// 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())
|
||||
&& 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);
|
||||
}
|
||||
@@ -1240,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) })
|
||||
|
||||
@@ -172,7 +172,7 @@ 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(|| {
|
||||
|
||||
@@ -2751,9 +2751,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
["layers", "artboards", "pathItems", "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));
|
||||
|
||||
@@ -43,7 +43,8 @@
|
||||
//! - `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`. Setting `Document.saved` runs `document.setSaved`.
|
||||
//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`.
|
||||
//! Assigning its current value runs no command.
|
||||
//! - `Document.close` with unsaved changes closes without them with
|
||||
//! `SaveOptions.DONOTSAVECHANGES`, and saves them to the document's file first with
|
||||
//! `SaveOptions.SAVECHANGES`, which throws for a document that has no file (a converted or
|
||||
@@ -52,6 +53,9 @@
|
||||
//! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record:
|
||||
//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only. Any other property
|
||||
//! but `typename` and `parent` throws the same error, unless it is `undefined`.
|
||||
//! Page and crop options require PDF content, including PDF-compatible `.ai` and `.ait` files.
|
||||
//! Built-in file reads by script commands reject files over 8 MiB and cap the read at 8 MiB plus one byte.
|
||||
//! - Optional arguments use defaults when omitted or `undefined`; explicit `null` throws a type error.
|
||||
//! - `app.userInteractionLevel` starts at `UserInteractionLevel.DISPLAYALERTS` in each run. The
|
||||
//! commands a script runs never show a dialog, so the level does not change what they do, and it
|
||||
//! never allows a file the script's grants do not.
|
||||
@@ -696,7 +700,7 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let path = file_path(arg(a, 1), "saveAs")?;
|
||||
let mut p = Map::new();
|
||||
let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null));
|
||||
let given_options = given(arg(a, 2));
|
||||
// Without options, a path ending in `.ai`, `.eps` or `.pdf` takes the defaults a new options
|
||||
// object of that format's class holds.
|
||||
let extension = path.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase());
|
||||
@@ -718,6 +722,9 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
|
||||
} else if !q.is_empty() {
|
||||
p.insert("options".into(), Value::Object(q));
|
||||
}
|
||||
} else {
|
||||
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)));
|
||||
@@ -742,7 +749,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
let path = file_path(arg(a, 1), "exportFile")?;
|
||||
let kind = export_kind(arg(a, 2))?;
|
||||
// Without options, an export takes the defaults a new options object of its class holds.
|
||||
let mut p = match given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) {
|
||||
let mut p = match given(arg(a, 3)) {
|
||||
None => match kind.options {
|
||||
Some(class) => options_params(class, &fresh(class))?,
|
||||
None => Map::new(),
|
||||
@@ -784,11 +791,11 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
let path = file_path(arg(a, 1), "open")?;
|
||||
let mut p = Map::new();
|
||||
if let Some(d) = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null)) {
|
||||
if let Some(d) = given(arg(a, 2)) {
|
||||
let mode = if member(d, "DocumentColorSpace", &["CMYK", "RGB"], "documentColorSpace")? == "RGB" { "rgb" } else { "cmyk" };
|
||||
p.insert("colorMode".into(), json!(mode));
|
||||
}
|
||||
if let Some(o) = given(arg(a, 3)).filter(|d| !matches!(d, Data::Null)) {
|
||||
if let Some(o) = given(arg(a, 3)) {
|
||||
let Data::Object(items) = o else { return Err(HostError::Type("open's options must be a PDFFileOptions record".into())) };
|
||||
if typename(o).is_some_and(|t| t != "PDFFileOptions") {
|
||||
return Err(HostError::Type("open's options must be a PDFFileOptions record".into()));
|
||||
@@ -819,8 +826,11 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
}
|
||||
}
|
||||
let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(real)));
|
||||
if p.contains_key("cropTo") {
|
||||
p.insert("editingData".into(), json!(false));
|
||||
}
|
||||
h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))));
|
||||
let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?;
|
||||
let index = match &r {
|
||||
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
|
||||
@@ -837,12 +847,23 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
/// The document's file, `None` for a document that has none, or `Script file access denied` with
|
||||
/// the document's name when the automation read roots do not allow the file to be named
|
||||
/// ([`crate::file_access::check_read`]), as `app.getIsFileOpen` reads them.
|
||||
fn shown_file(st: &crate::DocState) -> std::result::Result<Option<&str>, HostError> {
|
||||
match st.path.as_deref() {
|
||||
fn shown_file(st: &crate::DocState) -> std::result::Result<Option<String>, HostError> {
|
||||
let path = st.path.as_deref().map(absolute_file).transpose()?;
|
||||
match path.as_deref() {
|
||||
Some(p) if crate::file_access::check_read(p).is_err() => {
|
||||
Err(HostError::Error(format!("{}: {}", super::super::files::ACCESS_DENIED, st.title())))
|
||||
}
|
||||
p => Ok(p),
|
||||
_ => Ok(path),
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute_file(path: &str) -> std::result::Result<String, HostError> {
|
||||
let path = std::path::Path::new(path);
|
||||
if path.is_absolute() {
|
||||
Ok(path.to_string_lossy().into_owned())
|
||||
} else {
|
||||
let cwd = std::env::current_dir().map_err(|e| HostError::Error(e.to_string()))?;
|
||||
Ok(cwd.join(path).to_string_lossy().into_owned())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,7 +873,7 @@ fn doc_full_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
super::with_doc(h, doc, |_, st| {
|
||||
Ok(match shown_file(st)? {
|
||||
Some(p) => vectorcraft_js::file_ref(p),
|
||||
Some(p) => vectorcraft_js::file_ref(&p),
|
||||
None => vectorcraft_js::file_ref(&st.title()),
|
||||
})
|
||||
})
|
||||
@@ -864,7 +885,7 @@ fn doc_path(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let folder = super::with_doc(h, doc, |_, st| {
|
||||
Ok(shown_file(st)?.and_then(|p| {
|
||||
let parent = std::path::Path::new(p).parent()?.to_string_lossy().into_owned();
|
||||
let parent = std::path::Path::new(&p).parent()?.to_string_lossy().into_owned();
|
||||
(!parent.is_empty()).then_some(parent)
|
||||
}))
|
||||
})?;
|
||||
@@ -882,6 +903,9 @@ fn doc_saved(h: &Host, a: &[Data]) -> Answer {
|
||||
fn doc_set_saved(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let saved = boolean(arg(a, 1), "Document.saved")?;
|
||||
if saved == super::with_doc(h, doc, |_, st| !st.is_dirty()) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
command(h, "document.setSaved", &json!({"index": doc.index, "saved": saved}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -897,19 +921,23 @@ const NO_FILE_TO_SAVE: &str =
|
||||
"the document has unsaved changes and no file to save them to: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
|
||||
|
||||
/// The error `close(SaveOptions.SAVECHANGES)` gives for a document with unsaved changes whose
|
||||
/// last save named some of its artboards: saving with those options again could leave changes out.
|
||||
/// save would keep only some of its artboards.
|
||||
const SAVES_SOME_ARTBOARDS: &str =
|
||||
"the document was last saved with some of its artboards named: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
|
||||
"the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
|
||||
|
||||
/// Whether the options `st` was last saved with name artboards (`artboard`, `artboards`, or a
|
||||
/// `range` other than all of them), so that a save with them may write only some of the artboards.
|
||||
/// Whether saving `st` with its remembered options would omit artboards.
|
||||
fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
|
||||
let options = crate::cmd::fileio::remembered_save_options(st);
|
||||
crate::cmd::fileio::ARTBOARD_PARAMS.iter().any(|k| match options.get(*k) {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::String(r)) if *k == "range" => !(r.trim().is_empty() || r.trim().eq_ignore_ascii_case("all")),
|
||||
Some(_) => true,
|
||||
})
|
||||
let options = Value::Object(crate::cmd::fileio::remembered_save_options(st));
|
||||
if matches!(st.format, "svg" | "svgz") && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() {
|
||||
return true;
|
||||
}
|
||||
let count = st.doc.artboards.len();
|
||||
let pick = serde_json::from_value::<crate::cmd::fileio::ArtboardPick>(options);
|
||||
match pick.map_err(|e| e.to_string()).and_then(|p| p.resolve(count)) {
|
||||
Ok(None) => false,
|
||||
Ok(Some(indices)) => (0..count).any(|i| !indices.contains(&i)),
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `document.close(saveOptions?)`: `file.close` of the document. A document without unsaved
|
||||
@@ -918,12 +946,12 @@ fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
|
||||
/// `file.saveAs` in the format the document was last saved in, after the write-access check `saveAs` makes of
|
||||
/// the path, and then closes it, and throws [`NO_FILE_TO_SAVE`]
|
||||
/// for a document that has no file, a converted or recovered one included, and
|
||||
/// [`SAVES_SOME_ARTBOARDS`] before writing when the document's last save named some of its artboards; and
|
||||
/// [`SAVES_SOME_ARTBOARDS`] before writing when the save would omit artboards; and
|
||||
/// `SaveOptions.PROMPTTOSAVECHANGES`, the default, throws [`UNSAVED_CHANGES`], since a script
|
||||
/// cannot show the prompt.
|
||||
fn doc_close(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let how = match given(arg(a, 1)).filter(|d| !matches!(d, Data::Null)) {
|
||||
let how = match given(arg(a, 1)) {
|
||||
Some(d) => member(d, "SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"], "saveOptions")?,
|
||||
None => "PROMPTTOSAVECHANGES",
|
||||
};
|
||||
@@ -933,7 +961,7 @@ fn doc_close(h: &Host, a: &[Data]) -> Answer {
|
||||
match how {
|
||||
"DONOTSAVECHANGES" => {}
|
||||
"SAVECHANGES" => {
|
||||
let path = file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?;
|
||||
let path = absolute_file(&file.ok_or_else(|| HostError::Error(NO_FILE_TO_SAVE.into()))?)?;
|
||||
if picked {
|
||||
return Err(HostError::Error(SAVES_SOME_ARTBOARDS.into()));
|
||||
}
|
||||
@@ -974,7 +1002,7 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
("saveAs", method(l, doc_save_as), returns("undefined", &[("saveIn", "File"), ("options", "*")])),
|
||||
("exportFile", method(l, doc_export_file), returns("undefined", &[("exportFile", "File"), ("exportFormat", "ExportType"), ("options", "*")])),
|
||||
("fullName", get(l, doc_full_name), typed("File")),
|
||||
("path", get(l, doc_path), typed("File")),
|
||||
("path", get(l, doc_path), typed("Folder|string")),
|
||||
("saved", property(l, doc_saved, doc_set_saved), typed("boolean")),
|
||||
("close", method(l, doc_close), returns("undefined", &[("saveOptions", "SaveOptions")])),
|
||||
])
|
||||
|
||||
@@ -93,6 +93,92 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_saved_paths_use_the_process_working_directory() {
|
||||
let cwd = crate::cmd::findfiles::plain(std::fs::canonicalize(std::env::current_dir().unwrap()).unwrap());
|
||||
let relative_base = PathBuf::from(format!("vc-script-relative-save-{}", std::process::id()));
|
||||
let base = cwd.join(&relative_base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let file = dir.join("relative.svg");
|
||||
let relative = file.strip_prefix(&cwd).unwrap();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("file.saveAs", &json!({"path": relative.to_string_lossy()})).unwrap();
|
||||
let before = std::fs::read(&file).unwrap();
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; Folder.current = new Folder({main}); var d = app.activeDocument;\n\
|
||||
vc.log([d.fullName.fsName === new File({file}).fsName, d.path.fsName === new Folder({dir}).fsName]);\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\
|
||||
d.close(SaveOptions.SAVECHANGES); vc.log(app.documents.length);",
|
||||
main = quoted(&base.join("main")),
|
||||
file = quoted(&file),
|
||||
dir = quoted(&dir),
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([[true, true], 0]));
|
||||
assert_ne!(std::fs::read(&file).unwrap(), before);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn save_as_uses_the_link_name_extension_for_the_encoder() {
|
||||
let base = folder("linkformat");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let target = dir.join("drawing.vectorcraft");
|
||||
std::fs::write(&target, b"").unwrap();
|
||||
std::os::unix::fs::symlink(&target, dir.join("drawing.svg")).unwrap();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&dir.join("drawing.svg"))));
|
||||
assert!(std::fs::read_to_string(&target).unwrap().contains("<svg"));
|
||||
assert_eq!(s.active().unwrap().format, "svg");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_as_template_preserves_the_document_file_and_saved_state() {
|
||||
let base = folder("templatecopy");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var d = app.documents.add(); d.saveAs(new File({dir} + '/drawing.svg'));\n\
|
||||
var original = d.fullName.fsName;\n\
|
||||
d.saveAs(new File({dir} + '/clean.vctemplate')); vc.log([d.fullName.fsName === original, d.saved]);\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\
|
||||
d.saveAs(new File({dir} + '/dirty.vctemplate')); vc.log([d.fullName.fsName === original, d.saved]);",
|
||||
dir = quoted(&dir),
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([[true, true], [true, false]]));
|
||||
assert!(dir.join("clean.vctemplate").is_file());
|
||||
assert!(dir.join("dirty.vctemplate").is_file());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn open_uses_the_requested_symlink_filename() {
|
||||
let base = folder("openlinkname");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let target = dir.join("drawing.vectorcraft");
|
||||
let link = dir.join("drawing.svg");
|
||||
std::fs::write(&target, b"<svg xmlns='http://www.w3.org/2000/svg' width='100' height='50'/>").unwrap();
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
let out = logged(&mut s, &base, &format!("Folder.userData; var d = app.open(new File({})); vc.log([d.name, d.fullName.name]);", quoted(&link)));
|
||||
assert_eq!(out, json!([["drawing.svg", "drawing.svg"]]));
|
||||
assert_eq!(s.active().unwrap().format, "svg");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Without options, a save or export writes what an untouched new options object of its class gives.
|
||||
#[test]
|
||||
fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
@@ -633,6 +719,121 @@ fn open_takes_the_page_and_crop_box_of_its_options() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_only_options_apply_to_an_editable_pdf() {
|
||||
let base = folder("pdfcroponly");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let pdf = dir.join("editable.pdf");
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
s.execute(
|
||||
"file.saveAs",
|
||||
&json!({"path": pdf.to_string_lossy(), "preserveEditing": true,
|
||||
"bleed": {"useDocument": false, "top": 10, "bottom": 10, "left": 10, "right": 10}}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(vectorcraft_pdf::editing(&std::fs::read(&pdf).unwrap()).is_some_and(|e| e.intact));
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&pdf)));
|
||||
let original = s.active().unwrap().doc.artboards[0].rect;
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pDFCropToBox: PDFBoxType.PDFMEDIABOX}});", quoted(&pdf)));
|
||||
let cropped = s.active().unwrap().doc.artboards[0].rect;
|
||||
assert!(cropped.width() > original.width() && cropped.height() > original.height());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_document_open_rejects_files_over_the_read_limit() {
|
||||
let base = folder("openreadlimit");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let file = dir.join("large.svg");
|
||||
std::fs::write(&file, b"<svg xmlns='http://www.w3.org/2000/svg' width='100' height='50'/>").unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file)));
|
||||
let count = s.documents().len();
|
||||
std::fs::OpenOptions::new().write(true).open(&file).unwrap().set_len(crate::cmd::fileio::SCRIPT_OPEN_MAX_BYTES as u64 + 1).unwrap();
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&file)));
|
||||
assert!(e.contains(crate::cmd::fileio::SCRIPT_OPEN_TOO_LARGE), "{e}");
|
||||
assert_eq!(s.documents().len(), count);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pdf_open_options_reject_other_detected_formats() {
|
||||
let base = folder("pdfoptionsformat");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let native = dir.join("native.pdf");
|
||||
s.execute("file.saveAs", &json!({"path": native.to_string_lossy(), "format": "vectorcraft"})).unwrap();
|
||||
let svg = dir.join("drawing.pdf");
|
||||
std::fs::write(&svg, b"<svg xmlns='http://www.w3.org/2000/svg' width='100' height='50'/>").unwrap();
|
||||
let count = s.documents().len();
|
||||
let uid = s.active().unwrap().uid;
|
||||
for file in [&native, &svg] {
|
||||
for options in ["{pageToOpen: 2}", "{pDFCropToBox: PDFBoxType.PDFMEDIABOX}"] {
|
||||
let script = format!("Folder.userData; app.open(new File({}), undefined, {options});", quoted(file));
|
||||
let e = failure(&mut s, &base, &script);
|
||||
assert!(e.contains("PDF open options require a PDF file"), "{e}");
|
||||
assert_eq!(s.documents().len(), count);
|
||||
assert_eq!(s.active().unwrap().uid, uid);
|
||||
}
|
||||
}
|
||||
let pdf = dir.join("actual.svg");
|
||||
s.execute("file.saveCopy", &json!({"path": pdf.to_string_lossy(), "format": "pdf"})).unwrap();
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({}), undefined, {{pageToOpen: 1}});", quoted(&pdf)));
|
||||
assert_eq!(s.documents().len(), count + 1);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_document_open_treats_null_pdf_options_as_omitted() {
|
||||
let base = folder("nullpdfdefaults");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
for extension in ["svg", "vectorcraft"] {
|
||||
let file = dir.join(format!("drawing.{extension}"));
|
||||
s.execute("file.saveAs", &json!({"path": file.to_string_lossy()})).unwrap();
|
||||
for options in ["page: null", "cropTo: null", "page: null, cropTo: null"] {
|
||||
let count = s.documents().len();
|
||||
logged(&mut s, &base, &format!("Folder.userData; vc.run('document.open', {{path: {}, {options}}});", quoted(&file)));
|
||||
assert_eq!(s.documents().len(), count + 1, "{extension}: {options}");
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 1);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_null_options_do_not_save_export_open_or_close() {
|
||||
let base = folder("nulloptions");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let file = dir.join("existing.svg");
|
||||
let original = b"<svg xmlns='http://www.w3.org/2000/svg' width='20' height='10'/>";
|
||||
std::fs::write(&file, original).unwrap();
|
||||
let f = format!("new File({})", quoted(&file));
|
||||
for call in [
|
||||
format!("app.activeDocument.saveAs({f}, null);"),
|
||||
format!("app.activeDocument.exportFile({f}, ExportType.SVG, null);"),
|
||||
format!("app.open({f}, null);"),
|
||||
format!("app.open({f}, undefined, null);"),
|
||||
"app.activeDocument.close(null);".into(),
|
||||
] {
|
||||
let e = failure(&mut s, &base, &format!("Folder.userData; {call}"));
|
||||
assert!(e.contains("TypeError"), "{call}: {e}");
|
||||
assert_eq!(std::fs::read(&file).unwrap(), original, "{call}");
|
||||
assert_eq!(s.documents().len(), 1, "{call}");
|
||||
assert!(!s.active().unwrap().is_dirty(), "{call}");
|
||||
}
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs({f}, undefined);"));
|
||||
assert_ne!(std::fs::read(&file).unwrap(), original);
|
||||
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(undefined);");
|
||||
assert!(s.documents().is_empty());
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `fullName` and `path` name the document's file and folder once it has one, `saved` follows its
|
||||
/// changes, and `close` with `SaveOptions.DONOTSAVECHANGES` closes it.
|
||||
#[test]
|
||||
@@ -765,6 +966,109 @@ fn closing_with_save_changes_refuses_a_save_of_some_artboards() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_with_save_changes_accepts_a_range_covering_all_current_artboards() {
|
||||
let base = folder("closefullrange");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
for (name, range, boards) in [("one", "1", 1), ("two", "1-2", 2)] {
|
||||
let file = dir.join(format!("{name}.pdf"));
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50, "artboards": boards})).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var d = app.activeDocument, o = new PDFSaveOptions(); o.artboardRange = '{range}';\n\
|
||||
d.saveAs(new File({}), o);",
|
||||
quoted(&file),
|
||||
),
|
||||
);
|
||||
let before = std::fs::read(&file).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"Folder.userData; vc.run('shape.rectangle', {x: 10, y: 10, width: 5, height: 5}); app.activeDocument.close(SaveOptions.SAVECHANGES);",
|
||||
);
|
||||
assert!(s.documents().is_empty());
|
||||
assert_ne!(std::fs::read(&file).unwrap(), before);
|
||||
}
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var o = new PDFSaveOptions(); o.artboardRange = '1'; app.activeDocument.saveAs(new File({}), o);\n\
|
||||
vc.run('artboard.new', {{x: 300, y: 0, width: 60, height: 80}});",
|
||||
quoted(&dir.join("grown.pdf")),
|
||||
),
|
||||
);
|
||||
let before = std::fs::read(dir.join("grown.pdf")).unwrap();
|
||||
let e = failure(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);");
|
||||
assert!(e.contains("some of its artboards"), "{e}");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
assert_eq!(std::fs::read(dir.join("grown.pdf")).unwrap(), before);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_with_save_changes_refuses_svg_artboard_loss_before_writing() {
|
||||
let base = folder("closesvgboards");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
for extension in ["svg", "svgz"] {
|
||||
for preserve in [false, true] {
|
||||
let file = dir.join(format!("drawing-{preserve}.{extension}"));
|
||||
let path = quoted(&file);
|
||||
let save = if preserve {
|
||||
format!("vc.run('file.saveAs', {{path: {path}, preserveEditing: true}});")
|
||||
} else {
|
||||
format!("d.saveAs(new File({path}));")
|
||||
};
|
||||
logged(&mut s, &base, &format!("Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 100, 50); {save}"));
|
||||
let before = std::fs::read(&file).unwrap();
|
||||
logged(&mut s, &base, "Folder.userData; vc.run('artboard.new', {x: 300, y: 0, width: 60, height: 80});");
|
||||
let uid = s.active().unwrap().uid;
|
||||
if preserve {
|
||||
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);");
|
||||
assert!(s.documents().is_empty());
|
||||
assert_ne!(std::fs::read(&file).unwrap(), before);
|
||||
logged(&mut s, &base, &format!("Folder.userData; app.open(new File({path}));"));
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 2);
|
||||
} else {
|
||||
let e = failure(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.SAVECHANGES);");
|
||||
assert!(e.contains("some of its artboards"), "{extension}: {e}");
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
assert_eq!(s.active().unwrap().uid, uid);
|
||||
assert_eq!(s.active().unwrap().doc.artboards.len(), 2);
|
||||
assert!(s.active().unwrap().is_dirty());
|
||||
assert_eq!(std::fs::read(&file).unwrap(), before);
|
||||
}
|
||||
logged(&mut s, &base, "Folder.userData; app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);");
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_reflection_describes_folders_and_unsaved_strings() {
|
||||
let base = folder("pathreflection");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var d = app.documents.add();\n\
|
||||
vc.log([d.reflect.find('path').dataType, d.path === '']);\n\
|
||||
d.saveAs(new File({})); vc.log([d.reflect.find('path').dataType, d.path instanceof Folder ? 'Folder' : typeof d.path]);\n\
|
||||
vc.log([d.path instanceof Folder, d.path.fsName]);",
|
||||
quoted(&dir.join("saved.svg")),
|
||||
),
|
||||
);
|
||||
assert_eq!(out, json!([["Folder|string", true], ["Folder|string", "Folder"], [true, dir.to_string_lossy()]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Setting `Document.saved` records the document's saved state without saving it: `true` lets
|
||||
/// `close()` close a document with edits, and `false` makes an untouched one ask.
|
||||
#[test]
|
||||
@@ -794,6 +1098,24 @@ fn setting_saved_records_the_saved_state() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_saved_assignments_do_not_record_commands() {
|
||||
let base = folder("savednoop");
|
||||
let mut s = session(&base);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
|
||||
d.saved = d.saved; d.saved = true; vc.log(d.saved);\n\
|
||||
d.saved = false; d.saved = d.saved; d.saved = false; vc.log(d.saved);\n\
|
||||
d.saved = true; d.saved = d.saved; vc.log(d.saved);",
|
||||
);
|
||||
assert_eq!(out, json!([true, false, true]));
|
||||
let changes: Vec<_> = s.journal.iter().filter(|(id, _)| id == "document.setSaved").map(|(_, p)| p["saved"].clone()).collect();
|
||||
assert_eq!(changes, [json!(false), json!(true)]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// With automation read roots that leave out the document's file, `fullName` and `path` throw
|
||||
/// instead of naming another file.
|
||||
#[test]
|
||||
@@ -831,6 +1153,35 @@ fn full_name_and_path_leave_out_a_file_outside_the_read_roots() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn implicit_multifile_save_redacts_preflight_refusals_before_writing() {
|
||||
let base = folder("savepreflight");
|
||||
let mut s = session(&base);
|
||||
let hidden = base.join("private-save-directory");
|
||||
std::fs::create_dir_all(&hidden).unwrap();
|
||||
let path = hidden.join("drawing.vectorcraft");
|
||||
s.execute("file.new", &json!({"artboards": 2})).unwrap();
|
||||
let saved = s.execute("document.save", &json!({"path": path.to_string_lossy(), "separateArtboards": true})).unwrap();
|
||||
let files: Vec<_> = saved["files"].as_array().unwrap().iter().map(|p| PathBuf::from(p.as_str().unwrap())).collect();
|
||||
assert!(files.len() > 1);
|
||||
let before: Vec<_> = files.iter().map(|p| std::fs::read(p).unwrap()).collect();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 5, "height": 5})).unwrap();
|
||||
let main = base.join("main");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&main], &[&main]).unwrap().unwrap();
|
||||
let e = crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({}))).unwrap_err().to_string();
|
||||
assert!(e.contains("automation path rejected"), "{e}");
|
||||
assert!(!e.contains("private-save-directory"), "{e}");
|
||||
assert!(!e.contains(path.to_string_lossy().as_ref()), "{e}");
|
||||
assert!(s.active().unwrap().is_dirty());
|
||||
for (file, bytes) in files.iter().zip(before) {
|
||||
assert_eq!(std::fs::read(file).unwrap(), bytes);
|
||||
}
|
||||
let explicit =
|
||||
crate::file_access::confine(Some(&roots), || s.execute("document.save", &json!({"path": path.to_string_lossy()}))).unwrap_err().to_string();
|
||||
assert!(explicit.contains(path.to_string_lossy().as_ref()), "{explicit}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A `pDFPreset` in square brackets names the built-in preset of the name inside them, and a name
|
||||
/// that is not a preset either way is refused.
|
||||
#[test]
|
||||
|
||||
@@ -88,6 +88,39 @@ 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_importer_adds_a_read_only_format_while_it_is_installed() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -1474,10 +1474,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` is declared in a function body this token is inside (`var name`, `function
|
||||
/// 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.iter().any(|s| s.saved.get(name).is_some_and(|v| v.local))
|
||||
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
|
||||
|
||||
@@ -208,7 +208,7 @@ 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 {
|
||||
if n == catalog::SAVE_CHANGES && of(catalog::SAVE_OPTIONS) {
|
||||
self.save_changes(line);
|
||||
}
|
||||
if n == catalog::ON_DRAW {
|
||||
@@ -283,6 +283,13 @@ 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);
|
||||
}
|
||||
}
|
||||
// `local['saveAs']`: what the object before the bracket defines, for a call that may follow.
|
||||
"[" => self.index_receiver = self.writer_bits(h0, h1),
|
||||
@@ -364,7 +371,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// 0 for anything else. A receiver the check does not follow may be a document.
|
||||
fn writer_bits(&self, receiver: Option<Sig<'s>>, before: Option<Sig<'s>>) -> u8 {
|
||||
match receiver {
|
||||
Some(r) if r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0),
|
||||
Some(r) if !self.unsure && r.kind == T::Ident && !member_mark(before) => self.writers.get(r.text).copied().unwrap_or(0),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
@@ -447,11 +454,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
if t.text.contains(catalog::ACTION_TEXT) {
|
||||
self.acc.feature(FeatureId::Actions, line);
|
||||
}
|
||||
// `SaveOptions['SAVECHANGES']`, or the value written as the string `"SaveOptions.SAVECHANGES"`.
|
||||
// The value written as the string `"SaveOptions.SAVECHANGES"`.
|
||||
let value = unquote(t.text, 32);
|
||||
if value == catalog::SAVE_CHANGES
|
||||
|| value.strip_prefix(catalog::SAVE_OPTIONS).and_then(|r| r.strip_prefix('.')) == Some(catalog::SAVE_CHANGES)
|
||||
{
|
||||
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, "==" | "===" | "!=" | "!=="));
|
||||
|
||||
@@ -573,6 +573,19 @@ 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.
|
||||
@@ -592,6 +605,24 @@ fn closing_with_save_changes_writes_a_file() {
|
||||
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]
|
||||
@@ -714,6 +745,27 @@ fn a_function_read_earlier_that_assigns_the_variable_keeps_save_as_writing() {
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7][..]));
|
||||
}
|
||||
|
||||
#[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.
|
||||
|
||||
+11
-4
@@ -3003,6 +3003,8 @@ other files through `$`:
|
||||
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
|
||||
themselves, such as a path's fill, 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/).
|
||||
@@ -3027,7 +3029,10 @@ other files through `$`:
|
||||
`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`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of
|
||||
`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"`.
|
||||
@@ -3059,13 +3064,15 @@ other files through `$`:
|
||||
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`. Setting `saved` runs `document.setSaved`: `true` records the document as saved
|
||||
`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. With unsaved changes, `close` closes without them with `SaveOptions.DONOTSAVECHANGES`;
|
||||
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
|
||||
its last save named some of its artboards, without writing anything; and
|
||||
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`.
|
||||
`SaveOptions.PROMPTTOSAVECHANGES`, the default, throws an error and leaves the document open, since a script cannot
|
||||
show the prompt. A bad value throws an error before anything is written.
|
||||
- `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type
|
||||
|
||||
Reference in new issue
Block a user