Merge feat/scripts-api-d10-print-options into feat/scripts-print-printer

This commit is contained in:
dotCooCoo committed 2026-11-22 01:08:19 -08:00
commit 619ccb2a34
13 files changed
+616 -86

No files matched your search

+127 -28
View File
@@ -88,8 +88,8 @@ 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<Coords>,
@@ -99,6 +99,7 @@ pub(super) struct State {
save_options: save_open::State,
/// The print option objects ([`print`]).
printing: print::State,
presets: RefCell<Vec<Vec<(String, Data)>>>,
}
impl State {
@@ -891,10 +892,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"] {
@@ -931,23 +935,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
/// <https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/> 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<usize> {
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<Data>| {
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<Data>| {
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 ----
@@ -1185,19 +1267,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<u64> = 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<u64> = 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::<Vec<_>>().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::<Vec<_>>().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::<Vec<_>>()})))?;
}
@@ -1314,17 +1403,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::<Vec<_>>()})))?;
Ok(Data::Undefined)
}
/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the
@@ -1456,17 +1543,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";
@@ -1743,11 +1839,14 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
application.extend(print::application_members(l));
let preset = {
let l = link.clone();
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
current(&l)?.charge_call(64)?;
new_preset(&a)
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
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),
+49 -17
View File
@@ -29,23 +29,31 @@
//! prepares at most [`MAX_JOBS`] jobs, of at most [`MAX_SHEETS`] sheets and [`MAX_JOB_BYTES`]
//! together, and none while jobs of an earlier run still wait. A job for a printer is a PDF, so
//! `postScriptLevel` applies only to a file.
//! - 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
//! 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.
//! - With one of `horizontalScale` and `verticalScale` assigned, the other keeps the saved value.
//! every artboard prints. With `printAllArtboards` not assigned, an assigned `artboardRange`
//! 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 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
//! 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. `PPDName` takes only the empty string.
//! 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. `PPDName` takes only the empty string.
//! - A run makes at most [`MAX_OPTION_OBJECTS`] option objects.
//! - `app.printerList` lists the printers the frontend listed for the run as `Printer` objects,
//! whose `name` is read-only and whose `printerInfo` is not available yet. It throws with no
@@ -537,6 +545,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<String, Value>,
groups: Vec<(&'static str, Map<String, Value>)>,
@@ -664,7 +674,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,
_ => {}
}
}
@@ -741,7 +759,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));
@@ -749,10 +768,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 {
@@ -869,6 +886,9 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
let path = file_path(&file, "print")?;
let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?;
let mut p = print_params(&mut job);
// 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" }));
p.insert("path".into(), json!(plain(real)));
let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command(h, PRINT, &Value::Object(p)))))?;
// What the job lost or how its options apply: one Script Console line each.
@@ -899,7 +919,6 @@ fn print_params(job: &mut Job) -> Map<String, Value> {
p.insert("preset".into(), json!(preset));
}
if let Some(level) = job.level {
p.insert("format".into(), json!("postscript"));
p.insert("level".into(), json!(level));
}
let settings = job.settings();
@@ -976,18 +995,27 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> 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() {
@@ -1026,11 +1054,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)