Merge pull request #9060 from dotCooCoo/feat/scripts-api-d10-print-options

Scripts: Document.print prints to a file with PrintOptions and its option classes
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-05 06:52:50 -08:00
commit 7aefbb8cee
9 files changed
+63 -32

No files matched your search

+6 -14
View File
@@ -283,20 +283,6 @@ pub(crate) const SCRIPT_OPEN_MAX_BYTES: usize = vectorcraft_plugins::import::MAX
#[cfg(not(target_arch = "wasm32"))]
pub(crate) const SCRIPT_OPEN_TOO_LARGE: &str = "file exceeds 128 MiB";
#[cfg(all(test, not(target_arch = "wasm32")))]
thread_local! {
/// The paths [`read_file`] has read on this thread, in order.
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
#[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(())
}
thread_local! {
static READ_LIMIT: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}
@@ -314,6 +300,12 @@ pub(crate) fn with_read_limit<T>(max: usize, f: impl FnOnce() -> T) -> T {
f()
}
#[cfg(all(test, not(target_arch = "wasm32")))]
thread_local! {
/// The paths [`read_file`] has read on this thread, in order.
pub(crate) static FILES_READ: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_file(path: &str) -> Result<Vec<u8>> {
use std::io::Read;
+22 -1
View File
@@ -135,6 +135,27 @@ pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) {
}
}
/// Whether `\` separates folders in a path: on Windows and on the web, where paths may come from
/// Windows. On other platforms `\` is a character of a file name.
const BACKSLASH_SEPARATES: bool = cfg!(any(windows, target_arch = "wasm32"));
/// The length of `path`'s folder part, its last separator included.
fn dir_len(path: &str, backslash: bool) -> usize {
let at = if backslash { path.rfind(['/', '\\']) } else { path.rfind('/') };
at.map_or(0, |i| i + 1)
}
#[cfg(test)]
mod dir_tests {
#[test]
fn a_backslash_is_part_of_a_file_name_where_it_does_not_separate_folders() {
assert_eq!(super::dir_len("out/a\\b.svg", false), 4, "the file a\\b.svg is in out/");
assert_eq!(super::dir_len("a\\b.svg", false), 0);
assert_eq!(super::dir_len("out\\a\\b.svg", true), 6);
assert_eq!(super::dir_len("b.svg", true), 0);
}
}
impl Encoded {
pub(super) fn one(bytes: Vec<u8>) -> Self {
Self { files: vec![(None, bytes)], ..Self::default() }
@@ -180,7 +201,7 @@ impl Encoded {
/// under their own names, then the image maps as `{image stem}.html` or `.map`.
pub fn named<'a>(&'a self, doc: &Document, path: &str) -> Vec<(String, Cow<'a, [u8]>)> {
// Siblings keep the path's own separators (this runs on every platform and on the web).
let dir = &path[..path.rfind(['/', '\\']).map_or(0, |i| i + 1)];
let dir = &path[..dir_len(path, BACKSLASH_SEPARATES)];
let sibling = |name: &str| format!("{dir}{name}");
let mut out: Vec<(String, Cow<[u8]>)> = match self.files.as_slice() {
[(_, bytes)] => vec![(path.to_string(), Cow::Borrowed(bytes.as_slice()))],
+7 -9
View File
@@ -1086,17 +1086,15 @@ impl SaveJob {
return Ok(stopped);
}
// Every path is checked against the file access in force, and as a write target, before
// the first file is written. A refused file is not handed to `write`, so a writer that does
// not check the file access writes none of the files; the error is the file access's own
// refusal, as the writers that check it give.
// the first file is written. A refused file, or a folder at a file's path, is not handed to
// `write`, so a writer that does not check the file access writes none of the files; the
// error is the file access's own refusal, as the writers that check it give.
#[cfg(not(target_arch = "wasm32"))]
if files.len() > 1 {
let named = |e, p: &str| if self.redact_paths { super::access::naming_in_error(e, p) } else { e };
for (p, _) in &files {
super::may_write(p).map_err(|e| named(e, p))?;
}
for (p, _) in &files {
super::access::regular_write_target(p).map_err(|e| named(e, p))?;
if let Some(refused) = files.iter().find_map(|(p, _)| {
super::access::may_write_file(p).err().map(|e| if self.redact_paths { super::access::naming_in_error(e, p) } else { e })
}) {
return Err(refused);
}
super::export_names::distinct_write_targets(files.iter().map(|(p, _)| p.as_str()))?;
}
+1 -1
View File
@@ -1033,7 +1033,7 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
/// each assigned name against the list it must come from, and puts the checked names into the
/// job: a print or flattener preset by its name (any case), an RGB or CMYK color profile by its
/// 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, and so does `CUSTOMPROFILE` with no profile `name`.
/// a control character, throws, and so does `CUSTOMPROFILE` with no profile `name` and no profile in the base settings.
fn check_names(h: &Host, doc: Doc, job: &mut Job) -> std::result::Result<(), HostError> {
let (count, saved_ignore, saved_fit, saved_tiled, mut base_profile) = with_doc(h, doc, |_, st| {
let mode = st.doc.print_setup.as_ref().and_then(|v| v.get("artboards")).and_then(Value::as_str);
+1 -1
View File
@@ -1874,7 +1874,7 @@ fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() {
/// to the Script Console.
#[test]
fn a_saves_warnings_go_to_the_console() {
let base = folder("warnings");
let base = folder("pdf-warnings");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
+14 -4
View File
@@ -563,6 +563,7 @@ impl Interp {
pub(crate) fn sync_host_files(&mut self) -> JsResult<()> {
let mut updates = Vec::new();
let mut untracked = Vec::new();
for id in self.host_file_objects.clone() {
self.use_fuel()?;
let Some(object) = self.heap.object(id) else { continue };
@@ -570,13 +571,22 @@ impl Interp {
let class = h.class;
for (name, file, previous) in &h.files {
let Some(file_id) = file.as_object() else { continue };
if crate::file_classes::file_path(self, file_id)?.as_ref() != Some(previous)
&& let Some((get, set)) = self.file_accessors(class, name)
{
updates.push((id, name.clone(), file.clone(), previous.clone(), get, set));
match crate::file_classes::file_path(self, file_id)? {
// An object that is no longer a File (its prototype changed) is not tracked
// any more, and the host keeps the path it has.
None => untracked.push((id, name.clone())),
Some(path) if path != *previous => {
if let Some((get, set)) = self.file_accessors(class, name) {
updates.push((id, name.clone(), file.clone(), previous.clone(), get, set));
}
}
Some(_) => {}
}
}
}
for (id, name) in untracked {
self.keep_host_file(id, name, Value::Undefined)?;
}
for (id, name, file, previous, get, set) in updates {
self.use_fuel()?;
// A property the host changed since the assignment no longer holds this File: it is
+9
View File
@@ -1682,3 +1682,12 @@ fn a_refused_path_change_is_thrown_once() {
assert!(first.contains("refused"), "{first}");
assert_eq!(*seen.borrow(), ["/a", "/good"]);
}
#[test]
fn a_file_whose_prototype_changes_is_no_longer_tracked() {
let (mut r, seen) = file_property_realm();
r.set_es2015(true);
let source = "var f = new File('/a'); it.file = f; Reflect.setPrototypeOf(f, Object.prototype); it.touch(); it.touch(); it.file !== f && it.file instanceof File";
assert_eq!(r.run(source).unwrap(), JsValue::Bool(true));
assert_eq!(*seen.borrow(), ["/a"]);
}
+2 -1
View File
@@ -3797,7 +3797,8 @@ through `$`:
`PrintPosition`, `PrintTiling`, `PrintArtworkDesignation`, `PrintingBounds`, `PrintFontDownloadMode`,
`FontSubstitutionPolicy`, `PageMarksTypes`, `PostScriptImageCompressionType` and `PrinterPostScriptLevelEnum` hold
strings such as `"PrintTiling.TILEFULLPAGES"`. VectorCraft's own rules: `print` writes the file `jobOptions.file`
names. `jobOptions.file` keeps the assigned File object and uses its current path when printing.
names. `jobOptions.file` keeps the assigned File object and uses its current path when printing. When a script
changes that object's prototype, `jobOptions.file` keeps the path it held at the last call to a host object.
The file is checked as `saveAs` checks its file: PostScript when the name ends with `.ps` (any case, including `.ps` alone) or `postScriptLevel` is
assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension, and
`printerName` does not apply. The PostScript is level 2 when `postScriptLevel` is not assigned, the default it
+1 -1
View File
@@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: a document's perspective grid is shown, hidden, given its active plane and reset to a built-in or saved preset of the type the script names; `app.getPresetSettings` gives the settings of a startup preset as a `DocumentPreset`; and `app.startupPresetsList` lists the startup presets' names, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Document/ and https://ai-scripting.docsforadobe.dev/jsobjref/Application/ list them (`docs/mcp.md`). Showing, hiding and the active plane add no undo step in a script run, as outside one. Workspaces, `loadColorSettings`, `showPresets` and perspective grid preset files are not there yet. `crates/engine/src/tests/script_dom_perspective.rs`.
- Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). A path's fill or stroke takes a `SpotColor` of a spot at a tint (https://ai-scripting.docsforadobe.dev/jsobjref/SpotColor/). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`, `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it; `removeAll()` on a compound path's `pathItems` throws when it would empty a compound path that clips a group or layer keeping other objects that are not ruler guides. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check the group's, layer's and artboard's locks; turning clipping on also refuses a hidden or locked topmost object, which would become the mask. In a Shaper group, new empty groups and compound paths and turning clipping on are refused, since the group keeps its source art at the bottom. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws unless the base settings hold a profile. `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available, and `unitScaleRatio` is a percentage, with 100 at full size (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`); a batch submitted after a spool failure was reported clears it once the worker sends every job of the batch without a failure, while a failure reported after submission stays. `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.