From ba0441c458a6496b9152924ce895475cfc5e0ae5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:33:43 -0800 Subject: [PATCH 1/7] Scripts: addDocument takes only a DocumentPreset and throws when its profile cannot be read - new DocumentPreset() now makes an object of the DocumentPreset class whose settings the run keeps, so addDocument refuses a plain object, one with a typename of DocumentPreset included, with a TypeError naming presetSettings. - When file.new reports a profileError, addDocument throws an error that names the profile and the reason, and the document made with the defaults is put back. - A script's file.new reads the New Document profile file in the app's own profiles folder; the automation roots in force still apply. Before, the script's file gate refused the folder, so a scripted addDocument never used an edited profile. Docs: docs/mcp.md. --- crates/engine/src/cmd/newdoc.rs | 17 ++- crates/engine/src/file_access.rs | 9 +- crates/engine/src/script/dom.rs | 113 +++++++++++++++--- crates/engine/src/tests/script_dom.rs | 60 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 15 ++- docs/mcp.md | 10 +- 6 files changed, 197 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 983ef4041d..fb26b13c68 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -984,13 +984,18 @@ impl Session { let file = path.to_string_lossy().to_string(); // Checked before the file is looked for, so a request that may not read the folder learns // nothing of its files, nor where the folder is. + // A script's gate does not apply to reads of the app's own folder; the automation roots in + // force still do. let denied = |_| PROFILE_DENIED.to_string(); - crate::file_access::check_read(&file).map_err(denied)?; - if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { - return Ok(None); - } - crate::file_access::check_read(&file).map_err(denied)?; - let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; + let read = crate::file_access::app_folder_read(|| { + crate::file_access::check_read(&file).map_err(denied)?; + if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { + return Ok(None); + } + crate::file_access::check_read(&file).map_err(denied)?; + crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + })?; + let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs // them, so the new document's assigned profiles draw and are saved with it. let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..7c246c6a64 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -206,9 +206,16 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) } +/// Run `f`, a read of a file in one of the app's own folders, with reads exempt from the gate of +/// the script command this thread runs. Unlike [`unconfined`], the roots in force still apply. +pub(crate) fn app_folder_read(f: impl FnOnce() -> T) -> T { + with_gate_reads_exempt(true, f) +} + thread_local! { /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an - /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + /// [`unconfined`] or an [`app_folder_read`] entered after the gate was put in force + /// ([`with_script_gate`]). static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..f8caab9adb 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -85,13 +85,14 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, whether a call's own savepoint +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + presets: RefCell>>, } impl State { @@ -873,10 +874,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Range("the startup preset's name is too long".into())); } let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + // Only an object `new DocumentPreset()` made: a plain object such as `{width: 500}` is refused. let settings = match given(arg(a, 2)) { None | Some(Data::Null) => Vec::new(), - Some(Data::Object(o)) => o.clone(), - Some(_) => return Err(HostError::Type("presetSettings must be a DocumentPreset".into())), + Some(d) => { + let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + h.dom.presets.borrow()[i].clone() + } }; let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given); for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] { @@ -913,23 +917,101 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { if let Some(m) = mode { p.entry("colorMode").or_insert_with(|| json!(m)); } - new_document(h, p) + // A profile whose file could not be read throws, and the document `file.new` made with the + // defaults is put back, with the Recent sizes as they were. + atomically(h, |h| { + let (_, value) = command_value(h, "file.new", &Value::Object(p))?; + if let Some(e) = value.get("profileError") { + let profile = e["profile"].as_str().unwrap_or_default(); + let reason = e["reason"].as_str().unwrap_or_default(); + return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); + } + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) + }) } /// `new DocumentPreset()`: a record of new-document settings with the defaults the help page /// gives; the other settings are -/// left out. -fn new_preset(_: &[Data]) -> Answer { +/// left out. The settings stay with the run, which hands the script an object of the +/// `DocumentPreset` class. +fn new_preset(h: &Host) -> Answer { + let mut presets = h.dom.presets.borrow_mut(); + if presets.len() >= MAX_PRESETS { + return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); + } let item = |k: &str, v: Data| (k.to_string(), v); - Ok(Data::Object(vec![ - item("typename", text("DocumentPreset")), + presets.push(vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ])) + ]); + Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) +} + +/// The most `DocumentPreset` objects one run can make. +const MAX_PRESETS: usize = 10_000; + +/// The settings a `DocumentPreset` has, each a property a script reads and assigns. +const PRESET_FIELDS: &[&str] = &[ + "artboardLayout", + "artboardRowsOrCols", + "artboardSpacing", + "colorMode", + "documentBleedLink", + "documentBleedOffsetRect", + "height", + "numArtboards", + "previewMode", + "rasterResolution", + "title", + "transparencyGrid", + "units", + "width", +]; + +/// The index in the run's presets of the `DocumentPreset` `d` is, when it is one this run made. +fn preset_of(h: &Host, d: &Data) -> Option { + let handle = handle_of(d, "DocumentPreset")?; + let [run, i] = handle.as_slice() else { return None }; + if whole(*run) != Some(h.run) { + return None; + } + let i = usize::try_from(whole(*i)?).ok()?; + (i < h.dom.presets.borrow().len()).then_some(i) +} + +/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and +/// a value is checked when `addDocument` uses it. +fn preset_field(link: &Link, key: &'static str) -> HostMember { + let not_preset = || HostError::Type("this is not a DocumentPreset".into()); + let l = link.clone(); + let get: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let presets = h.dom.presets.borrow(); + Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone())) + }); + let l = link.clone(); + let set: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + let value = arg(&a, 1).clone(); + h.charge_call(16 + data_size(&value))?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let mut presets = h.dom.presets.borrow_mut(); + let fields = &mut presets[i]; + match fields.iter_mut().find(|(k, _)| k == key) { + Some((_, v)) => *v = value, + None => fields.push((key.to_string(), value)), + } + Ok(Data::Undefined) + }); + HostMember::Property { get, set } } // ---- Document ---- @@ -1723,11 +1805,14 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), application.push(later(l, "Application", "beep")); let preset = { let l = link.clone(); - let f: HostFunction = Rc::new(move |a: Vec| { - current(&l)?.charge_call(64)?; - new_preset(&a) + let f: HostFunction = Rc::new(move |_: Vec| { + let h = current(&l)?; + h.charge_call(64)?; + new_preset(&h) }); - HostClass { name: "DocumentPreset".into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); + HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } }; let mut classes = vec![ class("Application", None, application, None), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 795161ac1c..a0e63a5d06 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -835,6 +835,66 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +#[test] +fn add_document_takes_only_a_document_preset() { + let mut s = Session::new(); + for source in [ + "app.documents.addDocument('Print', {width: 500});", + "app.documents.addDocument('Print', {});", + "app.documents.addDocument('Print', {typename: 'DocumentPreset', width: 500});", + "var p = new DocumentPreset(); var q = {}; for (var k in p) q[k] = p[k]; app.documents.addDocument('Print', q);", + "app.documents.addDocument('Print', [612, 792]);", + "app.documents.addDocument('Print', 'DocumentPreset');", + ] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError") && e.contains("presetSettings must be a DocumentPreset"), "{source}: {e}"); + } + assert!(s.documents().is_empty(), "a refused preset makes no document"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 500; vc.log(app.documents.addDocument('Print', p).width);"); + assert_eq!(out, vec![json!(500)]); +} + +#[test] +fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + // A profile with no file gives the defaults. + let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.doc().unwrap().links_from, None); + // A script reads the profile's file in the app's own folder. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + log(&mut s, "app.documents.addDocument('Print');"); + assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + // file.new itself makes the document with the defaults and reports the profile it could not read. + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + s.execute("file.close", &json!({})).unwrap(); + let recent = s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(); + let e = failure(&mut s, "app.documents.addDocument('Print');"); + assert!(e.contains("Error: the New Document profile Print could not be read"), "{e}"); + assert!(s.documents().is_empty(), "the document made with the defaults is put back"); + // A script that catches the error finds nothing changed. + let out = log( + &mut s, + "var p = new DocumentPreset(); p.width = 333;\ + try { app.documents.addDocument('Print', p); } catch (e) { vc.log(e.name); } vc.log(app.documents.length);", + ); + assert_eq!(out, vec![json!("Error"), json!(0)]); + assert_eq!(s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(), recent, "the Recent sizes are as they were"); + // A startup preset with no profile reads no file. + let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); + assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..d9b6b87103 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -73,7 +73,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ + "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ PageItems RulerUnits ZOrderMethod", ), @@ -83,6 +83,14 @@ const INSIDE: &[(&str, &str)] = &[ "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ selection typename", ), + ("DocumentPreset.", "prototype"), + ( + "DocumentPreset.prototype.", + "artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \ + colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \ + height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \ + transparencyGrid transparencyGrid= typename units units= width width=", + ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), ("Document.", "prototype"), @@ -123,9 +131,8 @@ const INSIDE: &[(&str, &str)] = &[ ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; -/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. -const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ +/// The classes the host adds with nothing but a prototype and its constructor: the page item types. +const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..182e0fe1c8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2633,7 +2633,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when - the preset it is given holds one of them with a value other than `null`, and makes no document. + the preset it is given holds one of them with a value other than `null`, and makes no document. A + `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a + `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the + profile and the reason, and makes no document. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) @@ -9045,7 +9049,9 @@ The profile is read on every `file.new`, so a replayed journal or a recorded act runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read. When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the folder (whether or not the file exists), the document starts with the defaults and -`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar. The +`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and +a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's +file. The reason given when the read roots leave out the folder does not name the folder's path. Color profiles the profile's file carries are installed when they are missing, as `document.open` installs them, and each one that can't be used adds a line to `file.new`'s `warnings`. The new document's links find their files through relative paths from the From 5cb64802585f18dcbaeb3c4bea6136d87172b297 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:53:28 -0800 Subject: [PATCH 2/7] Scripts: assigning PageItem.selected keeps how the other objects are selected Setting selected to true or false runs select.add or select.toggle for that one object, so the other objects keep their direct-selected anchors and segments and the key object. Before, it replaced the selection with whole objects. --- crates/engine/src/script/dom.rs | 16 +++++++--------- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index f8caab9adb..e70dfbb86a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1378,17 +1378,15 @@ fn item_selected(h: &Host, a: &[Data]) -> Answer { fn item_set_selected(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let on = boolean(arg(a, 1), "selected")?; - let mut ids = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); - if ids.contains(&item.id) == on { + if with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)) == on { return Ok(Data::Undefined); } - if on { - let mut given = selection_ids(h, item.doc, arg(a, 0))?; - ids.append(&mut given); - } else { - ids.retain(|i| *i != item.id); - } - set_selection(h, item.doc, ids) + // Adding or removing the one object keeps how the others are selected (their direct-selected + // anchors and segments, and the key object). + let ids = if on { selection_ids(h, item.doc, arg(a, 0))? } else { vec![item.id] }; + let id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, item.doc.uid, false, |h| command(h, id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) } /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a0e63a5d06..9d933378ea 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -835,6 +835,24 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +#[test] +fn setting_selected_keeps_how_the_other_objects_are_selected() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let anchors = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert!(anchors.is_some()); + log( + &mut s, + "var p = app.activeDocument.pageItems;\ + for (var i = 0; i < p.length; i++) { if (p[i].left == 200) p[i].selected = true; if (p[i].left == 100) p[i].selected = false; }", + ); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.objects, vec![a, c]); + assert_eq!(sel.anchors.get(&a).cloned(), anchors, "the direct-selected anchors stay"); +} + #[test] fn add_document_takes_only_a_document_preset() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 182e0fe1c8..a826f5b3b8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2644,7 +2644,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each entry `[i]` gives. Each page item (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the - Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected`, `opacity` (0 to + Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds + or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they + were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` From e15e3e083d652d9dd1b9145663d9b7838a07215e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:35:17 -0800 Subject: [PATCH 3/7] New Document: Columns reads float rows and columns as file.new does The dialog read artboardLayout's rows and columns as whole numbers only, so a value stored as a float (4.0 from ui.dialog.set) fell back to the stored columns while file.new made the grid from it. The dialog now reads both as file.new does: a number of 1 or more, rounded and kept to the artboard limit. --- crates/ui-egui/src/dialogs/new_document.rs | 28 +++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 6b9abbcb2f..d7c20c0137 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -234,18 +234,20 @@ fn unit(d: &Dialog) -> Unit { } /// The artboard layout fields. A grid by column with rows shows the columns those rows give the -/// current number of artboards, as `file.new` lays them out. +/// current number of artboards, as `file.new` lays them out. Rows and columns are read as +/// `file.new` reads them: a number of 1 or more, rounded and kept to [`MAX_ARTBOARDS`]. fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { let l = d.fields.get("artboardLayout"); let get = |k: &str| l.and_then(|l| l.get(k)); + let count = |k: &str| get(k).and_then(Value::as_f64).filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u64); let lay = get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(); - let rows = get("rows").and_then(Value::as_u64).filter(|r| *r > 0 && lay == ArtboardLayout::GridByColumn); + let rows = count("rows").filter(|_| lay == ArtboardLayout::GridByColumn); let columns = match rows { Some(rows) => { let n = d.f64("artboards", 1.0).round().clamp(1.0, MAX_ARTBOARDS as f64) as u64; n.div_ceil(rows.min(n)) } - None => get("columns").and_then(Value::as_u64).unwrap_or(1), + None => count("columns").unwrap_or(1), }; (lay, columns, get("spacing").and_then(Value::as_f64).unwrap_or(20.0), get("rightToLeft").and_then(Value::as_bool).unwrap_or(false)) } @@ -931,6 +933,26 @@ mod tests { assert_eq!(columns(&app), 2); } + /// Rows and columns stored as floats, as `ui.dialog.set` stores them, show what `file.new` + /// makes of them: rounded, at least 1 and at most the artboard limit. + #[test] + fn columns_read_float_rows_and_columns_as_file_new_does() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + set(&mut app, "artboards", json!(5)); + for (rows, shown) in [(json!(4.0), 2), (json!(3.5), 2), (json!(2.4), 3)] { + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 1, "rows": rows})); + assert_eq!(columns(&app), shown, "rows {rows}"); + } + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 3.0})); + assert_eq!(columns(&app), 3); + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 1e9})); + assert_eq!(columns(&app), super::MAX_ARTBOARDS as u64); + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 0.4})); + assert_eq!(columns(&app), 1); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] From abe8b303ded7186796ad1ac8647f142a02ef1375 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:14:01 -0800 Subject: [PATCH 4/7] Scripts: remove and removeAll keep art on a locked artboard PageItem.remove() and PageItems.removeAll() checked only whether the object and its layers and groups were shown and unlocked, then passed the ids to edit.clear, which deletes named objects without checking artboard locks. Both now throw "cannot delete objects on a locked artboard" with the object ids and delete nothing, as art on a locked artboard is not editable elsewhere in the document. --- crates/engine/src/script/dom.rs | 26 +++++++++++++++++++++----- crates/engine/src/tests/script_dom.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e70dfbb86a..bce4edad74 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1249,19 +1249,26 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { } /// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or -/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, +/// and so does an object on a locked artboard. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}"))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } @@ -1518,17 +1525,26 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { } /// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or -/// group, or a group holding one is refused, as [`items_remove_all`] refuses it. +/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] +/// refuses it. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let whole = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable)); + let (whole, on_locked) = with_doc(h, item.doc, |_, st| { + (editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable), st.doc.on_locked_artboard(item.id)) + }); if !whole { return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; Ok(Data::Undefined) } +/// The error of `remove()` and `removeAll()` for an object on a locked artboard. +const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; + /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 9d933378ea..26632b7055 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -973,6 +973,30 @@ fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { assert!(s.active().unwrap().doc.node(b).is_none()); } +/// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. +#[test] +fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + let lock = |s: &mut Session, locked: bool| { + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = locked; + Ok(()) + }) + .unwrap(); + }; + lock(&mut s, true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[1].remove();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", b.0)), "{e}"); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index a826f5b3b8..51cd09fdbb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2673,7 +2673,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot tab as it was. A bad value throws an error and changes nothing. An object that was deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw - `cannot delete hidden or locked objects` and delete nothing. Setting `width` or `height` scales the object along + `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` + when any object is on one, throw `cannot delete objects on a locked artboard` and delete nothing. Setting `width` or `height` scales the object along the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, From 71aaa752a03dd40e4cbc7faef551022c6dd2f9a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:52:56 -0800 Subject: [PATCH 5/7] New Document: a new layout keeps the columns a preset's rows showed A preset made with file.new's rows under gridByColumn shows the column count those rows give the current number of artboards. Changing the Layout field removed the rows and kept the preset's stored columns, so Create laid out a different number of columns than the dialog showed. The layout change now writes the shown count into columns, for rows stored as integers or floats. Under gridByRow the dialog shows the stored columns and file.new rejects rows, so a layout change from it keeps the stored columns, as it does for rows file.new would reject. --- crates/ui-egui/src/dialogs/new_document.rs | 41 +++++++++++++++++++--- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index d7c20c0137..cf10f0035e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,11 +253,16 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. fn set_layout(d: &mut Dialog, key: &str, v: Value) { + let (lay, shown, ..) = layout(d); let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); - if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) { - o.remove("rows"); + if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) + && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) + && key == "layout" + && lay == ArtboardLayout::GridByColumn + { + o.insert("columns".into(), json!(shown)); } l[key] = v; d.fields.insert("artboardLayout".into(), l); @@ -914,7 +919,35 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 3, "spacing": 5.0})); set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4})); super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); - assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 1})); + } + + /// A new layout keeps the columns a preset's rows showed, so Create lays out what the dialog + /// showed. Under a grid by row the dialog shows the stored columns, and they stay. + #[test] + fn a_new_layout_keeps_the_columns_a_presets_rows_showed() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + set(&mut app, "artboards", json!(9)); + for to in ["gridByRow", "gridByColumn", "row", "column"] { + for rows in [json!(4), json!(4.0), json!(3.6)] { + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); + assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!(to)); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": to, "columns": 3}), "{to}, rows {rows}"); + } + } + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); + assert_eq!(columns(&app), 2); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByColumn")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 2})); + assert_eq!(columns(&app), 2); + // Rows file.new would reject leave the stored columns the dialog showed. + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 0})); + assert_eq!(columns(&app), 2); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 2})); } /// Columns shows what a preset's rows give the current number of artboards. From b2d458f66754a3233d1effc411c2158446113ce5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:01:28 -0800 Subject: [PATCH 6/7] Scripts: print lists in the host name check, applies range and print area over saved settings - The host name check lists Document.print as a file write, and app's print lists, PrintOptions, its option classes and the printing enumerations as names that stay inside the run. - The script checker reports a file write for print called on a document: app.activeDocument, app.documents[i], documents.add(), documents.getByName() and app.open(), or a variable that holds one. A print method of any other object is not reported. - An assigned artboardRange without printAllArtboards replaces the saved range. An assigned printArea prints by artboard when the saved settings, or the preset's, ignore the artboards: the assigned range, or each artboard. - The two scale factors are linked only when they are equal, as file.print compares them. - The format follows the name jobOptions.file gives, also when that name is a link to a file with another extension. - A print option name with a control character at either end throws. --- crates/engine/src/script/dom/print.rs | 56 +++++++++---- crates/engine/src/tests/script_print.rs | 64 +++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 84 ++++++++++++++++++- crates/scriptcheck/src/analyze/features.rs | 17 +++- crates/scriptcheck/src/catalog.rs | 19 +++++ crates/scriptcheck/src/tests.rs | 20 +++++ docs/mcp.md | 23 ++--- 7 files changed, 253 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index c2acec376e..8019ce2583 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -29,7 +29,12 @@ //! 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 `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range -//! every artboard prints. +//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange` +//! replaces the saved range, which prints when the saved settings print a range. +//! - An assigned `printArea` prints by artboard when the saved settings, or the preset's, ignore +//! the artboards: the artboards an assigned `artboardRange` names, otherwise each artboard. +//! - The format follows the name `jobOptions.file` gives, also when that name is a link to a file +//! with another extension. //! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps the saved value. //! - `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 @@ -37,8 +42,8 @@ //! not the name of an RGB or CMYK color profile (any case); and when `paperOptions.name` is not //! the id or label of a paper `file.print` knows, or names a paper other than `custom` while //! `width` or `height` is assigned above 0. An assigned name that is empty or only spaces, -//! or that holds `/`, `\` or a control character, throws too. Each checked name goes to -//! `file.print` without the spaces around it. `printerName` and `PPDName` take only the empty +//! or that holds `/`, `\` or a control character (also at either end), throws too. Each checked +//! name goes to `file.print` without the spaces around it. `printerName` and `PPDName` take only the empty //! string. //! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects. //! - `app.printerList` is not available yet, and `app.PPDFileList` is empty: VectorCraft prints @@ -497,6 +502,8 @@ struct Job { paper_size: bool, /// `colorProfileMode` is `SOURCEPROFILE`: the colors print as they are, whatever `name` says. source: bool, + /// `printArea` is assigned: the artboards print even when the base settings ignore them. + print_area: bool, /// The groups of `settings`: the top level and each nested object by its key. top: Map, groups: Vec<(&'static str, Map)>, @@ -623,7 +630,15 @@ fn map_job(h: &Host, slot: usize, job: &mut Job) { job.group("advanced").insert("printAsBitmap".into(), json!(flag(v))); } "file" => job.file = Some(v.clone()), - "artboardRange" => job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty()), + "artboardRange" => { + job.range = Some(string_of(v)).filter(|r| !r.trim().is_empty()); + // Without `printAllArtboards`, the range replaces the base range and the base + // settings still decide whether a range prints. + if let Some(range) = job.range.as_ref().filter(|_| value("printAllArtboards").is_none()) { + s.insert("range".into(), json!(range)); + } + } + "printArea" => job.print_area = true, _ => {} } } @@ -708,10 +723,8 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<( if let Some(hh) = vs { g.insert("height".into(), json!(hh)); } - let linked = match (hs, vs) { - (Some(w), Some(hh)) => (w - hh).abs() < 1e-9, - _ => false, - }; + // Linked only when the factors are equal, as `file.print` compares them. + let linked = matches!((hs, vs), (Some(w), Some(hh)) if w == hh); g.insert("linked".into(), json!(linked)); } for (k, v) in &set { @@ -830,8 +843,10 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { if let Some(preset) = job.preset.take() { p.insert("preset".into(), json!(preset)); } + // The format follows the name `jobOptions.file` gives, not the real path a link leads to. + let postscript = job.level.is_some() || crate::cmd::fileio::extension(path) == "ps"; + p.insert("format".into(), json!(if postscript { "postscript" } else { "pdf" })); if let Some(level) = job.level { - p.insert("format".into(), json!("postscript")); p.insert("level".into(), json!(level)); } let settings = job.settings(); @@ -861,18 +876,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 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")) + }); if let Some(range) = &job.range { - let count = with_doc(h, doc, |_, st| st.doc.artboards.len()); 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; if let Some(name) = job.preset.take() { let n = plain_name("PrintOptions.printPreset", "print preset", &name)?; - if s.print_preset_settings(n).is_none() { - return Err(no_such("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); job.preset = Some(n.to_string()); } + // 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") { + let mode = if job.top.contains_key("range") { "range" } else { "all" }; + job.top.insert("artboards".into(), json!(mode)); + } if let Some(name) = job.flattener.take() { let n = plain_name("PrintOptions.flattenerPreset", "flattener preset", &name)?; if FlattenOptions::find_preset(n, &s.prefs.flattener_presets).is_none() { @@ -911,11 +935,15 @@ fn no_such(what: &str, kind: &str, name: &str) -> HostError { /// `name` without the spaces around it, or an error when it is empty or holds a path separator or /// a control character. fn plain_name<'a>(what: &str, kind: &str, name: &'a str) -> std::result::Result<&'a str, HostError> { + // Control characters are looked for before the trim, which would drop a tab or a line break. + if name.chars().any(char::is_control) { + return Err(no_such(what, kind, name)); + } let n = name.trim(); if n.is_empty() { return Err(HostError::Error(format!("{what} must name a {kind}"))); } - if n.contains(['/', '\\']) || n.chars().any(char::is_control) { + if n.contains(['/', '\\']) { return Err(no_such(what, kind, name)); } Ok(n) diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index 104687e0e3..a9eb84b75d 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -81,7 +81,8 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { o.paperOptions.name = 'a4'; o.coordinateOptions.fitToPage = true; o.coordinateOptions.orientation = PrintOrientation.PORTRAIT;\n\ o.printerName = ''; o.fontOptions.downloadFonts = PrintFontDownloadMode.DOWNLOADSUBSET;\n\ doc.print(o);\n\ - o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/c.ps');\n\ + j.file = new File(dir + '/c.ps'); doc.print(o);\n\ + o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2; j.file = new File(dir + '/level2.prn');\n\ doc.print(o);\n\ vc.log([app.printPresetsList[0], app.PPDFileList.length]);" ), @@ -95,7 +96,9 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() { assert_eq!(pages(&dir.join("a.pdf")).len(), 6, "two artboards, three copies"); assert_eq!(pages(&dir.join("b.pdf")), vec![(595.0, 842.0)], "artboard 2 only, on upright A4"); let ps = std::fs::read_to_string(dir.join("c.ps")).unwrap(); - assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "{}", &ps[..ps.len().min(200)]); + assert!(ps.starts_with("%!PS") && !ps.contains("%%LanguageLevel: 2"), "a .ps name alone: {}", &ps[..ps.len().min(200)]); + let ps = std::fs::read_to_string(dir.join("level2.prn")).unwrap(); + assert!(ps.starts_with("%!PS") && ps.contains("%%LanguageLevel: 2"), "a level alone: {}", &ps[..ps.len().min(200)]); assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"], saved, "printing leaves the saved settings as they are"); assert_eq!(s.active().unwrap().history.undo.len(), undo, "and adds no undo step"); // The commands stay closed to vc.run, before and after a print. @@ -272,6 +275,61 @@ fn one_assigned_scale_factor_keeps_the_saved_other() { let _ = std::fs::remove_dir_all(base); } +/// An assigned `artboardRange` replaces a saved range, an assigned `printArea` prints by artboard over +/// saved settings that ignore the artboards, and two scale factors that differ by any amount print +/// unlinked. +#[test] +fn assigned_job_and_scale_options_apply_over_the_saved_settings() { + let base = folder("over-saved"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let print = |s: &mut Session, name: &str, body: &str| { + let file = quoted(&dir.join(name)); + logged( + s, + &base, + &format!("Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({file}); {body} app.activeDocument.print(o);"), + ); + pages(&dir.join(name)).len() + }; + s.execute("print.setup", &json!({"settings": {"artboards": "range", "range": "1"}})).unwrap(); + assert_eq!(print(&mut s, "saved.pdf", ""), 1, "the saved range"); + assert_eq!(print(&mut s, "range.pdf", "o.jobOptions.artboardRange = '1-2';"), 2, "the assigned range replaces the saved one"); + s.execute("print.setup", &json!({"settings": {"artboards": "ignore"}})).unwrap(); + assert_eq!(print(&mut s, "ignore.pdf", ""), 1, "all the art as one page"); + assert_eq!(print(&mut s, "area.pdf", "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS;"), 2, "each artboard prints"); + assert_eq!(print(&mut s, "range-ignored.pdf", "o.jobOptions.artboardRange = '2';"), 1, "a range alone keeps ignoring the artboards"); + let area_range = "o.jobOptions.printArea = PrintingBounds.ARTBOARDBOUNDS; o.jobOptions.artboardRange = '2';"; + assert_eq!(print(&mut s, "area-range.pdf", area_range), 1, "printArea with a range prints the range"); + let scaled = "o.coordinateOptions.horizontalScale = 100; o.coordinateOptions.verticalScale = 100.0000000005;"; + assert!(print(&mut s, "scale.pdf", scaled) >= 1, "factors that differ by a tiny amount print unlinked"); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["artboards"], json!("ignore"), "the saved settings stay"); + let _ = std::fs::remove_dir_all(base); +} + +/// The format follows the name `jobOptions.file` gives, not the extension of the file a link in the +/// granted folder leads to. +#[cfg(unix)] +#[test] +fn the_format_follows_the_name_the_script_gives() { + let base = folder("format-name"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + std::fs::write(dir.join("proof.pdf"), "old").unwrap(); + std::os::unix::fs::symlink(dir.join("proof.pdf"), dir.join("proof.ps")).unwrap(); + logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new PrintOptions(); o.jobOptions.file = new File({}); app.activeDocument.print(o);", + quoted(&dir.join("proof.ps")) + ), + ); + let written = std::fs::read(dir.join("proof.pdf")).unwrap(); + assert!(written.starts_with(b"%!PS"), "PostScript for a .ps name: {:?}", String::from_utf8_lossy(&written[..written.len().min(40)])); + let _ = std::fs::remove_dir_all(base); +} + /// Artboard ranges the document does not hold and preset names that are not presets, such as /// paths, throw before anything is written. #[test] @@ -323,6 +381,8 @@ fn print_refuses_profile_paper_and_blank_preset_names() { ("c.name = ' ';", "PrintColorManagementOptions.name must name a color profile"), ("p.name = '../letter';", paper), ("p.name = 'let\\u0007ter';", paper), + ("p.name = '\\tA4\\n';", paper), + ("o.printPreset = '[Default]\\n';", "PrintOptions.printPreset names no print preset"), ("p.name = 'Office Tray 2';", paper), ("p.name = '';", "PrintPaperOptions.name must name a paper"), ("p.name = 'a4'; p.width = 300;", "PrintPaperOptions.width and height apply only to custom paper, not a4"), diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 26b476a0b6..88574f94e9 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -39,6 +39,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), ("Document.prototype.saveAs", "app.activeDocument.saveAs(f);", "filesWritten"), ("Document.prototype.exportFile", "app.activeDocument.exportFile(f, ExportType.PNG24);", "filesWritten"), + ("Document.prototype.print", "var o = new PrintOptions(); o.jobOptions.file = new File(p); app.activeDocument.print(o);", "filesWritten"), ]; /// The names the host adds that stay inside the document and the run, by the object that has them. @@ -83,7 +84,8 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - open selection typename userInteractionLevel userInteractionLevel=", + open PPDFileList printPresetsList printerList printerList= selection typename userInteractionLevel \ + userInteractionLevel=", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), @@ -137,6 +139,86 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The print option classes and the enumerations of printing. + ( + "", + "FontSubstitutionPolicy PageMarksTypes PostScriptImageCompressionType PrintArtworkDesignation PrintColorIntent \ + PrintColorManagementOptions PrintColorProfile PrintColorSeparationMode PrintColorSeparationOptions \ + PrintCoordinateOptions PrintFlattenerOptions PrintFontDownloadMode PrintFontOptions PrintJobOptions PrintOptions \ + PrintOrientation PrintPageMarksOptions PrintPaperOptions PrintPosition PrintPostScriptOptions PrintTiling \ + PrinterPostScriptLevelEnum PrintingBounds", + ), + ("PrintOptions.", "prototype"), + ( + "PrintOptions.prototype.", + "PPDName PPDName= colorManagementOptions colorManagementOptions= colorSeparationOptions colorSeparationOptions= \ + constructor coordinateOptions coordinateOptions= flattenerOptions flattenerOptions= flattenerPreset \ + flattenerPreset= fontOptions fontOptions= jobOptions jobOptions= pageMarksOptions pageMarksOptions= paperOptions \ + paperOptions= postScriptOptions postScriptOptions= printPreset printPreset= printerName printerName= typename", + ), + ("PrintJobOptions.", "prototype"), + ( + "PrintJobOptions.prototype.", + "artboardRange artboardRange= bitmapResolution bitmapResolution= collate collate= constructor copies copies= \ + designation designation= file file= name name= printAllArtboards printAllArtboards= printArea printArea= \ + printAsBitmap printAsBitmap= reversePages reversePages= typename", + ), + ("PrintColorManagementOptions.", "prototype"), + ("PrintColorManagementOptions.prototype.", "colorProfileMode colorProfileMode= constructor intent intent= name name= typename"), + ("PrintColorSeparationOptions.", "prototype"), + ( + "PrintColorSeparationOptions.prototype.", + "colorSeparationMode colorSeparationMode= constructor convertSpotColors convertSpotColors= inkList inkList= \ + overPrintBlack overPrintBlack= typename", + ), + ("PrintCoordinateOptions.", "prototype"), + ( + "PrintCoordinateOptions.prototype.", + "constructor emulsion emulsion= fitToPage fitToPage= horizontalScale horizontalScale= orientation orientation= \ + position position= tiling tiling= typename verticalScale verticalScale=", + ), + ("PrintFlattenerOptions.", "prototype"), + ( + "PrintFlattenerOptions.prototype.", + "clipComplexRegions clipComplexRegions= constructor convertStrokesToOutlines convertStrokesToOutlines= \ + convertTextToOutlines convertTextToOutlines= flatteningBalance flatteningBalance= gradientResolution \ + gradientResolution= overprint overprint= rasterizationResolution rasterizationResolution= typename", + ), + ("PrintFontOptions.", "prototype"), + ("PrintFontOptions.prototype.", "constructor downloadFonts downloadFonts= fontSubstitution fontSubstitution= typename"), + ("PrintPageMarksOptions.", "prototype"), + ( + "PrintPageMarksOptions.prototype.", + "bleedOffsetRect bleedOffsetRect= colorBars colorBars= constructor marksOffsetRect marksOffsetRect= pageInfoMarks \ + pageInfoMarks= pageMarksType pageMarksType= registrationMarks registrationMarks= trimMarks trimMarks= \ + trimMarksWeight trimMarksWeight= typename", + ), + ("PrintPaperOptions.", "prototype"), + ("PrintPaperOptions.prototype.", "constructor height height= name name= offset offset= transverse transverse= typename width width="), + ("PrintPostScriptOptions.", "prototype"), + ( + "PrintPostScriptOptions.prototype.", + "binaryPrinting binaryPrinting= compatibleShading compatibleShading= constructor forceContinuousTone \ + forceContinuousTone= imageCompression imageCompression= negativePrinting negativePrinting= postScriptLevel \ + postScriptLevel= shadingResolution shadingResolution= typename", + ), + ("FontSubstitutionPolicy.", "SUBSTITUTEDEVICE SUBSTITUTEOBLIQUE SUBSTITUTETINT"), + ("PageMarksTypes.", "Japanese Roman"), + ("PostScriptImageCompressionType.", "IMAGECOMPRESSIONNONE JPEG RLE"), + ("PrintArtworkDesignation.", "ALLLAYERS VISIBLELAYERS VISIBLEPRINTABLELAYERS"), + ("PrintColorIntent.", "ABSOLUTECOLORIMETRIC PERCEPTUALINTENT RELATIVECOLORIMETRIC SATURATIONINTENT"), + ("PrintColorProfile.", "CUSTOMPROFILE OLDSTYLEPROFILE PRINTERPROFILE SOURCEPROFILE"), + ("PrintColorSeparationMode.", "COMPOSITE HOSTBASEDSEPARATION INRIPSEPARATION"), + ("PrintFontDownloadMode.", "DOWNLOADCOMPLETE DOWNLOADNONE DOWNLOADSUBSET"), + ("PrintOrientation.", "AUTOROTATE LANDSCAPE PORTRAIT REVERSELANDSCAPE REVERSEPORTRAIT"), + ( + "PrintPosition.", + "TRANSLATEBOTTOM TRANSLATEBOTTOMLEFT TRANSLATEBOTTOMRIGHT TRANSLATECENTER TRANSLATELEFT TRANSLATERIGHT TRANSLATETOP \ + TRANSLATETOPLEFT TRANSLATETOPRIGHT", + ), + ("PrintTiling.", "TILEFULLPAGES TILEIMAGEABLEAREAS TILESINGLEFULLPAGE"), + ("PrinterPostScriptLevelEnum.", "PSLEVEL1 PSLEVEL2 PSLEVEL3"), + ("PrintingBounds.", "ARTBOARDBOUNDS ARTWORKBOUNDS"), ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`, diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 354a0540aa..4704e4baf8 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -284,14 +284,22 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// Whether this `(` calls a document's `print`: the document-model member chain the `(` has just + /// set aside until its `)` is one of [`catalog::DOM_DOCUMENTS`] followed by `called`, the method + /// as the chain writes it (`.print()`, or `[]()` when brackets name it). + fn document_print(&self, called: &str) -> bool { + let chain = self.suspended.last().filter(|c| c.wait.saturating_add(1) == self.depth()); + chain.and_then(|c| c.path.strip_suffix(called)).is_some_and(|receiver| catalog::DOM_DOCUMENTS.contains(&receiver)) + } + /// `(` after a name: a call. fn call(&mut self, line: Option) { let [h0, h1, h2, h3] = self.h; // `doc['saveAs'](f)`: a document method named by a string literal in brackets. if is(h0, "]") && is(h2, "[") - && let Some(name) = h1.filter(|s| s.kind == T::Str) - && catalog::DOM_FILE_WRITES.contains(&unquote(name.text, 32).as_str()) + && let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32)) + && (catalog::DOM_FILE_WRITES.contains(&name.as_str()) || (name == catalog::DOM_PRINT && self.document_print("[]()"))) { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); @@ -311,7 +319,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.acc.feature(FeatureId::FileDialog, line); } else if catalog::FOLDER_READS.contains(&n) || (file && catalog::FILE_READS.contains(&n)) { self.acc.feature(FeatureId::FileRead, line); - } else if (file && catalog::FILE_WRITES.contains(&n)) || catalog::DOM_FILE_WRITES.contains(&n) { + } else if (file && catalog::FILE_WRITES.contains(&n)) + || catalog::DOM_FILE_WRITES.contains(&n) + || (n == catalog::DOM_PRINT && self.document_print(".print()")) + { self.acc.feature(FeatureId::FileWrite, line); self.acc.outside(OutsideId::FilesWritten, line, None); } else if n == catalog::EXECUTE { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index ee5b63dfb2..9ebf0c52a5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -75,6 +75,25 @@ pub(crate) const DOM_ROOTS: [&str; 4] = ["app", "activeDocument", "documents", " // Document methods that write the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Document/ pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"]; +// The document method that writes the file its options' `jobOptions.file` names, on the same page. +// It counts only when a member chain that ends with one of `DOM_DOCUMENTS` calls it. +pub(crate) const DOM_PRINT: &str = "print"; + +// The member chains that give a document, whole and as the chains are written (`[]` for an index, +// `()` for a call): https://ai-scripting.docsforadobe.dev/jsobjref/Application/ (`activeDocument`, +// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `getByName`). +pub(crate) const DOM_DOCUMENTS: &[&str] = &[ + "activeDocument", + "app.activeDocument", + "documents[]", + "app.documents[]", + "documents.add()", + "app.documents.add()", + "documents.getByName()", + "app.documents.getByName()", + "app.open()", +]; + // Application methods that page doesn't list, named in public forum posts: // https://community.adobe.com/t5/illustrator-discussions/changes-in-cs6/td-p/4173362 (executeMenuCommand, // doScript, loadAction, unloadAction) and diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 12e5527811..361b5e0865 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -558,6 +558,26 @@ fn save_as_and_export_file_in_brackets_write_a_file() { assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[3, 4][..])]); } +/// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or +/// with its name in brackets, on a document or a variable that holds one; reading the method without +/// calling it, and a `print` method of another object, do not. +#[test] +fn print_writes_a_file() { + let r = report(concat!( + "var o = new PrintOptions(); o.jobOptions.file = new File(p);\n", + "app.activeDocument.print(o);\n", + "app.activeDocument['print'](o);\n", + "var n = app.activeDocument['print'];\n", + "var d = app.documents[0]; d.print(o);\n", + "logger.print('hello'); logger['print']('hello');\n", + "app.activeDocument.name.concat(logger.print('x'));\n", + "app.print(o); app.activeDocument.layers[0]['print'](o); app.documents['print'](o); app.preferences.activeDocument.print(o);\n", + "var e = app.open(new File(p)); e.print(o); activeDocument.print(o);\n", + )); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 5, 9][..])); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3, 5, 9][..])]); +} + /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing /// them and setting them on another object does not. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 93dac91b5c..24bf498130 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,8 +2558,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too, and so does a document's `saveAs` or `exportFile`), - `filesOpened` (files opened in other apps), `network`, + File object's `length`, `hidden` or `readonly` counts too, and so does a document's `saveAs` or `exportFile`, and + `print` called on `app.activeDocument`, `app.documents[i]`, `documents.add()`, `documents.getByName()` or + `app.open()`, or on a variable that holds one of them), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, @@ -2743,17 +2744,19 @@ app through the global object `vc`, and writes to the Script Console and runs ot `FontSubstitutionPolicy`, `PageMarksTypes`, `PostScriptImageCompressionType` and `PrinterPostScriptLevelEnum` hold strings such as `"PrintTiling.TILEFULLPAGES"`. VectorCraft's own rules: `print` writes the file `jobOptions.file` names, checked as `saveAs` checks its file: PostScript when the name ends with `.ps` or `postScriptLevel` is - assigned, a print-ready PDF otherwise. Without a file it throws `Printing to a printer is not available to scripts - yet`, and `app.printerList` throws an error that says it is not available yet. `fitToPage` set to true wins over - the scale factors and the tiling mode. With `printAllArtboards` false, `artboardRange` picks the artboards, and - without a range every artboard prints. With one of `horizontalScale` and `verticalScale` assigned, the other keeps - the document's saved value. `print` throws before anything is written when an assigned `artboardRange` names an + assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension. Without a + file it throws `Printing to a printer is not available to scripts yet`, and `app.printerList` throws an error + that says it is not available yet. `fitToPage` set to true wins over the scale factors and the tiling mode. With + `printAllArtboards` false, `artboardRange` picks the artboards, and without a range every artboard prints. With + `printAllArtboards` not assigned, an assigned `artboardRange` replaces the saved range, which prints when the + saved settings print a range. When the saved settings, or the preset's, 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 the document's saved value. `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, 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 + 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 out of range, a string longer than 4,096 bytes, an option object of the wrong class or from an earlier run, and a From 141dc48e1a111642dc76631b54dbbc75bfe43efa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:25:50 -0800 Subject: [PATCH 7/7] Scripts: addDocument and addDocumentNoUI count for print, docs name the preset base The script checker reports `print` on a document that `documents.addDocument()` or `documents.addDocumentNoUI()` returns, with or without `app.`, as a file write, as it does for `documents.add()`. Both methods return a Document on the Documents help page. docs/mcp.md and the print module's notes say that with `printPreset` assigned, `print` starts from the preset's settings: an assigned `artboardRange` replaces that range, and an unassigned scale factor keeps the preset's value. --- crates/engine/src/script/dom/print.rs | 16 ++++++++++------ crates/scriptcheck/src/catalog.rs | 7 ++++++- crates/scriptcheck/src/tests.rs | 15 +++++++++++---- docs/mcp.md | 10 ++++++---- 4 files changed, 33 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 8019ce2583..29d09da58c 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -22,7 +22,8 @@ //! ([`super::super::files`]). PostScript is written when the name ends with `.ps` or //! `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise. Printing to a printer //! from a script is not available yet, so `print` without a file throws an error. -//! - Only the properties a script assigned apply; the others keep the document's print settings +//! - Only the properties a script assigned apply; the others keep the settings `print` starts +//! from: the preset's when `printPreset` is assigned, otherwise the document's print settings //! (`print.setup`), which `print` leaves as they are. A property that was not assigned reads as //! the default its help page gives. //! - A property the help pages list that is not mapped accepts the default its help page gives @@ -30,12 +31,14 @@ //! - `fitToPage` set to true wins over the scale factors and the tiling mode. //! - With `printAllArtboards` set to false, `artboardRange` picks the artboards; without a range //! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange` -//! replaces the saved range, which prints when the saved settings print a range. -//! - An assigned `printArea` prints by artboard when the saved settings, or the preset's, ignore -//! the artboards: the artboards an assigned `artboardRange` names, otherwise each artboard. +//! replaces the range of the settings `print` starts from, which prints when those settings +//! print a range. +//! - An assigned `printArea` prints by artboard when the settings `print` starts from ignore the +//! artboards: the artboards an assigned `artboardRange` names, otherwise each artboard. //! - The format follows the name `jobOptions.file` gives, also when that name is a link to a file //! with another extension. -//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps the saved value. +//! - 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 artboard //! the document does not have, also with `printAllArtboards` true; when `printPreset` or //! `flattenerPreset` is not the name of a preset (any case); when `colorManagementOptions.name` is @@ -715,7 +718,8 @@ fn map_coordinate(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<( job.top.insert("scaling".into(), json!(scaling)); } if scaled && fit != Some(true) { - // Only the assigned factors are sent; with one of them, the other keeps the saved value. + // Only the assigned factors are sent; with one of them, the other keeps its value in the + // base settings (the preset's or the saved ones). let g = job.group("scale"); if let Some(w) = hs { g.insert("width".into(), json!(w)); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index fac0173879..ad3931117a 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -83,7 +83,8 @@ pub(crate) const DOM_PRINT: &str = "print"; // The member chains that give a document, whole and as the chains are written (`[]` for an index, // `()` for a call): https://ai-scripting.docsforadobe.dev/jsobjref/Application/ (`activeDocument`, -// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `getByName`). +// `documents`, `open`) and https://ai-scripting.docsforadobe.dev/jsobjref/Documents/ (`add`, `addDocument`, +// `addDocumentNoUI`, `getByName`). pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "activeDocument", "app.activeDocument", @@ -91,6 +92,10 @@ pub(crate) const DOM_DOCUMENTS: &[&str] = &[ "app.documents[]", "documents.add()", "app.documents.add()", + "documents.addDocument()", + "app.documents.addDocument()", + "documents.addDocumentNoUI()", + "app.documents.addDocumentNoUI()", "documents.getByName()", "app.documents.getByName()", "app.open()", diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 4867b440c3..c833ccb540 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -559,7 +559,8 @@ fn save_as_and_export_file_in_brackets_write_a_file() { } /// A document's `print` writes the file its options' `jobOptions.file` names, called with a dot or -/// with its name in brackets, on a document or a variable that holds one; reading the method without +/// with its name in brackets, on a document (also one `add`, `addDocument` or `addDocumentNoUI` +/// returns) or a variable that holds one; reading the method without /// calling it, and a `print` method of another object, do not. #[test] fn print_writes_a_file() { @@ -572,10 +573,16 @@ fn print_writes_a_file() { "logger.print('hello'); logger['print']('hello');\n", "app.activeDocument.name.concat(logger.print('x'));\n", "app.print(o); app.activeDocument.layers[0]['print'](o); app.documents['print'](o); app.preferences.activeDocument.print(o);\n", - "var e = app.open(new File(p)); e.print(o); activeDocument.print(o);\n", + "var e = app.open(new File(p)); e.print(o);\n", + "activeDocument.print(o);\n", + "documents.addDocument('Print').print(o);\n", + "app.documents.addDocument('Print', s, false).print(o);\n", + "documents.addDocumentNoUI('Print').print(o);\n", + "app.documents.addDocumentNoUI('Print').print(o);\n", )); - assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 5, 9][..])); - assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", &[2, 3, 5, 9][..])]); + let lines = &[2, 3, 5, 9, 10, 11, 12, 13, 14][..]; + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(lines)); + assert_eq!(r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect::>(), [("filesWritten", lines)]); } /// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing diff --git a/docs/mcp.md b/docs/mcp.md index fd15234565..8e55502bac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2736,7 +2736,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot pages do not list are left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default keeps the preset's value. A bad value throws an error before anything is written. - `Document.print(options?)` runs `file.print` on the document, with the options a script assigned over the - document's print settings, which stay as they are, and adds no undo step + document's print settings, or over the preset's when `printPreset` is assigned. The document's print settings + stay as they are, and `print` adds no undo step (https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/). `options` is a `new PrintOptions()`, whose `jobOptions`, `colorManagementOptions`, `colorSeparationOptions`, `coordinateOptions`, `flattenerOptions`, `fontOptions`, `pageMarksOptions`, `paperOptions` and `postScriptOptions` @@ -2763,10 +2764,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot file it throws `Printing to a printer is not available to scripts yet`, and `app.printerList` throws an error that says it is not available yet. `fitToPage` set to true wins over the scale factors and the tiling mode. With `printAllArtboards` false, `artboardRange` picks the artboards, and without a range every artboard prints. With - `printAllArtboards` not assigned, an assigned `artboardRange` replaces the saved range, which prints when the - saved settings print a range. When the saved settings, or the preset's, ignore the artboards, an assigned + `printAllArtboards` not assigned, an assigned `artboardRange` replaces the range of the settings `print` starts + 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 the document's saved value. `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. `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`