Merge main into feat/scripts-export-autocad

This commit is contained in:
dotCooCoo committed 2026-11-30 15:26:54 -08:00
commit 270ffca6ef
126 files changed
+8418 -666

No files matched your search

+188 -44
View File
@@ -50,7 +50,8 @@
//! - `Document.path` is a `Folder` for the folder of the document's file. A file saved or opened
//! under a relative path is in the process's working folder. 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
@@ -59,6 +60,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.
@@ -71,8 +75,8 @@ use vectorcraft_doc::Unit;
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
use super::{
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, command_value, current, doc_ref, get, given,
method, named, num, on_doc, property, returns, text, this_doc, typed, whole,
Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, class, command, current, doc_ref, get, given, method, named,
num, on_doc, property, returns, text, this_doc, typed, whole,
};
/// The most a scale factor of an export takes, in percent.
@@ -123,6 +127,76 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]),
("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]),
("SaveOptions", &["DONOTSAVECHANGES", "PROMPTTOSAVECHANGES", "SAVECHANGES"]),
// The enumerations of the options that keep their defaults (`Default::Member`).
("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]),
(
"CompressionQuality",
&[
"AUTOMATICJPEG2000HIGH",
"AUTOMATICJPEG2000LOSSLESS",
"AUTOMATICJPEG2000LOW",
"AUTOMATICJPEG2000MAXIMUM",
"AUTOMATICJPEG2000MEDIUM",
"AUTOMATICJPEG2000MINIMUM",
"AUTOMATICJPEGHIGH",
"AUTOMATICJPEGLOW",
"AUTOMATICJPEGMAXIMUM",
"AUTOMATICJPEGMEDIUM",
"AUTOMATICJPEGMINIMUM",
"JPEG2000HIGH",
"JPEG2000LOSSLESS",
"JPEG2000LOW",
"JPEG2000MAXIMUM",
"JPEG2000MEDIUM",
"JPEG2000MINIMUM",
"JPEGHIGH",
"JPEGLOW",
"JPEGMAXIMUM",
"JPEGMEDIUM",
"JPEGMINIMUM",
"None",
"ZIP4BIT",
"ZIP8BIT",
],
),
("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]),
(
"ColorDestination",
&[
"COLORDESTINATIONDOCCMYK",
"COLORDESTINATIONDOCRGB",
"COLORDESTINATIONPROFILE",
"COLORDESTINATIONWORKINGCMYK",
"COLORDESTINATIONWORKINGRGB",
"None",
],
),
("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]),
("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]),
("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]),
("PageMarksTypes", &["Japanese", "Roman"]),
(
"PDFChangesAllowedEnum",
&[
"CHANGE128ANYCHANGES",
"CHANGE128COMMENTING",
"CHANGE128EDITPAGE",
"CHANGE128FILLFORM",
"CHANGE128NONE",
"CHANGE40ANYCHANGES",
"CHANGE40COMMENTING",
"CHANGE40NONE",
"CHANGE40PAGELAYOUT",
],
),
("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]),
("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]),
("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]),
("SVGCSSPropertyLocation", &["ENTITIES", "PRESENTATIONATTRIBUTES", "STYLEATTRIBUTES", "STYLEELEMENTS"]),
("SVGDocumentEncoding", &["ASCII", "UTF16", "UTF8"]),
("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]),
("SVGFontSubsetting", &["ALLGLYPHS", "COMMONENGLISH", "COMMONROMAN", "GLYPHSUSED", "GLYPHSUSEDPLUSENGLISH", "GLYPHSUSEDPLUSROMAN", "None"]),
("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]),
];
/// Other names of enumeration members: `(enumeration, name, member)` makes `enumeration.name` the
@@ -803,9 +877,20 @@ fn exactly(h: &Host, f: impl FnOnce() -> Answer) -> Answer {
r
}
/// The path to give a command for the real path `real`.
fn plain(real: std::path::PathBuf) -> String {
crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()
/// Runs command `id` with `p` and writes each warning it gives to the console after `method`'s
/// name, as `app.documents.addDocument` does: what a save or an export leaves out of its file, or
/// a linked image an open could not read. → the command's answer.
fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
let (answer, value) = super::super::command_value(h, id, p)?;
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
}
Ok(answer)
}
/// The path to give a command for the real path `real`, or an error when it is not valid UTF-8.
fn plain(real: std::path::PathBuf) -> std::result::Result<String, HostError> {
crate::cmd::findfiles::plain(real).into_os_string().into_string().map_err(|_| HostError::Error("Script file path is not valid UTF-8".into()))
}
/// The built-in preset names scripts use that VectorCraft's built-in presets name otherwise, and the
@@ -838,7 +923,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());
@@ -860,23 +945,16 @@ 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)));
p.insert("path".into(), json!(plain(real)?));
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "saveAs", "file.saveAs", &Value::Object(p))))?;
Ok(Data::Undefined)
}
/// Runs command `id` as [`command`] does, and writes each warning its result gives to the console as
/// `method: warning`, as `addDocument` writes the warnings of `file.new`.
fn warned(h: &Host, method: &str, id: &str, p: &Value) -> Answer {
let (data, value) = command_value(h, id, p)?;
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
super::super::each_line(&format!("{method}: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
}
Ok(data)
}
/// `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 };
@@ -894,7 +972,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(),
@@ -903,6 +981,7 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
// An AutoCAD option left out takes its help page's default, not the DXF writer's.
Some(class) if class.name == AUTOCAD.name => options_params(class, &with_starts(class, o))?,
Some(class) => options_params(class, o)?,
None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())),
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
},
};
@@ -942,7 +1021,7 @@ 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)));
p.insert("path".into(), json!(plain(real)?));
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "exportFile", "document.export", &Value::Object(p))))?;
Ok(Data::Undefined)
}
@@ -952,11 +1031,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()));
@@ -987,8 +1066,13 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
}
}
}
if p.contains_key("cropTo") {
p.insert("editingData".into(), json!(false));
}
// The command opens the given path; a real path that is not valid UTF-8 is still refused.
let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
p.insert("path".into(), json!(plain(real)));
plain(real)?;
p.insert("path".into(), json!(plain(std::path::PathBuf::from(path))?));
let r = exactly(h, || warned(h, "open", "document.open", &Value::Object(p)))?;
let index = match &r {
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
@@ -1002,25 +1086,26 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
Ok(doc_ref(h, st.uid))
}
/// A document's file as the engine reads and writes it: a relative path is in the process's working
/// folder. It stays as it is when the working folder is not known.
fn absolute(path: &str) -> String {
let p = std::path::Path::new(path);
match std::env::current_dir() {
Ok(cwd) if p.is_relative() => cwd.join(p).to_string_lossy().into_owned(),
_ => path.to_string(),
}
}
/// The document's file ([`absolute`]), `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
/// 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<String>, HostError> {
match st.path.as_deref() {
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.map(absolute)),
_ => 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())
}
}
@@ -1060,6 +1145,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)
}
@@ -1074,31 +1162,87 @@ const UNSAVED_CHANGES: &str =
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
/// save would keep only some of its artboards.
const SAVES_SOME_ARTBOARDS: &str =
"the save would keep only some of its artboards: save it with saveAs first, or close with SaveOptions.DONOTSAVECHANGES";
/// Whether the file that saving `st` with its remembered options writes would omit artboards. A
/// PDF with `useArtboards: false` holds one page of the art's bounds. A native file, or a `.ai`
/// file other than a legacy version 7 one, with `separateArtboards` holds every artboard, and its
/// `range` names only the separate files. An EPS file embeds the whole document in its main file,
/// so its `artboardRange` never omits an artboard from what reopens.
fn picks_artboards(st: &crate::doc_state::DocState) -> bool {
if st.format == "eps" {
return false;
}
let options = Value::Object(crate::cmd::fileio::remembered_save_options(st));
let svg = matches!(st.format, "svg" | "svgz");
if svg && crate::cmd::fileio::svg_lost_artboards_warning(&st.doc, &options, st.format).is_some() {
return true;
}
if st.format == "pdf" && options.get("useArtboards") == Some(&Value::Bool(false)) {
return true;
}
let legacy = crate::cmd::fileio::saves_legacy_ai(st.format, &options);
if matches!(st.format, "vectorcraft" | "template" | "ai" | "ait") && options.get("separateArtboards") == Some(&Value::Bool(true)) && !legacy {
return false;
}
let count = st.doc.artboards.len();
// A `.ai` file other than a legacy one saves with `range` "all" (a `range` that isn't text is
// left for the save to refuse).
let modern_ai = matches!(st.format, "ai" | "ait") && !legacy;
let mut effective = options.clone();
if let (true, Value::Object(o)) = (modern_ai, &mut effective)
&& o.get("range").is_none_or(|r| r.is_string() || r.is_null())
{
o.insert("range".into(), json!("all"));
}
let resolved = serde_json::from_value::<crate::cmd::fileio::ArtboardPick>(effective).map_err(|e| e.to_string()).and_then(|p| p.resolve(count));
// Such a `.ai` file, and an SVG file that carries the native document, keep every artboard;
// a pick the save refuses still refuses (an SVG save with `useArtboards: false` reads no pick).
if modern_ai {
return resolved.is_err();
}
if svg && crate::cmd::fileio::svg_preserves_editing(&st.doc, &options) {
return options.get("useArtboards") != Some(&Value::Bool(false)) && resolved.is_err();
}
match resolved {
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
/// changes closes with any `SaveOptions`. With unsaved changes, `SaveOptions.DONOTSAVECHANGES`
/// closes it without them; `SaveOptions.SAVECHANGES` saves them to the document's file with
/// `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
/// for a document that has no file, a converted or recovered one included, 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",
};
let (dirty, file, format) =
super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format));
let (dirty, file, format, picked) =
super::with_doc(h, doc, |_, st| (st.is_dirty(), st.path.clone().filter(|_| !st.converted && !st.recovered), st.format, picks_artboards(st)));
if dirty {
match how {
"DONOTSAVECHANGES" => {}
"SAVECHANGES" => {
let path = absolute(&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()));
}
// A refusal names the document, as `fullName` does when the read roots hide its file.
let name = super::with_doc(h, doc, |_, st| st.title());
let real = h.disk.borrow().save_target(&path).map_err(|m| refused(m, &name))?;
let p = json!({"path": plain(real), "format": format});
let p = json!({"path": plain(real)?, "format": format});
exactly(h, || on_doc(h, doc.uid, false, |h| warned(h, "close", "file.saveAs", &p)))?;
}
_ => return Err(HostError::Error(UNSAVED_CHANGES.into())),
@@ -1132,7 +1276,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("Folder")),
("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")])),
])