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

+11 -6
View File
@@ -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())?;
+8 -1
View File
@@ -206,9 +206,16 @@ pub fn unconfined<T>(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<T>(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<bool> = const { std::cell::Cell::new(false) };
}
+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)
+102
View File
@@ -835,6 +835,84 @@ 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();
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();
@@ -895,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();
+62 -2
View File
@@ -82,7 +82,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]);"
),
@@ -96,7 +97,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.
@@ -447,6 +450,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]
@@ -498,6 +556,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"),
@@ -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.
@@ -75,7 +76,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,7 +84,16 @@ const INSIDE: &[(&str, &str)] = &[
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \
open selection typename userInteractionLevel userInteractionLevel=",
open PPDFileList printPresetsList printerList selection typename userInteractionLevel \
userInteractionLevel=",
),
("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"),
@@ -137,11 +147,93 @@ 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 \
Printer PrinterPostScriptLevelEnum PrintingBounds",
),
("Printer.", "prototype"),
("Printer.prototype.", "constructor name printerInfo printerInfo= typename"),
("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`,
/// the page item types and the save and export option classes.
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
/// and the save and export option classes.
const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \
PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame EPSSaveOptions ExportOptionsJPEG ExportOptionsPNG24 \
ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions";
+14 -4
View File
@@ -286,16 +286,23 @@ 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<usize>) {
let [h0, h1, h2, h3] = self.h;
// `doc['saveAs'](f)` and `app['open'](f)`: a method named by a string literal in brackets.
if is(h0, "]")
&& is(h2, "[")
&& let Some(name) = h1.filter(|s| s.kind == T::Str)
&& let Some(name) = h1.filter(|s| s.kind == T::Str).map(|s| unquote(s.text, 32))
{
let name = unquote(name.text, 32);
if catalog::DOM_FILE_WRITES.contains(&name.as_str()) {
if 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);
} else if catalog::DOM_FILE_READS.contains(&name.as_str()) && self.app_receiver(h3, self.h4) {
@@ -320,7 +327,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|| (catalog::DOM_FILE_READS.contains(&n) && self.app_receiver(h2, h3))
{
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 {
+24
View File
@@ -79,6 +79,30 @@ pub(crate) const DOM_FILE_WRITES: &[&str] = &["exportFile", "saveAs"];
// Application methods that read the file they are given: https://ai-scripting.docsforadobe.dev/jsobjref/Application/
pub(crate) const DOM_FILE_READS: &[&str] = &["open"];
// 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`, `addDocument`,
// `addDocumentNoUI`, `getByName`).
pub(crate) const DOM_DOCUMENTS: &[&str] = &[
"activeDocument",
"app.activeDocument",
"documents[]",
"app.documents[]",
"documents.add()",
"app.documents.add()",
"documents.addDocument()",
"app.documents.addDocument()",
"documents.addDocumentNoUI()",
"app.documents.addDocumentNoUI()",
"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
+27
View File
@@ -577,6 +577,33 @@ fn app_open_reads_a_file() {
assert!(feature(&r, "file.read").is_none());
}
/// 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 (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() {
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);\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",
));
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::<Vec<_>>(), [("filesWritten", lines)]);
}
/// 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]
+62 -7
View File
@@ -234,28 +234,35 @@ 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))
}
/// 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);
@@ -912,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.
@@ -931,6 +966,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]
+32 -15
View File
@@ -2566,7 +2566,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
- `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, on any object that may be a File object; only
`new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out; a
document's `saveAs` or `exportFile` counts too), `filesOpened` (files opened in other apps), `network`,
document's `saveAs` or `exportFile` counts too, and so does `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,
@@ -2641,14 +2643,20 @@ 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/)
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)`
@@ -2675,7 +2683,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,
@@ -2727,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`
@@ -2750,7 +2760,8 @@ 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, and `printerName` does not apply. Without a file, `print` prints to the
assigned, a print-ready PDF otherwise, also when that name is a link to a file with another extension, and
`printerName` does not apply. Without a file, `print` prints to the
printer `printerName` names, or to the system's default printer when it is `""` or not assigned
(https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/). The name must be exactly the name of a printer the
app listed for the run, or `print` throws `PrintOptions.printerName names no installed printer`; with no default
@@ -2765,7 +2776,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot
nothing. Before it sends them, the app checks that each printer is still installed under that name, and sends none
when one is not. A run prepares at most 4 jobs, together at most 100 pages, every copy counted, and 32 MiB, and
none while an earlier run's jobs wait for an answer. A job for a printer is a PDF, so `postScriptLevel` with no
file throws. Where the app lists no printers for scripts (the web, MCP or the command line without the app),
file throws. Where the app lists no printers for scripts (the web build, and MCP or the command line without the app),
`print` with no file throws `Printing to a printer is not available here`. `app.printerList` gives a `Printer` for
each printer the app listed for the run, at most 256, leaving out names longer than 512 bytes or with a control
character (https://ai-scripting.docsforadobe.dev/jsobjref/Application/,
@@ -2773,16 +2784,20 @@ app through the global object `vc`, and writes to the Script Console and runs ot
error that says it is not available yet. With no document open, `app.printerList` throws `Application.printerList
needs an open document`, as the Printer help page describes, and where the app lists no printers for scripts it
throws `Application.printerList is not available here`. A printer name is only compared with the listed names: it
is never read as a path, a URL or a command. `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
is never read as a path, a URL or a command. `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 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 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`
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. `PPDName` takes 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.
`PPDName` takes 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
@@ -9228,7 +9243,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
+1 -1
View File
@@ -1030,7 +1030,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/ and https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ describe, and read and write only where the script's `File` objects may (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print, which takes no click for the first second, nothing is sent from a failed run, and the web, MCP and the command line cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.