Scripts: fix print, save and export gaps found after merging main

- PrintJobOptions.file reads back as a File that can be assigned again.
- Document.saveAs picks the format from the supplied name before following
  a link, trims the trailing dots and spaces Windows ignores, and keeps the
  .ai, .eps and .pdf rule for a name that is only a dot and an extension.
- A save or export that writes several files refuses a target that is not
  a regular file before any file is written, with the usual path redaction.
- Document.saveAs, Document.exportFile and app.open send command warnings
  to the Script Console.
- fitToPage = false keeps a base tiling mode and clears only a base fit.
- The print scale factors take 1 to 1000 at assignment.
- File and Folder keep their state in native slots, so an object made from
  File.prototype with a path property is refused as before, and logging,
  localize() and toSource() still read their own properties.
- bitmapResolution declares a finite maximum, so its reflection matches.
- The two new script file messages are English only.
This commit is contained in:
dotCooCoo committed 2026-11-28 21:21:19 -08:00
1 parent 7182b8bf1c
commit a666185cc6
41 files changed
+543 -94

No files matched your search

+8
View File
@@ -267,6 +267,14 @@ pub(crate) fn may_write(path: &str) -> Result<()> {
crate::file_access::check_write(path).map_err(EngineError::Other)
}
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn regular_write_target(path: &str) -> Result<()> {
if std::fs::metadata(path).is_ok_and(|m| !m.is_file()) {
return Err(EngineError::Other(format!("{path}: not a file")));
}
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
may_read(path)?;
@@ -88,6 +88,7 @@ pub(super) fn write_encoded(path: Option<&str>, name: &str, doc: &vectorcraft_do
if files.len() > 1 {
for (p, _) in &files {
super::may_write(p)?;
super::access::regular_write_target(p)?;
}
}
for (p, bytes) in &files {
+12 -6
View File
@@ -85,6 +85,7 @@ pub struct SavePlan {
/// Where to write. `None` when no path is known (never saved, converted from an older version,
/// restored by Data Recovery, or a format other than the document's own): the caller asks for one or takes the bytes.
pub path: Option<String>,
pub path_given: bool,
pub format: &'static Format,
/// The format's options (only those its encoder reads).
pub options: Map<String, Value>,
@@ -348,7 +349,8 @@ pub fn save_plan(s: &Session, mode: SaveMode, p: &Value) -> Result<SavePlan> {
}
}
let lossy_source = super::lossy_source(st, p);
Ok(SavePlan { mode, path, format, options, name, folder, modified, notes, lossy_source, kept })
let path_given = str_param(p, "path").is_some_and(|g| !g.is_empty());
Ok(SavePlan { mode, path, path_given, format, options, name, folder, modified, notes, lossy_source, kept })
}
/// The native save options, which a save also takes beside the path.
@@ -1073,11 +1075,15 @@ impl SaveJob {
// Every path is checked against the file access in force before the first file is
// 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.
// A permitted target that is not a regular file then stops the save the same way.
#[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 {
if let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) {
write(p, bytes)?;
}
for (p, _) in &files {
super::access::regular_write_target(p).map_err(|e| if plan.path_given { e } else { super::access::naming_in_error(e, p) })?;
}
}
for (i, (p, bytes)) in files.iter().enumerate() {
if i == 0 {
@@ -1241,7 +1247,7 @@ 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 uid = s.doc()?.uid;
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
let given = job.plan.path_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) })
+1
View File
@@ -1185,6 +1185,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
let plan = SavePlan {
mode: SaveMode::Copy,
path: st.path.clone(),
path_given: false,
format: native,
options: serde_json::Map::from_iter([("pdfCompatible".into(), json!(false))]),
name: format!("{file}{DOC_EXT}"),
+15 -6
View File
@@ -30,6 +30,7 @@
//! - A property the help pages list that is not mapped accepts the default its help page gives
//! and throws an error that says it is not available yet at any other value.
//! - `fitToPage` set to true wins over the scale factors and the tiling mode.
//! With no scale or tiling assigned, false clears a base fit mode and preserves other base scaling modes.
//! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range
//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange`
//! replaces the range of the settings `print` starts from, which prints when those settings
@@ -241,7 +242,7 @@ const JOB: Class = Class {
name: "PrintJobOptions",
fields: &[
f("artboardRange", Kind::Text, Start::Text("1-")),
kept("bitmapResolution", Kind::Number(0.0, f64::MAX), Start::Num(0.0)),
kept("bitmapResolution", Kind::Number(0.0, 1_000_000_000.0), Start::Num(0.0)),
f("collate", Kind::Bool, Start::Bool(false)),
f("copies", Kind::Whole(1, 999), Start::Num(1.0)),
f(
@@ -286,11 +287,11 @@ const COORDINATE: Class = Class {
fields: &[
f("emulsion", Kind::Bool, Start::Bool(false)),
f("fitToPage", Kind::Bool, Start::Bool(false)),
f("horizontalScale", Kind::Number(1.0, 10_000.0), Start::Num(100.0)),
f("horizontalScale", Kind::Number(1.0, MAX_PRINT_SCALE), Start::Num(100.0)),
f("orientation", choice("PrintOrientation", PRINT_ORIENTATION, PRINT_ORIENTATION), Start::Member("PORTRAIT")),
f("position", choice("PrintPosition", PRINT_POSITION, PRINT_POSITION), Start::Member("TRANSLATECENTER")),
f("tiling", choice("PrintTiling", PRINT_TILING, PRINT_TILING), Start::Member("TILESINGLEFULLPAGE")),
f("verticalScale", Kind::Number(1.0, 10_000.0), Start::Num(100.0)),
f("verticalScale", Kind::Number(1.0, MAX_PRINT_SCALE), Start::Num(100.0)),
],
};
@@ -506,6 +507,7 @@ fn property(link: &Link, class: usize, field: usize) -> HostMember {
/// What a `PrintOptions` asks `file.print` for.
#[derive(Default)]
struct Job {
clear_fit: bool,
preset: Option<String>,
file: Option<Data>,
level: Option<u64>,
@@ -724,11 +726,12 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(
Some(t)
} else if scaled {
Some("custom")
} else if fit.is_some() || tiling.is_some() {
} else if tiling.is_some() {
Some("none")
} else {
None
};
job.clear_fit = fit == Some(false) && scaling.is_none();
if let Some(scaling) = scaling {
job.top.insert("scaling".into(), json!(scaling));
}
@@ -896,21 +899,27 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
/// name (any case) and a paper by its id or label. An empty name, or one with a path separator or
/// a control character, throws.
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
let (count, saved_ignore) = with_doc(h, doc, |_, st| {
let (count, saved_ignore, saved_fit) = with_doc(h, doc, |_, st| {
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
(st.doc.artboards.len(), mode == Some("ignore"))
let fit = st.doc.print_setup.as_ref().and_then(|v| v.get("scaling")).and_then(Value::as_str) == Some("fit");
(st.doc.artboards.len(), mode == Some("ignore"), fit)
});
if let Some(range) = &job.range {
vectorcraft_doc::range::parse_range(range, count).map_err(|e| HostError::Range(format!("PrintJobOptions.artboardRange: {e}")))?;
}
let s = h.session.borrow();
let mut base_ignore = saved_ignore;
let mut base_fit = saved_fit;
if let Some(name) = job.preset.take() {
let n = plain_name("PrintOptions.printPreset", "print preset", &name)?;
let preset = s.print_preset_settings(n).ok_or_else(|| no_such("PrintOptions.printPreset", "print preset", &name))?;
base_ignore = matches!(preset.artboards, vectorcraft_pdf::PrintArtboards::Ignore);
base_fit = matches!(preset.scaling, vectorcraft_pdf::PrintScaling::Fit);
job.preset = Some(n.to_string());
}
if job.clear_fit && base_fit {
job.top.insert("scaling".into(), json!("none"));
}
// An assigned `printArea` prints by artboard when the base settings ignore the artboards: the
// assigned `artboardRange` when there is one, otherwise every artboard.
if job.print_area && base_ignore && !job.top.contains_key("artboards") {
+69 -4
View File
@@ -31,6 +31,7 @@
//! `PDFSaveOptions` option still at a new object's default keeps the preset's value.
//! - `app.open(file, documentColorSpace?, options?)` takes `options` as a `PDFFileOptions` record:
//! an object with `pageToOpen` and `pDFCropToBox`, used for that call only.
//! - Each method sends command warnings to the Script Console with its name as the prefix.
//! - `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.
@@ -580,8 +581,8 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
let given_options = given(arg(a, 2)).filter(|d| !matches!(d, Data::Null));
// 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());
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == extension.as_deref()).map(|(c, _)| fresh(c));
let named_format = save_format_for_name(path, cfg!(windows)).map(|f| f.id);
let by_extension = SAVE_CLASSES.iter().find(|(_, f)| Some(*f) == named_format).map(|(c, _)| fresh(c));
if let Some(o) = given_options.or(by_extension.as_ref()) {
let name = typename(o);
let Some((class, format)) = SAVE_CLASSES.iter().find(|(c, _)| Some(c.name) == name) else {
@@ -595,12 +596,30 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer {
p.insert("options".into(), Value::Object(q));
}
}
if !p.contains_key("format") {
let format = named_format.unwrap_or_else(|| super::with_doc(h, doc, |_, st| st.format));
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)));
exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?;
let result = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "file.saveAs", &Value::Object(p))))?;
report_warnings(h, "Document.saveAs", &result);
Ok(Data::Undefined)
}
fn save_format_for_name(path: &str, windows: bool) -> Option<&'static crate::cmd::fileio::Format> {
let name = if windows { path.rsplit(['/', '\\']).next() } else { path.rsplit('/').next() }.unwrap_or(path);
let name = if windows { name.trim_end_matches(['.', ' ']) } else { name };
// A name that is only a dot and an extension, such as `.pdf`, picks its format only for the
// `.ai`, `.eps` and `.pdf` options classes; any other name takes the usual extension rule.
match name.rsplit_once('.') {
Some(("", extension)) if SAVE_CLASSES.iter().any(|(_, f)| extension.eq_ignore_ascii_case(f)) => {
crate::cmd::fileio::format_for_name(&format!("x.{extension}"))
}
_ => crate::cmd::fileio::format_for_name(name),
}
}
/// `path` with the extension of `kind` added, unless its name already ends with one of them.
fn with_extension(path: &str, kind: &ExportKind, svgz: bool) -> String {
let extensions: &[&str] = if svgz { &["svgz"] } else { kind.extensions };
@@ -651,7 +670,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
let named = with_extension(path, &kind, svgz);
let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?;
p.insert("path".into(), json!(plain(real)));
exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?;
let result = exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?;
report_warnings(h, "Document.exportFile", &result);
Ok(Data::Undefined)
}
@@ -693,6 +713,7 @@ 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)));
let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?;
report_warnings(h, "app.open", &r);
let index = match &r {
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()),
@@ -705,6 +726,20 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
Ok(doc_ref(h, st.uid))
}
fn report_warnings(h: &Host, method: &str, result: &Data) {
let warnings = match result {
Data::Object(fields) => fields.iter().find(|(k, _)| k == "warnings").map(|(_, v)| v),
_ => None,
};
if let Some(Data::Array(warnings)) = warnings {
for warning in warnings.iter().take(super::MAX_LISTED) {
if let Data::String(warning) = warning {
super::super::each_line(&format!("{method}: {warning}"), |line, cut| h.line(super::super::console::Entry::Output(line), cut));
}
}
}
}
fn app_interaction(h: &Host, _: &[Data]) -> Answer {
Ok(text(if h.dom.save_options.quiet.get() { QUIET } else { DISPLAY }))
}
@@ -745,3 +780,33 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
})
.collect()
}
#[cfg(test)]
mod save_format_tests {
use super::save_format_for_name;
#[test]
fn save_as_selects_the_format_from_windows_filename_aliases() {
for extension in ["svg", "svgz", "ai", "eps", "pdf"] {
for suffix in [".", " ", ". . ", "..."] {
for prefix in ["", "/exports/", "C:\\exports\\"] {
let name = format!("{prefix}drawing.{}{suffix}", extension.to_ascii_uppercase());
assert_eq!(save_format_for_name(&name, true).map(|f| f.id), Some(extension), "{name}");
assert!(save_format_for_name(&name, false).is_none(), "{name}");
}
}
}
for name in ["drawing", "drawing. . ", "drawing.svg\t", "drawing.svg\u{a0}", "folder.svg/drawing", "folder.svg\\drawing"] {
assert!(save_format_for_name(name, true).is_none(), "{name}");
}
assert_eq!(save_format_for_name("proof\\.svg", false).map(|f| f.id), Some("svg"));
for windows in [false, true] {
assert_eq!(save_format_for_name(".pdf", windows).map(|f| f.id), Some("pdf"));
assert!(save_format_for_name(".svg", windows).is_none());
assert!(save_format_for_name("/exports/.png", windows).is_none());
assert_eq!(save_format_for_name("/exports/.eps", windows).map(|f| f.id), Some("eps"));
assert_eq!(save_format_for_name("drawing.svg", windows).map(|f| f.id), Some("svg"));
assert_eq!(save_format_for_name("drawing.svgz", windows).map(|f| f.id), Some("svgz"));
}
}
}
+44
View File
@@ -133,6 +133,50 @@ fn pathless_save_rejection_hides_document_folder() {
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn multi_file_save_directory_errors_hide_paths_the_caller_did_not_give() {
use crate::file_access::{AutomationRoots, confine};
let d = dir("multi-file-directory-error");
let (inside, outside) = (d.join("in"), d.join("kept-out"));
for folder in [&inside, &outside] {
std::fs::create_dir_all(folder).unwrap();
}
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
let own = path(&outside, "doc.vectorcraft");
let saved = s.execute("document.save", &json!({"path": own, "separateArtboards": true})).unwrap();
let files: Vec<String> = saved["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
assert!(files.len() > 1, "{saved}");
let primary = std::fs::read(&own).unwrap();
rect(&mut s);
let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap();
let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap();
for target in [&files[0], &files[1]] {
let original = std::fs::read(target).unwrap();
std::fs::remove_file(target).unwrap();
std::fs::create_dir(target).unwrap();
let name = std::path::Path::new(target).file_name().unwrap().to_string_lossy();
for (roots, params, shown) in [
(&write_only, json!({"separateArtboards": true}), name.as_ref()),
(&write_only, json!({"path": null, "separateArtboards": true}), name.as_ref()),
(&write_only, json!({"path": own, "separateArtboards": true}), target.as_str()),
(&both, json!({"separateArtboards": true}), target.as_str()),
] {
let error = confine(roots.as_ref(), || s.execute("document.save", &params)).unwrap_err().to_string();
assert_eq!(error, format!("{shown}: not a file"), "{params}");
assert!(std::path::Path::new(target).is_dir());
if target != &own {
assert_eq!(std::fs::read(&own).unwrap(), primary);
}
assert!(s.doc().unwrap().is_dirty());
}
std::fs::remove_dir(target).unwrap();
std::fs::write(target, original).unwrap();
}
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn an_svg_path_writes_svg_and_save_writes_it_back() {
let d = dir("svg");
+91 -6
View File
@@ -135,6 +135,92 @@ fn print_without_a_file_does_not_print() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_print_job_file_can_be_read_and_assigned_to_another_job() {
let base = folder("file-getter");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let path = dir.join("proof 100%.pdf");
let out = logged(
&mut s,
&base,
&format!(
"Folder.userData; var first = new PrintJobOptions(), second = new PrintJobOptions();
first.file = new File({}); second.file = first.file;
vc.log([second.file instanceof File, second.file.fsName === first.file.fsName]);
var o = new PrintOptions(); o.jobOptions = second; app.activeDocument.print(o);",
quoted(&path)
),
);
assert_eq!(out[0], json!([true, true]));
assert!(!pages(&path).is_empty());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn print_scale_assignment_and_reflection_share_the_supported_range() {
let base = folder("scale-range");
let mut s = session(&base);
let out = logged(
&mut s,
&base,
"var c = new PrintCoordinateOptions();
var names = ['horizontalScale', 'verticalScale'];
for (var i = 0; i < names.length; i++) {
var name = names[i], info = c.reflect.find(name);
c[name] = info.max;
try { c[name] = info.max + 0.01; vc.log('accepted'); }
catch (e) { vc.log([e.name, c[name] === info.max, info.max === 1000]); }
}",
);
assert_eq!(out, json!([["RangeError", true, true], ["RangeError", true, true]]));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn disabling_fit_preserves_other_base_scaling_modes() {
let base = folder("fit-false");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let boxes = |path: &Path| {
let mut boxes = Vec::new();
vectorcraft_pdf::import(&std::fs::read(path).unwrap()).unwrap().walk(|node| {
if let Some(bounds) = node.path_data().and_then(|p| p.bounds()) {
boxes.push(bounds);
}
});
boxes
};
for mode in ["tileFull", "tileImageable", "custom", "fit"] {
let settings = json!({"scaling": mode, "scale": {"width": 500, "height": 500}});
s.execute("print.setup", &json!({"settings": settings})).unwrap();
s.execute("print.presets.save", &json!({"name": "Base", "settings": settings})).unwrap();
let override_settings = if mode == "fit" { json!({"scaling": "none"}) } else { json!({}) };
let want = s.execute("file.print", &json!({"settings": override_settings, "path": dir.join("want.pdf").to_string_lossy()})).unwrap();
for preset in [false, true] {
if preset {
s.execute("print.setup", &json!({"settings": {"scaling": "none"}})).unwrap();
}
let out = dir.join(format!("{mode}-{preset}.pdf"));
let select = if preset { "o.printPreset = 'Base';" } else { "" };
logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({});
{select} o.coordinateOptions.fitToPage = false; app.activeDocument.print(o);",
quoted(&out)
),
);
let expected = boxes(&dir.join("want.pdf"));
assert!(!expected.is_empty());
assert_eq!(boxes(&out), expected, "{mode}, preset: {preset}");
assert_eq!(pages(&out).len() as u64, want["pages"].as_u64().unwrap());
}
}
let _ = std::fs::remove_dir_all(base);
}
/// Bad values throw when they are assigned, and nothing prints.
#[test]
fn print_options_refuse_bad_values() {
@@ -149,8 +235,10 @@ fn print_options_refuse_bad_values() {
("j.collate = 1;", "TypeError", "collate must be true or false"),
("c.horizontalScale = NaN;", "TypeError", "horizontalScale"),
("c.horizontalScale = Infinity;", "TypeError", "horizontalScale"),
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 10000"),
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 10000"),
("c.verticalScale = 20000;", "RangeError", "verticalScale must be from 1 to 1000"),
("c.verticalScale = 0;", "RangeError", "verticalScale must be from 1 to 1000"),
("c.horizontalScale = 1000.01;", "RangeError", "horizontalScale must be from 1 to 1000"),
("c.verticalScale = 1000.01;", "RangeError", "verticalScale must be from 1 to 1000"),
("m.trimMarksWeight = -1;", "RangeError", "trimMarksWeight must be from 0"),
("c.orientation = 'PrintOrientation.SIDEWAYS';", "TypeError", "orientation must be a PrintOrientation value"),
("c.orientation = 'PrintTiling.TILEFULLPAGES';", "TypeError", "orientation must be a PrintOrientation value"),
@@ -194,10 +282,7 @@ fn options_that_are_not_available_throw() {
("o.paperOptions.offset = 10;", "PrintPaperOptions.offset is not available yet"),
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL1;", "PSLEVEL1 is not available yet"),
("o.postScriptOptions.binaryPrinting = true;", "PrintPostScriptOptions.binaryPrinting is not available yet"),
(
&format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"),
"horizontalScale above 1000 is not available yet",
),
(&format!("{file} o.coordinateOptions.horizontalScale = 2000; app.activeDocument.print(o);"), "horizontalScale must be from 1 to 1000"),
];
let prefix = "Folder.userData; var o = new PrintOptions(), j = o.jobOptions;";
for (case, part) in cases {
+131
View File
@@ -93,6 +93,120 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() {
let _ = std::fs::remove_dir_all(base);
}
#[cfg(unix)]
#[test]
fn save_as_selects_the_format_before_resolving_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();
for extension in ["svg", "svgz"] {
let target = dir.join(format!("{extension}.vectorcraft"));
let link = dir.join(format!("drawing.{extension}"));
std::fs::write(&target, "original").unwrap();
std::os::unix::fs::symlink(&target, &link).unwrap();
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&link)));
let bytes = std::fs::read(&target).unwrap();
if extension == "svgz" {
assert!(bytes.starts_with(&[0x1f, 0x8b]));
} else {
assert!(String::from_utf8(bytes).unwrap().contains("<svg"));
}
}
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let link = dir.join("drawing");
std::fs::write(dir.join("target.svg"), "original").unwrap();
std::os::unix::fs::symlink(dir.join("target.svg"), &link).unwrap();
logged(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&link)));
assert_eq!(s.active().unwrap().format, "vectorcraft");
assert!(dir.join("target.svg").is_file());
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn svg_sidecar_directories_are_refused_before_any_output_changes() {
let base = folder("svg-directory");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let pic = base.join("outside/pic.png");
std::fs::write(&pic, super::links::png(2, 2, [10, 200, 30])).unwrap();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("file.place", &json!({"path": pic.to_string_lossy(), "link": false})).unwrap();
let svg = dir.join("a.svg");
let export = format!("app.activeDocument.exportFile(new File({}), ExportType.SVG);", quoted(&svg));
logged(&mut s, &base, &format!("Folder.userData; {export}"));
s.execute("file.saveAs", &json!({"path": svg.to_string_lossy(), "format": "svg", "images": "link"})).unwrap();
let images: Vec<PathBuf> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != svg).collect();
assert_eq!(images.len(), 1);
let image = &images[0];
std::fs::remove_file(image).unwrap();
std::fs::create_dir(image).unwrap();
for save in [false, true] {
std::fs::write(&svg, "original SVG").unwrap();
let call = if save { format!("app.activeDocument.saveAs(new File({}));", quoted(&svg)) } else { export.clone() };
let error = failure(&mut s, &base, &format!("Folder.userData; {call}"));
assert!(error.contains("not a file"), "{call}: {error}");
assert_eq!(std::fs::read_to_string(&svg).unwrap(), "original SVG");
assert!(image.is_dir());
}
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn save_export_and_open_report_command_warnings_in_the_console() {
let base = folder("command-warnings");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
logged(
&mut s,
&base,
"app.documents.add(DocumentColorSpace.RGB, 100, 100);
vc.run('shape.rectangle', {x: 10, y: 10, width: 50, height: 50});
vc.run('transparency.set', {opacity: 0.5}); app.activeDocument.pageItems[0].name = 'bad\\u0001name';",
);
for (command, format, method, call) in [
("file.saveAs", "eps", "Document.saveAs", "app.activeDocument.saveAs(f);"),
("document.export", "svg", "Document.exportFile", "app.activeDocument.exportFile(f, ExportType.SVG);"),
] {
let path = dir.join(format!("warnings.{format}"));
let want = s.execute(command, &json!({"path": path.to_string_lossy(), "format": format})).unwrap();
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("{method}: {}", w.as_str().unwrap())).collect();
assert!(!warnings.is_empty(), "{command}: {want}");
let report = run(&mut s, &base, &format!("Folder.userData; var f = new File({}); {call}", quoted(&path))).unwrap();
assert_eq!(report["console"]["lines"], json!(warnings));
}
let svg = dir.join("missing-image.svg");
std::fs::write(&svg, "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'><image href='missing.png' width='50' height='50'/></svg>")
.unwrap();
let want = s.execute("document.open", &json!({"path": svg.to_string_lossy()})).unwrap();
let warnings: Vec<String> = want["warnings"].as_array().unwrap().iter().map(|w| format!("app.open: {}", w.as_str().unwrap())).collect();
assert!(!warnings.is_empty(), "{want}");
let report = run(&mut s, &base, &format!("Folder.userData; app.open(new File({}));", quoted(&svg))).unwrap();
assert_eq!(report["console"]["lines"], json!(warnings));
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_multi_file_save_refuses_a_directory_before_replacing_the_primary_file() {
let base = folder("save-directory");
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("drawing.vectorcraft");
let saved = s.execute("file.saveAs", &json!({"path": path.to_string_lossy(), "format": "vectorcraft", "separateArtboards": true})).unwrap();
let files = saved["files"].as_array().unwrap();
assert!(files.len() > 1, "{saved}");
let primary = std::fs::read(&path).unwrap();
let sidecar = files.iter().map(|v| PathBuf::from(v.as_str().unwrap())).find(|p| *p != path).unwrap();
std::fs::remove_file(&sidecar).unwrap();
std::fs::create_dir(&sidecar).unwrap();
let error = failure(&mut s, &base, &format!("Folder.userData; app.activeDocument.saveAs(new File({}));", quoted(&path)));
assert!(error.contains("not a file"), "{error}");
assert_eq!(std::fs::read(&path).unwrap(), primary);
assert!(sidecar.is_dir());
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() {
@@ -496,6 +610,23 @@ fn bad_arguments_are_refused_with_an_error() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn logging_files_and_folders_reads_only_enumerable_own_properties() {
let base = folder("log-file-folder");
let mut s = session(&base);
let text = "var f = new File('kept.svg'), d = new Folder('kept');\n\
vc.log(f); vc.log(d); vc.log([f, {folder: d}]);\n\
File.prototype.inherited = 'omit'; Folder.prototype.inherited = 'omit';\n\
Object.defineProperty(f, 'hidden', {value: 'omit', enumerable: false});\n\
Object.defineProperty(d, 'hidden', {value: 'omit', enumerable: false});\n\
f.label = 'drawing'; d.count = 2;\n\
vc.log(f); vc.log(d); vc.log([f, {folder: d}]);";
let log = logged(&mut s, &base, text);
let nested = json!([{"label": "drawing"}, {"folder": {"count": 2}}]);
assert_eq!(log, json!([{}, {}, [{}, {"folder": {}}], {"label": "drawing"}, {"count": 2}, nested]));
let _ = std::fs::remove_dir_all(base);
}
/// Only a `File` the `File` class made names a file. An object made from `File.prototype` and a
/// plain object throw a `TypeError`, and a `File` whose hidden path property a script set keeps its
/// own path, so nothing is written or opened at the path the script put there.
+55 -4
View File
@@ -103,7 +103,7 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> {
/// The text of the localization object `id` for the current locale: the string value of the first
/// of [`Localization::keys`] that the object has as its own data property. No getter runs.
pub(crate) fn localized_text(interp: &mut Interp, id: ObjId) -> JsResult<Option<Value>> {
if !matches!(interp.object(id)?.class, Class::Ordinary) {
if !matches!(interp.object(id)?.class, Class::Ordinary | Class::File(_)) {
return Ok(None);
}
for k in interp.localization.keys() {
@@ -293,11 +293,13 @@ impl Source {
Some(Err(*length))
}
Class::Array { .. } => return Err(interp.type_error(NOT_PLAIN_ARRAY)),
Class::Ordinary if has_symbols => return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source")),
Class::Ordinary if o.proto == Some(object_proto) && enumerable => {
Class::Ordinary | Class::File(_) if has_symbols => {
return Err(interp.type_error("toSource: an object with a Symbol property cannot be written as source"));
}
Class::Ordinary | Class::File(_) if o.proto == Some(object_proto) && enumerable => {
Some(Ok(o.props.iter().map(|(k, p)| (k.clone(), p.clone())).collect::<Vec<_>>()))
}
Class::Ordinary => return Err(interp.type_error(NOT_PLAIN_OBJECT)),
Class::Ordinary | Class::File(_) => return Err(interp.type_error(NOT_PLAIN_OBJECT)),
_ => None,
};
let fixed = shape.as_ref().and(fixed_state(o));
@@ -451,3 +453,52 @@ fn function_name(code: &Code) -> String {
None => "[anonymous]".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::heap::{OPEN, PropMap};
use crate::interp::Abrupt;
fn source_error(interp: &mut Interp, id: ObjId) -> String {
let Err(Abrupt::Throw(error)) = write_source(interp, Value::Object(id)) else { panic!("expected a source error") };
let Value::String(message) = interp.get_value(&error, &key("message")).unwrap() else { panic!("expected an error message") };
message.to_rust_string()
}
#[test]
fn to_source_uses_ordinary_properties_and_guards_for_files() {
for file in [false, true] {
let mut interp = Interp::new(crate::Options { es2015: true, ..crate::Options::default() }, crate::Limits::default());
let class = if file {
let mut slots = PropMap::default();
slots.insert(key("__vcPath"), Value::str("native path"));
Class::File(Box::new(slots))
} else {
Class::Ordinary
};
let mut object = Object::new(class, Some(interp.intrinsics.object_proto));
object.props.insert(key("label"), Prop::Data { value: Value::str("public"), flags: OPEN });
let id = interp.heap.alloc_object(object);
let Value::String(source) = write_source(&mut interp, Value::Object(id)).unwrap() else { panic!("expected source text") };
assert_eq!(source.to_rust_string(), r#"({"label":"public"})"#);
interp.object_mut(id).unwrap().props.insert(key("__vcPath"), Prop::Data { value: Value::str("own path"), flags: OPEN });
let Value::String(source) = write_source(&mut interp, Value::Object(id)).unwrap() else { panic!("expected source text") };
assert_eq!(source.to_rust_string(), r#"({"label":"public", "__vcPath":"own path"})"#);
interp.object_mut(id).unwrap().proto = None;
assert_eq!(source_error(&mut interp, id), NOT_PLAIN_OBJECT);
interp.object_mut(id).unwrap().proto = Some(interp.intrinsics.object_proto);
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: 0 });
assert_eq!(source_error(&mut interp, id), NOT_PLAIN_OBJECT);
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: crate::heap::ENUMERABLE });
assert_eq!(source_error(&mut interp, id), FIXED_PROPERTY);
interp.object_mut(id).unwrap().props.insert(key("hidden"), Prop::Data { value: Value::Bool(true), flags: OPEN });
interp.object_mut(id).unwrap().extensible = false;
assert_eq!(source_error(&mut interp, id), NOT_EXTENSIBLE);
interp.object_mut(id).unwrap().extensible = true;
let symbol = interp.well_known(|w| &w.iterator).unwrap();
interp.define_sym(id, symbol, Prop::Data { value: Value::Bool(true), flags: OPEN }).unwrap();
assert_eq!(source_error(&mut interp, id), "toSource: an object with a Symbol property cannot be written as source");
}
}
}
+1 -1
View File
@@ -282,7 +282,7 @@ impl Interp {
self.constructing = was;
let v = v?;
if let Value::Object(o) = &v
&& matches!(self.object(*o)?.class, Class::Ordinary)
&& matches!(self.object(*o)?.class, Class::Ordinary | Class::File(_))
&& let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))?
{
self.object_mut(*o)?.proto = Some(proto);
+99 -11
View File
@@ -8,7 +8,7 @@
//! 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
//! and its line feed in native slots; 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`.
//!
@@ -79,15 +79,18 @@ fn message(i: &mut Interp, name: &str) -> JsResult<Value> {
/// so that a property a script put on `Object.prototype` is not read as part of it.
fn field(i: &mut Interp, v: &Value, name: &str) -> JsResult<Value> {
match v.as_object() {
Some(o) => slot(i, o, name),
Some(o) => Ok(match i.get_own_property(o, &key(name))? {
Some(Prop::Data { value, .. }) => value,
_ => Value::Undefined,
}),
None => Ok(Value::Undefined),
}
}
/// The value of the own data property `name` of `o`, `undefined` when it has none.
/// The native slot `name` of `o`, or `undefined` when it has none.
fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
Ok(match i.get_own_property(o, &key(name))? {
Some(Prop::Data { value, .. }) => value,
Ok(match &i.object(o)?.class {
Class::File(fields) => fields.get(&key(name)).cloned().unwrap_or(Value::Undefined),
_ => Value::Undefined,
})
}
@@ -106,10 +109,19 @@ pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
}
fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> {
if let Value::String(s) = &value {
i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES + string_bytes(s.len())))?;
}
i.define(o, key(name), Prop::Data { value, flags: HIDDEN })
let Class::File(fields) = &i.object(o)?.class else {
return Err(Abrupt::Internal("File slot on an object without native storage".into()));
};
let name = key(name);
let added = if fields.contains(&name) { 0 } else { PROP_BYTES + string_bytes(name.len()) };
i.rooted(&[Value::Object(o), value.clone()], |i| {
i.reserve_heap(added)?;
if let Class::File(fields) = &mut i.object_mut(o)?.class {
fields.insert(name, value);
i.heap.bytes = i.heap.bytes.saturating_add(added);
}
Ok(())
})
}
/// The object `this` and its path, or a `TypeError` naming `what` when it is not a `File` or
@@ -181,8 +193,10 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult<Valu
fn instance(i: &mut Interp, proto: ObjId, fs: Value) -> JsResult<Value> {
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)));
let storage = std::mem::size_of::<crate::heap::PropMap<Value>>();
i.reserve_heap(OBJECT_BYTES + storage + 6 * PROP_BYTES)?;
let o = i.heap.alloc_object(Object::new(Class::File(Box::default()), Some(proto)));
i.heap.bytes = i.heap.bytes.saturating_add(storage);
i.rooted(&[Value::Object(o)], |i| {
set_slot(i, o, PATH, fs.clone())?;
set_slot(i, o, ERROR, Value::str(""))?;
@@ -290,6 +304,11 @@ fn count(i: &mut Interp, v: &Value, what: &str) -> JsResult<Option<f64>> {
// ---- constructors ----
pub(crate) fn from_path(i: &mut Interp, path: Value) -> JsResult<Value> {
let proto = classes(i)?.file_proto;
i.rooted(std::slice::from_ref(&path), |i| instance(i, proto, path.clone()))
}
fn file_ctor(i: &mut Interp, _: Value, args: &[Value], construct: bool) -> JsResult<Value> {
make(i, args, construct, true)
}
@@ -1363,6 +1382,75 @@ mod tests {
assert_eq!(v.unwrap(), JsValue::String("x,/x,2,d/b,1".into()));
}
#[test]
fn files_and_folders_localize_their_own_locale_properties() {
let mut r = realm();
r.add_script_extensions().unwrap();
r.localization().set_locale("fr_FR");
r.localization().set_enabled(true);
let source = "var results = []; var constructors = [File, Folder];
for (var n = 0; n < constructors.length; n++) {
var C = constructors[n], f = new C('x'), hit = false;
C.prototype.fr = 'inherited';
results.push(localize(f) === f);
f.en = 'English %1';
Object.defineProperty(f, 'fr_FR', {get: function () { hit = true; return 'getter'; }, configurable: true});
results.push(localize(f, 'text') === 'English text', !hit);
f.fr = 'French %1';
results.push(localize(f, 'text') === 'French text');
results.push(Object.prototype.toString.call(f) === 'French %1');
delete C.prototype.fr;
}
results.every(function (v) { return v; })";
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
}
#[test]
fn files_and_folders_copy_only_ordinary_own_properties() {
let mut r = realm();
let copy = HostItem::Function(Rc::new(|a: Vec<Data>| Ok(a.into_iter().next().unwrap_or(Data::Undefined))));
r.define_host_object("host", vec![("copy".into(), copy)]).unwrap();
let source = "var results = []; var constructors = [File, Folder];
for (var n = 0; n < constructors.length; n++) {
var C = constructors[n], f = new C('x');
results.push(Object.getOwnPropertyNames(f).length === 0, Object.keys(f).length === 0);
results.push(JSON.stringify(f) === '{}', typeof f === 'object', f instanceof C);
results.push(Object.prototype.toString.call(f) === '[object Object]');
f.label = 'public'; f.child = {values: [1, true]}; f.__vcPath = 'ordinary property';
var plain = {label: 'public', child: {values: [1, true]}, __vcPath: 'ordinary property'};
results.push(JSON.stringify(f) === JSON.stringify(plain));
results.push(Object.keys(f).join() === Object.keys(plain).join());
results.push(Object.getOwnPropertyNames(f).join() === Object.getOwnPropertyNames(plain).join());
results.push(f.fsName === '/x', f.__vcPath === 'ordinary property', f.__vcHandle === undefined);
var cloned = host.copy(f);
results.push(JSON.stringify(cloned) === JSON.stringify(plain), cloned !== f, cloned.child !== f.child);
results.push(Object.getPrototypeOf(cloned) === Object.prototype);
}
results.every(function (v) { return v; })";
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
}
#[test]
fn a_host_constructor_assigns_its_prototype_to_a_returned_file() {
let mut r = realm();
let make = Rc::new(|_: Vec<Data>| Ok(Data::Object(vec![(crate::FILE_REF_KEY.into(), Data::String("/x".into()))])));
let copy = Rc::new(|a: Vec<Data>| Ok(a.get(1).cloned().unwrap_or(Data::Undefined)));
let class = crate::HostClass {
name: "ReturnedFile".into(),
parent: None,
members: vec![("copy".into(), crate::HostMember::Method(copy))],
info: Vec::new(),
index: None,
construct: Some(make),
};
r.define_host_classes(vec![class], Vec::new()).unwrap();
let source = "var f = new ReturnedFile(); f.own = 'kept'; var d = new Folder('x'); d.own = 'folder';
f instanceof ReturnedFile && Object.getPrototypeOf(f) === ReturnedFile.prototype &&
Object.keys(f).join() === 'own' && JSON.stringify(f) === '{\"own\":\"kept\"}' &&
JSON.stringify(f.copy(f)) === '{\"own\":\"kept\"}' && JSON.stringify(f.copy(d)) === '{\"own\":\"folder\"}'";
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
}
#[test]
fn the_constructor_picks_the_class_only_without_new() {
let mut r = realm();
+3 -2
View File
@@ -272,6 +272,7 @@ pub(crate) enum Class {
Xmp(Box<crate::xmp::Meta>),
/// An object the `XMPFile` constructor made ([`crate::xmp_classes`]).
XmpFile(Box<PropMap<Value>>),
File(Box<PropMap<Value>>),
/// An object of a class a host defined ([`crate::host_classes`]).
Host(crate::host_classes::HostObj),
/// A `UnitValue` object and its measurement ([`crate::unit_value`]).
@@ -578,7 +579,7 @@ impl Class {
Class::XmlList(_) => "XMLList",
Class::Namespace(_) => "Namespace",
Class::QName { .. } => "QName",
Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::PromiseRecord(_) => "Object",
Class::XmlFilter(_) | Class::Xmp(_) | Class::XmpFile(_) | Class::File(_) | Class::PromiseRecord(_) => "Object",
Class::Promise(_) => "Promise",
Class::Math => "Math",
Class::Json => "JSON",
@@ -1187,7 +1188,7 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
extra = VIEW_BYTES;
}
Class::Xmp(meta) => extra = meta.heap_bytes(),
Class::XmpFile(fields) => {
Class::XmpFile(fields) | Class::File(fields) => {
for (name, value) in fields.iter() {
strings.add_key(name);
mark_value(value, work, strings);
+5 -1
View File
@@ -282,7 +282,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::File(_) => {
let o = self.object(id)?;
if o.props.len() > r.limits.entries {
return Err(self.data_error(r, ErrorType::Range, "has too many entries"));
@@ -385,6 +385,10 @@ impl Interp {
Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, _)] if k == crate::HOST_REF_KEY) => {
self.write_host_ref(&Data::Object(items))?
}
Data::Object(items) if self.write_hosted && matches!(items.as_slice(), [(k, Data::String(_))] if k == crate::FILE_REF_KEY) => {
let path = self.write_data(items.into_iter().next().map_or(Data::Undefined, |(_, v)| v), depth + 1, false)?;
crate::file_classes::from_path(self, path)?
}
Data::Object(items) => self.write_container(items.into_iter().map(|(k, d)| (Slot::Name(k), d)).collect(), false, depth, frozen)?,
})
}
-2
View File
@@ -6647,8 +6647,6 @@ liquify-list-end {0}, {1} {0} i {1}
@msg Script file could not be written No s’ha pogut escriure el fitxer de l’script
@msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui
@msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi
@msg Script file is read-only El fitxer de l’script és només de lectura
@msg Script file is open for writing El fitxer de l’script està obert per escriure-hi
@msg Script file name is already in use El nom del fitxer de l’script ja està en ús
@msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta
@msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer
Can't render this file because it is too large.
-2
View File
@@ -5429,8 +5429,6 @@ liquify-list-end {0}, {1} {0} a {1}
@msg Script file could not be written Soubor skriptu nelze zapsat
@msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví
@msg Script file is not open for writing Soubor skriptu není otevřený pro zápis
@msg Script file is read-only Soubor skriptu je jen pro čtení
@msg Script file is open for writing Soubor skriptu je otevřený pro zápis
@msg Script file name is already in use Název souboru skriptu se už používá
@msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky
@msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru
Can't render this file because it is too large.
-2
View File
@@ -88,8 +88,6 @@
@msg Script file could not be written Scriptfilen kunne ikke skrives
@msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person
@msg Script file is not open for writing Scriptfilen er ikke åben for skrivning
@msg Script file is read-only Scriptfilen er skrivebeskyttet
@msg Script file is open for writing Scriptfilen er åben for skrivning
@msg Script file name is already in use Scriptfilens navn er allerede i brug
@msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe
@msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil
Can't render this file because it is too large.
-2
View File
@@ -5006,8 +5006,6 @@ liquify-list-end {0}, {1} {0} und {1}
@msg Script file could not be written Skriptdatei konnte nicht geschrieben werden
@msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet
@msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet
@msg Script file is read-only Skriptdatei ist schreibgeschützt
@msg Script file is open for writing Skriptdatei ist zum Schreiben geöffnet
@msg Script file name is already in use Name der Skriptdatei wird bereits verwendet
@msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein
@msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird
Can't render this file because it is too large.
-2
View File
@@ -2838,8 +2838,6 @@ liquify-list-end {0}, {1} {0} και {1}
@msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου
@msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει
@msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή
@msg Script file is read-only Το αρχείο του σεναρίου είναι μόνο για ανάγνωση
@msg Script file is open for writing Το αρχείο του σεναρίου είναι ανοιχτό για εγγραφή
@msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη
@msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο
@msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο
Can't render this file because it is too large.
-2
View File
@@ -5116,8 +5116,6 @@ liquify-list-end {0}, {1} {0}, {1}
@msg Script file could not be written No se pudo escribir el archivo del script
@msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda
@msg Script file is not open for writing El archivo del script no está abierto para escritura
@msg Script file is read-only El archivo del script es de solo lectura
@msg Script file is open for writing El archivo del script está abierto para escritura
@msg Script file name is already in use El nombre del archivo del script ya está en uso
@msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta
@msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo
Can't render this file because it is too large.
-2
View File
@@ -5359,8 +5359,6 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa
@msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö
@msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten
@msg Script file is read-only Komentosarjan tiedosto on vain luku -tilassa
@msg Script file is open for writing Komentosarjan tiedosto on auki kirjoittamista varten
@msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä
@msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota
@msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle
Can't render this file because it is too large.
-2
View File
@@ -5073,8 +5073,6 @@ liquify-list-end {0}, {1} {0} et {1}
@msg Script file could not be written Le fichier du script n’a pas pu être écrit
@msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre
@msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture
@msg Script file is read-only Le fichier du script est en lecture seule
@msg Script file is open for writing Le fichier du script est ouvert en écriture
@msg Script file name is already in use Le nom du fichier du script est déjà utilisé
@msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier
@msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier
Can't render this file because it is too large.
-2
View File
@@ -7850,8 +7850,6 @@ liquify-list-end {0}, {1} {0} और {1}
@msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी
@msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है
@msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है
@msg Script file is read-only स्क्रिप्ट फ़ाइल केवल पढ़ने के लिए है
@msg Script file is open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली है
@msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है
@msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए
@msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है
Can't render this file because it is too large.
-2
View File
@@ -5951,8 +5951,6 @@ liquify-list-end {0}, {1} {0} és {1}
@msg Script file could not be written A parancsfájl fájlját nem sikerült írni
@msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia
@msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva
@msg Script file is read-only A parancsfájl fájlja csak olvasható
@msg Script file is open for writing A parancsfájl fájlja írásra meg van nyitva
@msg Script file name is already in use A parancsfájl fájljának neve már használatban van
@msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen
@msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg
Can't render this file because it is too large.
-2
View File
@@ -8913,8 +8913,6 @@ breakText Glyphs Glif
@msg Script file could not be written File skrip tidak dapat ditulis
@msg Script file dialogs need a person to answer them Dialog file skrip memerlukan orang untuk menjawabnya
@msg Script file is not open for writing File skrip tidak dibuka untuk ditulis
@msg Script file is read-only File skrip hanya dapat dibaca
@msg Script file is open for writing File skrip sedang dibuka untuk ditulis
@msg Script file name is already in use Nama file skrip sudah digunakan
@msg Script file name must be a name without a folder Nama file skrip harus berupa nama tanpa folder
@msg Script file permission can be kept only for a script run from a file Izin file skrip hanya dapat disimpan untuk skrip yang dijalankan dari file
Can't render this file because it is too large.
-2
View File
@@ -5144,8 +5144,6 @@ liquify-list-end {0}, {1} {0} e {1}
@msg Script file could not be written Impossibile scrivere il file dello script
@msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda
@msg Script file is not open for writing Il file dello script non è aperto in scrittura
@msg Script file is read-only Il file dello script è di sola lettura
@msg Script file is open for writing Il file dello script è aperto in scrittura
@msg Script file name is already in use Il nome del file dello script è già in uso
@msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella
@msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file
Can't render this file because it is too large.
-2
View File
@@ -5980,8 +5980,6 @@ liquify-list-end {0}, {1} {0}、{1}
@msg Script file could not be written スクリプトのファイルを書き込めませんでした
@msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です
@msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません
@msg Script file is read-only スクリプトのファイルは読み取り専用です
@msg Script file is open for writing スクリプトのファイルが書き込み用に開かれています
@msg Script file name is already in use スクリプトのファイル名はすでに使用されています
@msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください
@msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです
Can't render this file because it is too large.
-2
View File
@@ -8653,8 +8653,6 @@ liquify-list-end {0}, {1} {0} და {1}
@msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა
@msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს
@msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის
@msg Script file is read-only სკრიპტის ფაილი მხოლოდ წასაკითხია
@msg Script file is open for writing სკრიპტის ფაილი ჩასაწერად გახსნილია
@msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება
@msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე
@msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის
Can't render this file because it is too large.
-2
View File
@@ -5909,8 +5909,6 @@ liquify-list-end {0}, {1} {0} 및 {1}
@msg Script file could not be written 스크립트 파일을 쓸 수 없습니다
@msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다
@msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다
@msg Script file is read-only 스크립트 파일이 읽기 전용입니다
@msg Script file is open for writing 스크립트 파일이 쓰기용으로 열려 있습니다
@msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다
@msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다
@msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다
Can't render this file because it is too large.
-2
View File
@@ -90,8 +90,6 @@
@msg Script file could not be written Het scriptbestand kon niet worden geschreven
@msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord
@msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven
@msg Script file is read-only Het scriptbestand is alleen-lezen
@msg Script file is open for writing Het scriptbestand is geopend voor schrijven
@msg Script file name is already in use De naam van het scriptbestand is al in gebruik
@msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn
@msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd
Can't render this file because it is too large.
-2
View File
@@ -5246,8 +5246,6 @@ liquify-list-end {0}, {1} {0} i {1}
@msg Script file could not be written Nie można zapisać pliku skryptu
@msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie
@msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu
@msg Script file is read-only Plik skryptu jest tylko do odczytu
@msg Script file is open for writing Plik skryptu jest otwarty do zapisu
@msg Script file name is already in use Nazwa pliku skryptu jest już używana
@msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu
@msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku
Can't render this file because it is too large.
-2
View File
@@ -6291,8 +6291,6 @@ liquify-list-end {0}, {1} {0} e {1}
@msg Script file could not be written Não foi possível gravar o arquivo do script
@msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las
@msg Script file is not open for writing O arquivo do script não está aberto para gravação
@msg Script file is read-only O arquivo do script é somente leitura
@msg Script file is open for writing O arquivo do script está aberto para gravação
@msg Script file name is already in use O nome do arquivo do script já está em uso
@msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta
@msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo
Can't render this file because it is too large.
-2
View File
@@ -5141,8 +5141,6 @@ liquify-list-end {0}, {1} {0} и {1}
@msg Script file could not be written Не удалось записать файл скрипта
@msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек
@msg Script file is not open for writing Файл скрипта не открыт для записи
@msg Script file is read-only Файл скрипта доступен только для чтения
@msg Script file is open for writing Файл скрипта открыт для записи
@msg Script file name is already in use Имя файла скрипта уже используется
@msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки
@msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла
Can't render this file because it is too large.
-2
View File
@@ -5014,8 +5014,6 @@ liquify-list-end {0}, {1} {0} och {1}
@msg Script file could not be written Skriptets fil kunde inte skrivas
@msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem
@msg Script file is not open for writing Skriptets fil är inte öppen för skrivning
@msg Script file is read-only Skriptets fil är skrivskyddad
@msg Script file is open for writing Skriptets fil är öppen för skrivning
@msg Script file name is already in use Namnet på skriptets fil används redan
@msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp
@msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil
Can't render this file because it is too large.
-2
View File
@@ -4842,8 +4842,6 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg Script file could not be written Betiğin dosyası yazılamadı
@msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir
@msg Script file is not open for writing Betiğin dosyası yazmak için açık değil
@msg Script file is read-only Betiğin dosyası salt okunur
@msg Script file is open for writing Betiğin dosyası yazmak için açık
@msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor
@msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır
@msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir
Can't render this file because it is too large.
-2
View File
@@ -5128,8 +5128,6 @@ liquify-list-end {0}, {1} {0} і {1}
@msg Script file could not be written Не вдалося записати файл скрипту
@msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина
@msg Script file is not open for writing Файл скрипту не відкрито для запису
@msg Script file is read-only Файл скрипту доступний лише для читання
@msg Script file is open for writing Файл скрипту відкрито для запису
@msg Script file name is already in use Ім’я файлу скрипту вже використовується
@msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки
@msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу
Can't render this file because it is too large.
-2
View File
@@ -5641,8 +5641,6 @@ liquify-list-end {0}, {1} {0} và {1}
@msg Script file could not be written Không thể ghi tệp của tập lệnh
@msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời
@msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi
@msg Script file is read-only Tệp của tập lệnh ở chế độ chỉ đọc
@msg Script file is open for writing Tệp của tập lệnh đang được mở để ghi
@msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng
@msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục
@msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp
Can't render this file because it is too large.
-2
View File
@@ -5636,8 +5636,6 @@ liquify-list-end {0}, {1} {0}和{1}
@msg Script file could not be written 无法写入脚本的文件
@msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答
@msg Script file is not open for writing 脚本的文件未以写入方式打开
@msg Script file is read-only 脚本的文件为只读
@msg Script file is open for writing 脚本的文件已以写入方式打开
@msg Script file name is already in use 脚本的文件名已被使用
@msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称
@msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限
Can't render this file because it is too large.
-2
View File
@@ -2977,8 +2977,6 @@ liquify-list-end {0}, {1} {0}和{1}
@msg Script file could not be written 無法寫入指令碼的檔案
@msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應
@msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟
@msg Script file is read-only 指令碼的檔案為唯讀
@msg Script file is open for writing 指令碼的檔案已以寫入方式開啟
@msg Script file name is already in use 指令碼的檔案名稱已在使用中
@msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱
@msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限
Can't render this file because it is too large.
+7 -3
View File
@@ -3004,6 +3004,8 @@ other files through `$`:
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.
`Document.exportFile(file, exportType, options?)` runs `document.export` and leaves the document's file as it is.
Each method sends command warnings to the Script Console with its name as the prefix: `Document.saveAs: `,
`Document.exportFile: ` or `app.open: `. Without options, `saveAs` selects the format from the supplied name before following a link.
`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
@@ -3073,14 +3075,16 @@ other files through `$`:
from, which prints when those settings print a range. `print` starts from the preset's settings when `printPreset`
is assigned, otherwise from the document's saved settings. When those settings ignore the artboards, an assigned
`printArea` prints the artboards an assigned `artboardRange` names, or each artboard without a range. With one of
`horizontalScale` and `verticalScale` assigned, the other keeps its value in the settings `print` starts from. `print` throws before anything is written when an assigned `artboardRange` names an
`horizontalScale` and `verticalScale` assigned, the other keeps its value in the settings `print` starts from.
With no scale or tiling assigned, `fitToPage = false` clears a base fit mode and preserves other base scaling modes.
`print` throws before anything is written when an assigned `artboardRange` names an
artboard the document does not have, also with `printAllArtboards` true, when `printPreset` or `flattenerPreset`
is not a preset's name (any case), when `colorManagementOptions.name` is not an RGB or CMYK profile's name (any
case), when `paperOptions.name` is not a paper `file.print` knows, or when it names a paper other than `custom`
and `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, or holds `/`, `\` or
a control character (also at either end), throws too, and each checked name is sent without the spaces around it. `printerName` and `PPDName` take only `""`. A listed option that is not mapped, or a value that is not mapped such as
`PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION`, `PSLEVEL1` or a scale above 1000, throws an error that says it
is not available yet. Each value is checked when it is assigned: a wrong type, a number that is not finite or is
`PrintingBounds.ARTWORKBOUNDS`, `INRIPSEPARATION` or `PSLEVEL1`, throws an error that says it
is not available yet. Print scale factors must be from 1 to 1000 percent. Each value is checked when it is assigned: a wrong type, a number that is not finite or is
out of range, a string longer than 4,096 bytes, an option object of the wrong class or from an earlier run, and a
path given as a string all throw. A run makes at most 256 option objects. Each warning `file.print` gives goes to
the Script Console as a line that starts with `Document.print: `. `vc.run` still cannot run `file.print` or
+1
View File
@@ -0,0 +1 @@
Scripts return usable File objects from print job options, select Save As formats before resolving links, and report save, export, and open warnings in the Script Console. Saves and exports reject generated targets that already name directories before writing any output. Print options preserve base tiling when fitToPage is false and validate scale factors from 1 to 1000 percent at assignment. New message keys use English fallback text.