Scripts: Document.print sends to a printer after the run and the person's approval, and app.printerList lists printers

Document.print without jobOptions.file now prints to the printer that
PrintOptions.printerName names, or to the default printer. A run started
in the app gets a bounded list of the print service's printer names
(at most 256, names up to 512 bytes, no control characters), and
app.printerList gives a Printer object for each. A name must match a
listed printer exactly.

print composes each job as a print-ready PDF and holds it until the
run ends. When the run's changes are kept, a dialog lists each job's
document, printer and pages, and only the person at the keyboard can
choose Print: ui.dialog.confirm and synthetic input are refused. Cancel
drops the jobs. A failed or stopped run sends nothing, and no job is
sent if one of its printers is no longer installed. A run prepares at
most 4 jobs, 100 pages and 32 MiB, and pages are counted before a job
is composed. The web, MCP and the command line cannot print to a
printer from a script.

Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-21 20:51:08 -08:00
1 parent 1b429b586e
commit b965a3ef1f
17 files changed
+902 -51

No files matched your search

+3
View File
@@ -28,6 +28,9 @@ impl PrintService for SystemPrint {
fn setup(&mut self, printer: Option<&str>) -> Result<(), String> {
system::setup(printer)
}
fn scripts_may_print(&self) -> bool {
true
}
}
/// The status after the job `title` went to `printer` (the default one without a name), with the
+6
View File
@@ -315,6 +315,12 @@ pub struct Session {
/// [`script::refused_to_scripts`] while it is set: `file.print` for `Document.print`, after the
/// member checked its options and its file.
pub(crate) script_unfenced: Option<&'static str>,
/// The printers the frontend lists for the next run, which takes them: `app.printerList` and
/// `Document.print` to a printer read them. `None`: scripts cannot print to a printer here.
pub script_printers: Option<script::printing::Printers>,
/// The jobs the last run that printed to a printer prepared, until the frontend takes them
/// ([`Session::take_script_prints`]).
pub(crate) script_prints: Vec<script::printing::PreparedPrint>,
/// Write recovery copies of the unsaved documents before a run, and don't start without them.
pub script_copy_first: bool,
/// While the active tool's actions run: their commands aren't "a command from outside the
+12 -1
View File
@@ -35,7 +35,7 @@ use serde_json::{Value, json};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session};
mod print;
@@ -106,6 +106,17 @@ impl State {
pub(super) fn saving(&self) -> bool {
self.saving.get()
}
/// Gives the run the printers the frontend listed (`None`: none can be printed to here), and
/// whether jobs an earlier run prepared still wait.
pub(super) fn start_printing(&self, printers: Option<super::printing::Printers>, waiting: bool) {
self.printing.start(printers, waiting);
}
/// The jobs the run prepared for a printer, which the run no longer holds.
pub(super) fn take_prints(&self) -> Vec<super::printing::PreparedPrint> {
self.printing.take_jobs()
}
}
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
+199 -39
View File
@@ -18,10 +18,17 @@
//! into `file.print`'s settings before anything is written.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `print` writes a file: `jobOptions.file` names it, a `File` the script may write
//! ([`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.
//! - `print` with `jobOptions.file` writes a file, a `File` the script may write
//! ([`super::super::files`]), and `printerName` does not apply. PostScript is written when the
//! name ends with `.ps` or `postScriptOptions.postScriptLevel` is set, a print-ready PDF otherwise.
//! - `print` without a file prepares a job for the printer `printerName` names, or for the
//! system's default printer when it is empty or not assigned ([`super::super::printing`]): a
//! print-ready PDF composed when `print` is called, which the run keeps until it ends. A name
//! must be exactly the name of a printer the frontend listed for the run. Where the frontend lists
//! no printers for scripts (the web, a run without the app), `print` without a file throws. A run
//! 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
//! (`print.setup`), which `print` leaves as they are. A property that was not assigned reads as
//! the default its help page gives.
@@ -38,23 +45,26 @@
//! 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
//! string.
//! `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` is not available yet, and `app.PPDFileList` is empty: VectorCraft prints
//! without PPD files.
//! - `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
//! document open, as the help page <https://ai-scripting.docsforadobe.dev/jsobjref/Printer/>
//! describes, and where the frontend lists no printers for scripts. `app.PPDFileList` is empty:
//! VectorCraft prints without PPD files.
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_color::cms;
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref, host_ref_parts};
use super::super::printing::{MAX_JOB_BYTES, MAX_JOBS, MAX_SHEETS, PreparedPrint, Printers};
use super::save_open::{exactly, file_path, plain, refused};
use super::{
Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, command, current, float, get, given, later, method, named, num, on_doc, text, this_doc,
whole, with_doc,
Answer, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, command, command_kept, current, float, get, given, later, method, named, num, on_doc,
text, this_doc, whole, with_doc,
};
use crate::cmd::flatten::FlattenOptions;
@@ -62,16 +72,44 @@ use crate::cmd::flatten::FlattenOptions;
pub const MAX_OPTION_OBJECTS: usize = 256;
/// The largest scale factor `file.print` takes, in percent.
pub const MAX_PRINT_SCALE: f64 = 1000.0;
/// The error of `print` without `jobOptions.file`.
pub const NO_PRINTER: &str = "Printing to a printer is not available to scripts yet: set jobOptions.file to print to a file";
/// The error of `print` without `jobOptions.file` where the frontend lists no printers for scripts.
pub const NO_PRINTER: &str = "Printing to a printer is not available here: set jobOptions.file to print to a file";
/// The error of `app.printerList` where the frontend lists no printers for scripts.
pub const NO_PRINTERS: &str = "Application.printerList is not available here";
/// The error of `app.printerList` with no document open.
pub const PRINTERS_NEED_DOCUMENT: &str = "Application.printerList needs an open document";
/// The error of `print` to the default printer when the system names none.
pub const NO_DEFAULT_PRINTER: &str = "There is no default printer: set PrintOptions.printerName";
/// The error of `print` to a printer while jobs an earlier run prepared wait.
pub const PRINT_WAITING: &str = "A print job from an earlier script still waits for approval";
/// The error of `print` to a printer with `postScriptLevel` assigned.
pub const POSTSCRIPT_TO_FILE: &str = "PostScript prints only to a file: set jobOptions.file";
/// The error for an option object from an earlier run.
pub const STALE_OPTIONS: &str = "Stale print options";
/// The error for a `Printer` object from an earlier run.
pub const STALE_PRINTER: &str = "Stale printer";
/// The option objects of the run: each one's class, as an index into [`CLASSES`], and the
/// properties the script assigned.
/// properties the script assigned; the printers the frontend listed for the run, and the jobs the
/// run prepared for them.
#[derive(Default)]
pub(in crate::script) struct State {
objects: RefCell<Vec<Options>>,
printers: RefCell<Option<Printers>>,
/// Jobs an earlier run prepared wait to be sent or dropped.
waiting: Cell<bool>,
jobs: RefCell<Vec<PreparedPrint>>,
}
impl State {
pub(in crate::script) fn start(&self, printers: Option<Printers>, waiting: bool) {
*self.printers.borrow_mut() = printers;
self.waiting.set(waiting);
}
pub(in crate::script) fn take_jobs(&self) -> Vec<PreparedPrint> {
std::mem::take(&mut *self.jobs.borrow_mut())
}
}
struct Options {
@@ -209,7 +247,7 @@ const PRINT_OPTIONS: Class = Class {
f("paperOptions", Kind::Child("PrintPaperOptions"), Start::None),
f("postScriptOptions", Kind::Child("PrintPostScriptOptions"), Start::None),
kept("PPDName", Kind::Text, Start::Text("")),
kept("printerName", Kind::Text, Start::Text("")),
f("printerName", Kind::Text, Start::Text("")),
f("printPreset", Kind::Text, Start::None),
],
};
@@ -485,6 +523,8 @@ fn property(link: &Link, class: usize, field: usize) -> HostMember {
struct Job {
preset: Option<String>,
file: Option<Data>,
/// The assigned `printerName`.
printer: Option<String>,
level: Option<u64>,
/// The assigned `artboardRange`, checked whether or not it picks the artboards.
range: Option<String>,
@@ -567,6 +607,7 @@ fn map_options(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(),
match k {
"flattenerPreset" => job.flattener = Some(string_of(&v)),
"printPreset" => job.preset = Some(string_of(&v)),
"printerName" => job.printer = Some(string_of(&v)),
"jobOptions" => map_job(h, child_slot(h, &v, JOB.name)?, job),
"colorManagementOptions" => map_color(h, child_slot(h, &v, COLOR.name)?, job),
"colorSeparationOptions" => map_separation(h, child_slot(h, &v, SEPARATION.name)?, job),
@@ -811,7 +852,8 @@ fn map_postscript(h: &Host, slot: usize, job: &mut Job) {
}
/// `document.print(options?)`: `file.print` of the document to the file `jobOptions.file` names,
/// with the assigned options over the document's print settings.
/// with the assigned options over the document's print settings, or without a file the job for a
/// printer ([`prepare`]).
fn doc_print(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let mut job = Job::default();
@@ -822,10 +864,36 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
})?;
map_options(h, slot, &mut job)?;
}
let Some(file) = job.file.take() else { return Err(HostError::Error(NO_PRINTER.into())) };
let Some(file) = job.file.take() else { return prepare(h, doc, job) };
check_names(h, doc, &mut job)?;
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);
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.
let warnings = match &printed {
Data::Object(fields) => fields.iter().find(|(k, _)| k == "warnings").map(|(_, v)| v),
_ => None,
};
if let Some(Data::Array(warnings)) = warnings {
for w in warnings.iter().take(MAX_LISTED) {
if let Data::String(w) = w {
console_warning(h, w);
}
}
}
Ok(Data::Undefined)
}
/// Writes `file.print`'s warning `w` to the Script Console.
fn console_warning(h: &Host, w: &str) {
super::super::each_line(&format!("Document.print: {w}"), |line, cut| h.line(super::super::console::Entry::Output(line), cut));
}
/// `file.print`'s params for `job`, without a path: the print preset, the PostScript level and the
/// settings.
fn print_params(job: &mut Job) -> Map<String, Value> {
let mut p = Map::new();
if let Some(preset) = job.preset.take() {
p.insert("preset".into(), json!(preset));
@@ -838,20 +906,67 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer {
if !settings.is_empty() {
p.insert("settings".into(), Value::Object(settings));
}
p.insert("path".into(), json!(plain(real)));
let printed = exactly(h, || on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, &Value::Object(p))))?;
// What the job lost or how its options apply: one Script Console line each.
let warnings = match &printed {
Data::Object(fields) => fields.iter().find(|(k, _)| k == "warnings").map(|(_, v)| v),
_ => None,
p
}
/// `document.print(options?)` without `jobOptions.file`: the job for the printer `printerName`
/// names, or for the system's default printer, as `file.print` composes it now. The run keeps it,
/// and the session takes it only when the run's changes are kept ([`super::super::printing`]).
/// Everything is checked before the job is composed, and its size after.
fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer {
let state = &h.dom.printing;
let (printer, for_printer) = {
let printers = state.printers.borrow();
let Some(printers) = printers.as_ref() else { return Err(HostError::Error(NO_PRINTER.into())) };
let printer = match job.printer.take().filter(|n| !n.is_empty()) {
Some(name) if printers.has(&name) => name,
Some(name) => return Err(HostError::Error(format!("PrintOptions.printerName names no installed printer: {name}"))),
None => printers.default_name().map(str::to_string).ok_or_else(|| HostError::Error(NO_DEFAULT_PRINTER.into()))?,
};
(printer, printers.for_printer)
};
if let Some(Data::Array(warnings)) = warnings {
for w in warnings.iter().take(MAX_LISTED) {
if let Data::String(w) = w {
super::super::each_line(&format!("Document.print: {w}"), |line, cut| h.line(super::super::console::Entry::Output(line), cut));
}
if state.waiting.get() {
return Err(HostError::Error(PRINT_WAITING.into()));
}
if job.level.is_some() {
return Err(HostError::Error(POSTSCRIPT_TO_FILE.into()));
}
let (count, sheets, bytes) = {
let jobs = state.jobs.borrow();
(jobs.len(), jobs.iter().map(|j| j.sheets).sum::<u64>(), jobs.iter().map(|j| j.pdf.len()).sum::<usize>())
};
if count >= MAX_JOBS {
return Err(HostError::Range(format!("a script can print at most {MAX_JOBS} jobs to a printer in a run")));
}
check_names(h, doc, &mut job)?;
let mut p = print_params(&mut job);
if for_printer {
p.insert("forPrinter".into(), json!(true));
}
// The pages are counted from the layout before the job is composed.
let plan: serde_json::Map<String, Value> =
p.iter().filter(|(k, _)| matches!(k.as_str(), "preset" | "settings")).map(|(k, v)| (k.clone(), v.clone())).collect();
let planned = on_doc(h, doc.uid, false, |h| unfenced(h, PREVIEW, || command_kept(h, PREVIEW, &Value::Object(plan))))?;
let pages = planned.get("pages").and_then(Value::as_u64).unwrap_or(0);
sheets_fit(sheets, pages)?;
let printed = on_doc(h, doc.uid, false, |h| unfenced(h, PRINT, || command_kept(h, PRINT, &Value::Object(p))))?;
let pdf = printed
.get("dataBase64")
.and_then(Value::as_str)
.and_then(vectorcraft_format::base64_decode)
.ok_or_else(|| HostError::Error("the print job has no data".into()))?;
let pages = printed.get("pages").and_then(Value::as_u64).unwrap_or(pages);
sheets_fit(sheets, pages)?;
if bytes.saturating_add(pdf.len()) > MAX_JOB_BYTES {
return Err(HostError::Range("a script's printer jobs can hold at most 32 MiB in a run".into()));
}
for w in printed.get("warnings").and_then(Value::as_array).into_iter().flatten().take(MAX_LISTED) {
if let Some(w) = w.as_str() {
console_warning(h, w);
}
}
let title = with_doc(h, doc, |_, st| st.title());
state.jobs.borrow_mut().push(PreparedPrint { printer, title, pdf, sheets: pages });
Ok(Data::Undefined)
}
@@ -921,13 +1036,24 @@ fn plain_name<'a>(what: &str, kind: &str, name: &'a str) -> std::result::Result<
Ok(n)
}
const PRINT: &str = "file.print";
/// The error when a job of `pages` sheets would take a run's jobs past [`MAX_SHEETS`], after
/// `sheets` in earlier jobs.
fn sheets_fit(sheets: u64, pages: u64) -> std::result::Result<(), HostError> {
if sheets.saturating_add(pages) > MAX_SHEETS {
return Err(HostError::Range(format!("a script's printer jobs can hold at most {MAX_SHEETS} sheets in a run; this job has {pages}")));
}
Ok(())
}
/// Runs `id`, which scripts may not run through `vc.run`, for a member that checked its params:
/// only `id` passes the fence, and only for this one command.
fn unfenced(h: &Host, id: &'static str, params: &Value) -> Answer {
const PRINT: &str = "file.print";
/// Counts a job's pages without composing it.
const PREVIEW: &str = "print.preview";
/// Runs `run`, which runs `id`, a command scripts may not run through `vc.run`, for a member that
/// checked its params: only `id` passes the fence, and only while `run` runs.
fn unfenced<T>(h: &Host, id: &'static str, run: impl FnOnce() -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
h.session.borrow_mut().script_unfenced = Some(id);
let r = command(h, id, params);
let r = run();
h.session.borrow_mut().script_unfenced = None;
r
}
@@ -942,11 +1068,39 @@ fn app_ppd_files(_: &Host, _: &[Data]) -> Answer {
Ok(Data::Array(Vec::new()))
}
/// `app.printerList`: a `Printer` for each printer the frontend listed for the run.
fn app_printers(h: &Host, _: &[Data]) -> Answer {
if h.session.borrow().active().is_none() {
return Err(HostError::Error(PRINTERS_NEED_DOCUMENT.into()));
}
let printers = h.dom.printing.printers.borrow();
let printers = printers.as_ref().ok_or_else(|| HostError::Error(NO_PRINTERS.into()))?;
let count = u64::try_from(printers.names().len()).unwrap_or(0);
Ok(Data::Array((0..count).map(|i| host_ref(PRINTER, &[float(h.run), float(i)])).collect()))
}
const PRINTER: &str = "Printer";
/// `printer.name`: the name the frontend listed for the printer.
fn printer_name(h: &Host, a: &[Data]) -> Answer {
let wrong = || HostError::Type("this is not a Printer".into());
let (class, handle) = host_ref_parts(arg(a, 0)).ok_or_else(wrong)?;
if class != PRINTER {
return Err(wrong());
}
let [run, index] = handle.as_slice() else { return Err(wrong()) };
let stale = || HostError::Error(STALE_PRINTER.into());
if whole(*run) != Some(h.run) {
return Err(stale());
}
let index = whole(*index).and_then(|i| usize::try_from(i).ok()).ok_or_else(stale)?;
let printers = h.dom.printing.printers.borrow();
printers.as_ref().and_then(|p| p.names().get(index)).map(|n| text(n.clone())).ok_or_else(stale)
}
/// The members these add to `Application`.
pub(super) fn application_members(l: &Link) -> Vec<(String, HostMember)> {
let mut members = named(vec![("printPresetsList", get(l, app_presets)), ("PPDFileList", get(l, app_ppd_files))]);
members.push(later(l, "Application", "printerList"));
members
named(vec![("printPresetsList", get(l, app_presets)), ("PPDFileList", get(l, app_ppd_files)), ("printerList", get(l, app_printers))])
}
/// The members these add to `Document`.
@@ -954,9 +1108,10 @@ pub(super) fn document_members(l: &Link) -> Vec<(String, HostMember)> {
named(vec![("print", method(l, doc_print))])
}
/// The option classes: each `new Name()` gives a new option object with nothing assigned.
/// The option classes: each `new Name()` gives a new option object with nothing assigned. And
/// `Printer`, whose objects only `app.printerList` gives.
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
CLASSES
let mut classes: Vec<HostClass> = CLASSES
.iter()
.enumerate()
.map(|(index, c)| {
@@ -970,5 +1125,10 @@ pub(super) fn classes(link: &Link) -> Vec<HostClass> {
members.extend(c.fields.iter().enumerate().map(|(i, field)| (field.name.to_string(), property(link, index, i))));
HostClass { name: c.name.into(), parent: None, members, index: None, construct: Some(construct) }
})
.collect()
.collect();
let mut printer = named(vec![("name", get(link, printer_name))]);
printer.insert(0, ("typename".to_string(), super::typename_of(PRINTER)));
printer.push(later(link, PRINTER, "printerInfo"));
classes.push(HostClass { name: PRINTER.into(), parent: None, members: printer, index: None, construct: None });
classes
}
+45 -1
View File
@@ -47,12 +47,17 @@
//! run. An engine keeps no document and no run: its host functions reach the run through a link
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
//! documents back and keeps the engine's globals; an internal error drops the engine.
//!
//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run
//! only after the run's changes are kept, for the frontend to send once the person approves them
//! ([`printing`]).
pub mod console;
pub mod dialogs;
pub mod dollar;
pub mod dom;
pub mod include;
pub mod printing;
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
@@ -1309,6 +1314,17 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
command_crossing(host, id, params, true).map(|(data, value)| (data.unwrap_or(Data::Undefined), value))
}
/// [`command`] for a member that keeps the command's result itself: the result does not cross to
/// the script, so it is not held to the limits of a crossing. → the result as the command gave it.
fn command_kept(host: &Host, id: &str, params: &Value) -> std::result::Result<Value, HostError> {
command_crossing(host, id, params, false).map(|(_, value)| value)
}
/// [`command_value`], with the script's copy of the result made only when `cross` is true.
fn command_crossing(host: &Host, id: &str, params: &Value, cross: bool) -> std::result::Result<(Option<Data>, Value), HostError> {
let id = id.to_string();
let params = params.clone();
let session = host.session.clone();
@@ -1332,10 +1348,13 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
Err(e) => return Err(HostError::Error(e.to_string())),
};
let crossed = host.charge_growth(objects, added).and_then(|()| {
if !cross {
return Ok(None);
}
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
host.charge_call(data_size(&data))?;
Ok(data)
Ok(Some(data))
});
// A command whose result does not reach the script is put back, like one that failed.
if let Some(save) = save {
@@ -1786,6 +1805,22 @@ impl Session {
self.script_report.as_ref()
}
/// Whether jobs a run prepared for a printer wait to be sent or dropped ([`printing`]).
pub fn script_prints_waiting(&self) -> bool {
!self.script_prints.is_empty()
}
/// The jobs that wait, as [`Self::take_script_prints`] would give them.
pub fn script_prints(&self) -> &[printing::PreparedPrint] {
&self.script_prints
}
/// The jobs the last run that printed to a printer prepared, which the session no longer holds:
/// the frontend sends them or drops them ([`printing`]).
pub fn take_script_prints(&mut self) -> Vec<printing::PreparedPrint> {
std::mem::take(&mut self.script_prints)
}
/// The Script Console: the lines of this session's runs, oldest first.
pub fn script_console(&self) -> &console::Console {
&self.script_console
@@ -2066,6 +2101,9 @@ impl Session {
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::default(),
});
// The printers the frontend listed are this run's alone, and a run may not print while
// jobs an earlier run prepared still wait for the person.
host.dom.start_printing(self.script_printers.take(), !self.script_prints.is_empty());
*link.borrow_mut() = Some(host.clone());
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
Ok(args) => args,
@@ -2290,6 +2328,12 @@ impl Session {
"hostCalls": host.calls.get(),
});
host.more_written(&mut report);
// The jobs it prepared for a printer wait for the frontend now that its changes are kept.
let prints = host.dom.take_prints();
if !prints.is_empty() {
report["prints"] = json!(prints.len());
self.script_prints = prints;
}
close_run(self, host, &mut report, console::Ending::Finished);
self.end_job(job, false);
self.script_report = Some(report.clone());
+85
View File
@@ -0,0 +1,85 @@
//! Printing to a printer from a script: the printers a frontend lists for a run ([`Printers`]),
//! which `app.printerList` and `PrintOptions.printerName` read, and the jobs `Document.print`
//! prepares ([`PreparedPrint`]).
//!
//! A run that prints to a printer sends nothing while it runs: each job is composed in memory and
//! kept with the run. When the run fails or is stopped, its jobs are dropped with its changes. When
//! it ends and its changes are kept, the session holds its jobs ([`crate::Session::take_script_prints`])
//! for the frontend, which sends them only when the person at the computer approves them.
//!
//! A printer name is only a key into the list the frontend gave: it never becomes a path, a URL or
//! a command line.
//!
//! The limits are VectorCraft's own: [`MAX_PRINTERS`], [`MAX_PRINTER_NAME_BYTES`], [`MAX_JOBS`],
//! [`MAX_SHEETS`] and [`MAX_JOB_BYTES`].
/// The most printers a run lists.
pub const MAX_PRINTERS: usize = 256;
/// The longest printer name a run lists, in bytes.
pub const MAX_PRINTER_NAME_BYTES: usize = 512;
/// The most printer jobs one run prepares.
pub const MAX_JOBS: usize = 4;
/// The most sheets of paper the jobs of one run hold together, every copy counted.
pub const MAX_SHEETS: u64 = 100;
/// The most bytes the jobs of one run hold together.
pub const MAX_JOB_BYTES: usize = 32 << 20;
/// The printers a frontend lists for a run, by name, with the system's default printer.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Printers {
names: Vec<String>,
default: Option<usize>,
/// The printer turns no landscape page to fit its paper: jobs are written upright
/// (`file.print`'s `forPrinter`).
pub for_printer: bool,
}
impl Printers {
/// The printers of `list` (name, whether it is the default), in its order. A name that is
/// empty, longer than [`MAX_PRINTER_NAME_BYTES`], holds a control character or repeats an
/// earlier one is left out, and so is every printer after the first [`MAX_PRINTERS`].
pub fn new(list: impl IntoIterator<Item = (String, bool)>, for_printer: bool) -> Self {
let mut names: Vec<String> = Vec::new();
let mut default = None;
for (name, is_default) in list {
if names.len() >= MAX_PRINTERS {
break;
}
if name.is_empty() || name.len() > MAX_PRINTER_NAME_BYTES || name.chars().any(char::is_control) || names.contains(&name) {
continue;
}
if is_default && default.is_none() {
default = Some(names.len());
}
names.push(name);
}
Self { names, default, for_printer }
}
/// The printers' names.
pub fn names(&self) -> &[String] {
&self.names
}
/// The system's default printer, when the list holds it.
pub fn default_name(&self) -> Option<&str> {
self.default.map(|i| self.names[i].as_str())
}
/// Whether the list holds a printer named exactly `name`.
pub fn has(&self, name: &str) -> bool {
self.names.iter().any(|n| n == name)
}
}
/// A job a run prepared for a printer: a print-ready PDF, every copy in it.
#[derive(Clone, Debug, PartialEq)]
pub struct PreparedPrint {
/// The printer, by the name the run's list gave it.
pub printer: String,
/// The title of the document it prints, the job's name in the print queue.
pub title: String,
pub pdf: Vec<u8>,
/// The sheets of paper it prints, every copy counted.
pub sheets: u64,
}
+2
View File
@@ -167,6 +167,8 @@ impl Session {
script_high_water: Default::default(),
script_in_run: false,
script_unfenced: None,
script_printers: None,
script_prints: Vec::new(),
script_copy_first: cfg!(target_arch = "wasm32"),
}
}
+179 -4
View File
@@ -5,6 +5,7 @@ use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::script::printing::{MAX_PRINTER_NAME_BYTES, MAX_PRINTERS, PreparedPrint, Printers};
use crate::*;
const DENIED: &str = "Script file access denied";
@@ -111,6 +112,8 @@ fn print_writes_the_file_with_the_assigned_options_over_the_saved_settings() {
let _ = std::fs::remove_dir_all(base);
}
/// Without the printers a frontend lists for scripts (a run outside the app, the web), printing to
/// a printer and `app.printerList` throw, and nothing is prepared.
#[test]
fn print_without_a_file_does_not_print() {
let base = folder("no-file");
@@ -119,12 +122,186 @@ fn print_without_a_file_does_not_print() {
"app.activeDocument.print();",
"app.activeDocument.print(new PrintOptions());",
"var o = new PrintOptions(); o.jobOptions.copies = 2; app.activeDocument.print(o);",
"var o = new PrintOptions(); o.printerName = 'Office'; app.activeDocument.print(o);",
] {
let e = failure(&mut s, &base, case);
assert!(e.contains("Printing to a printer is not available to scripts yet"), "{case}: {e}");
assert!(e.contains("Printing to a printer is not available here"), "{case}: {e}");
}
let e = failure(&mut s, &base, "app.printerList;");
assert!(e.contains("Application.printerList is not available yet"), "{e}");
assert!(e.contains("Application.printerList is not available here"), "{e}");
assert!(!s.script_prints_waiting());
let _ = std::fs::remove_dir_all(base);
}
/// The printers a frontend lists, `Office` the default, with a name a shell or a file system would
/// read as more than a name.
const ODD_NAME: &str = "Lab; rm -rf / & \\\\srv\\q $(x) ../p";
fn printers() -> Printers {
Printers::new([("Office".to_string(), true), (ODD_NAME.to_string(), false)], false)
}
/// The PDF pages a prepared job holds.
fn job_pages(job: &PreparedPrint) -> usize {
vectorcraft_pdf::info(&job.pdf, None).unwrap().pages.len()
}
/// `app.printerList` gives a `Printer` for each printer the frontend listed, at most 256 of them,
/// without names that are empty, too long, hold a control character or repeat; the list is the
/// run's own, needs an open document, and its objects go stale after the run.
#[test]
fn printer_list_is_the_bounded_list_the_frontend_gave() {
let base = folder("printer-list");
let mut s = session(&base);
let mut list: Vec<(String, bool)> = (0..300).map(|i| (format!("Printer {i}"), i == 1)).collect();
list.insert(0, ("x".repeat(MAX_PRINTER_NAME_BYTES + 1), true));
list.insert(1, ("Bad\nName".into(), false));
list.insert(2, (String::new(), false));
list.insert(3, ("Printer 5".into(), false));
let snapshot = Printers::new(list, false);
assert_eq!(snapshot.names().len(), MAX_PRINTERS);
assert_eq!(snapshot.default_name(), Some("Printer 1"));
s.script_printers = Some(snapshot);
let out = logged(
&mut s,
&base,
"#targetengine keep\nvar l = app.printerList; held = l[0];\n\
vc.log([l.length, l[0].name, l[0].typename, l[1].name, l[255].name]);\n\
try { l[0].name = 'Other'; } catch (e) {} vc.log(l[0].name);\n\
try { l[0].printerInfo; } catch (e) { vc.log(e.message); }",
);
assert_eq!(out[0], json!([256, "Printer 5", "Printer", "Printer 0", "Printer 255"]));
assert_eq!(out[1], json!("Printer 5"), "name is read-only");
assert_eq!(out[2], json!("Printer.printerInfo is not available yet"));
// The next run has no list unless the frontend gives one again.
let e = failure(&mut s, &base, "app.printerList;");
assert!(e.contains("Application.printerList is not available here"), "{e}");
s.script_printers = Some(printers());
let e = failure(&mut s, &base, "#targetengine keep\nheld.name;");
assert!(e.contains("Stale printer"), "{e}");
s.script_printers = Some(printers());
assert_eq!(logged(&mut s, &base, "vc.log(app.printerList[1].name);")[0], json!(ODD_NAME));
// With no document open there is no list.
let mut empty = Session::new();
empty.attach_script_data(base.join("settings/Script Data"));
empty.script_printers = Some(printers());
let e = failure(&mut empty, &base, "app.printerList;");
assert!(e.contains("Application.printerList needs an open document"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// `print` without a file prepares a print-ready PDF for the printer it names, or the default one,
/// and sends nothing: the session holds the jobs once the run's changes are kept, for the frontend
/// to take. A name is matched exactly, whatever characters it holds.
#[test]
fn print_to_a_printer_holds_the_job_until_the_run_ends() {
let base = folder("prepared");
let mut s = session(&base);
s.script_printers = Some(printers());
let name = serde_json::to_string(ODD_NAME).unwrap();
let report = run(
&mut s,
&base,
&format!(
"var o = new PrintOptions(); o.printerName = {name}; o.jobOptions.copies = 2; o.jobOptions.collate = true;\n\
app.activeDocument.print(o);\n\
vc.run('shape.rectangle', {{x: 150, y: 10, width: 20, height: 20}});\n\
app.activeDocument.print();"
),
)
.unwrap();
assert_eq!(report["prints"], 2, "{report}");
assert!(s.script_prints_waiting());
let title = s.active().unwrap().title();
let jobs = s.take_script_prints();
assert!(!s.script_prints_waiting());
assert_eq!(jobs.len(), 2);
assert_eq!((jobs[0].printer.as_str(), jobs[0].sheets, job_pages(&jobs[0])), (ODD_NAME, 4, 4), "two artboards, two copies");
assert_eq!((jobs[1].printer.as_str(), jobs[1].sheets, job_pages(&jobs[1])), ("Office", 2, 2), "the default printer");
assert!(jobs.iter().all(|j| j.title == title && j.pdf.starts_with(b"%PDF")));
assert_ne!(jobs[0].pdf, jobs[1].pdf, "each job holds the document as it was when print was called");
assert!(s.take_script_prints().is_empty(), "a job is taken once");
let _ = std::fs::remove_dir_all(base);
}
/// A run that throws, runs out of fuel or ends at a failed command keeps no job.
#[test]
fn a_run_that_fails_keeps_no_print_job() {
let base = folder("rollback");
let mut s = session(&base);
let objects = s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len);
for case in [
"app.activeDocument.print(); throw new Error('late');",
"app.activeDocument.print(); vc.run('no.such.command', {});",
"app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print(); app.activeDocument.print();",
] {
s.script_printers = Some(printers());
failure(&mut s, &base, case);
assert!(!s.script_prints_waiting(), "{case}");
}
s.script_printers = Some(printers());
let stopped = s.execute("script.run", &json!({"source": "app.activeDocument.print(); while (true) {}", "name": "t.js", "maxFuel": 2_000_000}));
assert!(stopped.is_err());
assert!(s.take_script_prints().is_empty());
assert_eq!(s.active().unwrap().doc.layers[0].children().map_or(0, Vec::len), objects);
let _ = std::fs::remove_dir_all(base);
}
/// A name that is not exactly a listed printer's, a list with no default, PostScript, more jobs or
/// sheets than a run may prepare and jobs an earlier run left waiting all throw, and nothing is
/// prepared; a file wins over a printer name.
#[test]
fn print_to_a_printer_refuses_what_it_cannot_send() {
let base = folder("refuse");
let mut s = session(&base);
let dir = data_folder(&mut s, &base);
let cases = [
("o.printerName = 'office';", "PrintOptions.printerName names no installed printer: office"),
("o.printerName = 'Offic';", "names no installed printer: Offic"),
("o.printerName = ' Office';", "names no installed printer: Office"),
("o.printerName = 'Office\\n';", "names no installed printer"),
("o.postScriptOptions.postScriptLevel = PrinterPostScriptLevelEnum.PSLEVEL2;", "PostScript prints only to a file"),
("o.jobOptions.copies = 51;", "at most 100 sheets in a run; this job has 102"),
("for (var i = 0; i < 4; i++) app.activeDocument.print(o);", "at most 4 jobs to a printer in a run"),
("o.printPreset = 'Nope';", "printPreset names no print preset"),
];
for (case, part) in cases {
s.script_printers = Some(printers());
let e = failure(&mut s, &base, &format!("var o = new PrintOptions(); {case} app.activeDocument.print(o);"));
assert!(e.contains(part), "{case}: {e}");
assert!(!s.script_prints_waiting(), "{case}");
}
// A job past the sheet limit is refused before it is composed.
s.script_printers = Some(printers());
failure(&mut s, &base, "var o = new PrintOptions(); o.jobOptions.copies = 999; app.activeDocument.print(o);");
let report = s.script_report().unwrap();
let ran: Vec<&str> = report["slowestCommands"].as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
assert_eq!(ran, ["print.preview"], "{report}");
s.script_printers = Some(Printers::new([("Office".to_string(), false)], false));
let e = failure(&mut s, &base, "app.activeDocument.print();");
assert!(e.contains("There is no default printer: set PrintOptions.printerName"), "{e}");
// Jobs an earlier run left waiting: the next run cannot print to a printer until they are taken.
s.script_printers = Some(printers());
logged(&mut s, &base, "app.activeDocument.print();");
s.script_printers = Some(printers());
let e = failure(&mut s, &base, "app.activeDocument.print();");
assert!(e.contains("A print job from an earlier script still waits for approval"), "{e}");
assert_eq!(s.take_script_prints().len(), 1, "the earlier job is kept");
s.script_printers = Some(printers());
logged(&mut s, &base, "app.activeDocument.print();");
assert_eq!(s.take_script_prints().len(), 1);
// A file wins over the printer name.
s.script_printers = Some(printers());
let file = quoted(&dir.join("f.pdf"));
logged(
&mut s,
&base,
&format!(
"Folder.userData; var o = new PrintOptions(); o.printerName = 'Nowhere'; o.jobOptions.file = new File({file}); app.activeDocument.print(o);"
),
);
assert!(dir.join("f.pdf").exists());
assert!(!s.script_prints_waiting());
let _ = std::fs::remove_dir_all(base);
}
@@ -171,8 +348,6 @@ fn options_that_are_not_available_throw() {
let dir = data_folder(&mut s, &base);
let file = format!("j.file = new File({});", quoted(&dir.join("x.pdf")));
let cases = [
("o.printerName = 'Office';", "PrintOptions.printerName is not available yet"),
("o.printerName = '\\\\\\\\server\\\\share';", "PrintOptions.printerName is not available yet"),
("o.PPDName = 'Generic';", "PrintOptions.PPDName is not available yet"),
("o.PPDName = '/etc/cups/ppd/office.ppd';", "PrintOptions.PPDName is not available yet"),
("j.name = 'Job';", "PrintJobOptions.name is not available yet"),
+1 -1
View File
@@ -247,7 +247,7 @@ impl VectorcraftApp {
let ime_before = crate::ime::stamp(&mut self.session, ime_view);
let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors);
let spot_base = panels::color_guide::before_command(self);
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
let r = crate::print::execute_listing_printers(self, id, &params);
let r = panels::actions::after_recorded_command(self, r);
if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) {
self.canvas.hover_cursor = None;
+4
View File
@@ -466,6 +466,7 @@ registry! {
ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC,
ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC,
ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC,
ScriptPrint: [script_run::PRINT_KIND] => script_run::PRINT_SPEC,
VectorHalftone: [halftone::KIND] => halftone::SPEC,
ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC,
SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC,
@@ -811,6 +812,9 @@ pub fn cancel(app: &mut VectorcraftApp) {
if d.kind == script_run::PICKER_KIND {
script_run::picker_cancel(app, &d);
}
if d.kind == script_run::PRINT_KIND {
script_run::print_cancel(app, &d);
}
missing_links::cancelled(app, &d);
// Cancel discards Recolor Artwork's own history of color edits with them.
if d.kind == recolor::KIND {
+83
View File
@@ -24,6 +24,13 @@
//! and the dialog's own fields change neither what it allows nor what it says it allows. Escape,
//! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny.
//! `selectDlg` opens the host's folder picker in its own folder.
//!
//! The jobs a script prepared for a printer (`Document.print` without a file) wait for the dialog of
//! kind `scriptPrint`, which opens once the run has ended and its changes are kept, when no other
//! dialog is open. It lists each job's document, printer and sheets from the jobs themselves, which
//! no field changes. Only the person at the keyboard prints them, with Print: from
//! `ui.dialog.confirm` or synthetic input Print is refused and the dialog stays open. Cancel,
//! Escape and `ui.dialog.cancel` drop the jobs, from anyone; the script's changes stay either way.
use serde_json::{Value, json};
use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs};
@@ -46,6 +53,18 @@ pub const CLOSE_KIND: &str = "scriptClose";
pub const NOTICE_KIND: &str = "scriptDialog";
/// The dialog kind of a script's file dialogs.
pub const PICKER_KIND: &str = "scriptFiles";
/// The dialog kind of the question before the jobs a script prepared for a printer are sent.
pub const PRINT_KIND: &str = "scriptPrint";
pub(super) const PRINT_SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Print").into(),
body: print_body,
confirm: print_confirm,
ok: Some("Print"),
min_width: 420.0,
max_width: Some(560.0),
..DialogSpec::FORM
};
pub(super) const PICKER_SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Script File Access").into(),
@@ -546,3 +565,67 @@ fn answers_for(kind: &str) -> &'static str {
_ => "ok, stop",
}
}
/// Opens the question before the jobs a script prepared for a printer are sent, once the run has
/// ended and no other dialog is open.
pub(crate) fn ask_print(app: &mut VectorcraftApp) {
if app.ui.dialog.is_none() && !app.session.script_running() && app.session.script_prints_waiting() {
app.ui.dialog = Some(Dialog::new(PRINT_KIND, json!({})));
}
}
/// The jobs, read from the session, so `ui.dialog.set` cannot change what the person reads.
fn print_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, _: &mut Dialog) -> bool {
let t = Tokens::get(ui.ctx());
ui.label(tl!("The script asks to print these jobs. Its changes to the documents are kept whether or not you print."));
ui.add_space(8.0);
egui::ScrollArea::vertical().max_height(200.0).show(ui, |ui| {
egui::Grid::new("script-print-jobs").num_columns(3).spacing([16.0, 4.0]).show(ui, |ui| {
for head in [tl!("Document"), tl!("Printer"), tl!("Pages")] {
ui.label(egui::RichText::new(head).font(theme::semibold(12.0)).color(t.text));
}
ui.end_row();
for job in app.session.script_prints() {
ui.label(egui::RichText::new(shown_text(&job.title, false)).color(t.text_strong));
ui.label(egui::RichText::new(shown_text(&job.printer, false)).color(t.text_strong));
ui.label(egui::RichText::new(job.sheets.to_string()).color(t.text_strong));
ui.end_row();
}
});
});
false
}
/// Print: sends the jobs, when the person at the keyboard asked. From automation (a control or MCP
/// request, or synthetic input) it is refused and the dialog stays open.
fn print_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result<Value, String> {
if app.automation_asked() {
return Err(PRINT_BY_PERSON.into());
}
close_print(app);
let jobs = app.session.take_script_prints();
if jobs.is_empty() {
return Ok(Value::Null);
}
// The dialog is closed and the jobs are taken: a failure is reported in the status bar.
crate::print::send_script_prints(app, jobs).inspect_err(|e| app.status(e.clone()))
}
/// Cancel or Escape, from anyone: the jobs are dropped.
pub(super) fn print_cancel(app: &mut VectorcraftApp, _: &Dialog) {
close_print(app);
if !app.session.take_script_prints().is_empty() {
app.status(PRINTS_DROPPED);
}
}
fn close_print(app: &mut VectorcraftApp) {
if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PRINT_KIND) {
app.ui.dialog = None;
}
}
/// Print's error when automation asked.
pub(crate) const PRINT_BY_PERSON: &str = "Only the person at the keyboard can print a script's print jobs";
/// The status after Cancel.
pub(crate) const PRINTS_DROPPED: &str = "The script's print jobs were not sent";
+76
View File
@@ -4,10 +4,16 @@
//! it, or saves the PDF when asked to (`toFile`, `path`) or when there is no print service; a
//! PostScript file (`format: "postscript"`, or a `.ps` path) is always saved. `print.printers`
//! lists the printers.
//!
//! A script run started in the app gets the printers of a service that lets scripts print
//! ([`PrintService::scripts_may_print`], the desktop's), as names only. The jobs a script prepares
//! for them are sent after the run's changes are kept and the person approves them
//! ([`crate::dialogs::script_run::PRINT_KIND`], [`send_script_prints`]).
use serde::Serialize;
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::script::printing::{PreparedPrint, Printers};
use crate::{VectorcraftApp, io};
@@ -55,6 +61,11 @@ pub trait PrintService {
fn has_setup(&self) -> bool {
false
}
/// Whether scripts may list this service's printers and send jobs to them once the person
/// approves them. The browser's print dialog picks its own printer, so the web's does not.
fn scripts_may_print(&self) -> bool {
false
}
/// Setup…: open the system's settings of `printer` (`None`: the printers).
fn setup(&mut self, _printer: Option<&str>) -> Result<(), String> {
Err("there are no printer settings to open here".into())
@@ -67,6 +78,71 @@ pub fn printers(app: &mut VectorcraftApp) -> Value {
json!({ "printers": printers, "service": app.services.print.is_some(), "setup": setup })
}
/// The printers a script run may print to: the print service's, by name, when it lets scripts
/// print; `None` otherwise.
pub fn script_printers(app: &mut VectorcraftApp) -> Option<Printers> {
let service = app.services.print.as_mut().filter(|s| s.scripts_may_print())?;
let for_printer = !service.turns_landscape();
Some(Printers::new(service.printers().into_iter().map(|p| (p.name, p.default)), for_printer))
}
/// Runs the engine command `id`. A `script.run` started here lists the printers it may print to
/// ([`script_printers`]), and only that run lists them.
pub(crate) fn execute_listing_printers(app: &mut VectorcraftApp, id: &str, params: &Value) -> Result<Value, String> {
if id == "script.run" {
app.session.script_printers = script_printers(app);
}
let r = app.session.execute(id, params).map_err(|e| e.to_string());
app.session.script_printers = None;
r
}
/// The error for a script's jobs when the print service does not let scripts print.
const NO_SCRIPT_PRINTING: &str = "Printing from scripts is not available here: the script's print jobs were not sent";
/// Sends the jobs a script prepared, which the person approved, each to its printer. Every printer
/// must still be one the service lists, by its exact name, or no job is sent. → `{sent}`, or
/// `{background: true}` while the desktop's worker sends them.
pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec<PreparedPrint>) -> Result<Value, String> {
let service = app.services.print.as_mut().filter(|s| s.scripts_may_print()).ok_or(NO_SCRIPT_PRINTING)?;
let listed: Vec<String> = service.printers().into_iter().map(|p| p.name).collect();
if let Some(gone) = jobs.iter().find(|j| !listed.contains(&j.printer)) {
return Err(format!("The printer {} is no longer installed: the script's print jobs were not sent", gone.printer));
}
let count = jobs.len();
if let Some(submit) = service.shared_print() {
return crate::background::run(
app,
true,
"Printing from a script".into(),
None,
move |_| send_each(&mut |job| submit(job), &jobs).map(|notes| json!({ "notes": notes })),
move |app, result| {
let notes = result?;
app.status(notes["notes"].as_array().and_then(|n| n.last()).and_then(Value::as_str).unwrap_or_default());
Ok(json!({ "sent": count }))
},
);
}
let notes = send_each(&mut |job| service.print(job), &jobs)?;
app.status(notes.last().cloned().unwrap_or_default());
Ok(json!({ "sent": count }))
}
/// Gives each of `jobs` to `submit`, in order, stopping at the first that fails. → what each one
/// gave, or the error, which says how many were sent before it.
fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result<String, String>, jobs: &[PreparedPrint]) -> Result<Vec<String>, String> {
let mut notes = Vec::new();
for (sent, job) in jobs.iter().enumerate() {
match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, direct_pdf: false }) {
Ok(note) => notes.push(note),
Err(e) if sent == 0 => return Err(e),
Err(e) => return Err(format!("{e} ({sent} of {} print jobs were sent)", jobs.len())),
}
}
Ok(notes)
}
/// `file.print` with settings: print the active document with `settings` (over the document's, or
/// over those of the print preset `preset` names) on `printer` (default: the system's default), or
/// save the job as a PDF at `path` (else a picked file, the web downloads it) with `toFile`, a
+4
View File
@@ -2,6 +2,7 @@
//! its end, while the app goes on drawing the documents as they were before the run. The status bar
//! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with
//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer.
//! A run that prepared jobs for a printer ends with the question before they are sent.
use serde_json::json;
@@ -12,6 +13,7 @@ use crate::state::Dialog;
/// Advances the running script by one slice, or asks what its growth needs asked.
pub fn poll(app: &mut VectorcraftApp) {
script_run::drain(app);
script_run::ask_print(app);
if !app.session.script_running() {
return;
}
@@ -39,6 +41,8 @@ pub fn poll(app: &mut VectorcraftApp) {
if !crate::panels::actions::after_journaled_edit(app) {
app.status(format!("Ran {name}"));
}
// The jobs it prepared for a printer wait for the person's answer.
script_run::ask_print(app);
}
Err(e) => failed(app, e.to_string()),
}
+1
View File
@@ -42,6 +42,7 @@ mod screenmode;
mod screenshots;
mod script_check;
mod script_dialogs;
mod script_print;
mod script_run;
mod scripts_menu;
mod scrub;
+176
View File
@@ -0,0 +1,176 @@
//! A script's jobs for a printer (`Document.print` without a file): the run lists the print
//! service's printers, and its jobs are sent after it ends, only when the person at the keyboard
//! approves them.
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use crate::dialogs::script_run::{PRINT_BY_PERSON, PRINT_KIND, PRINTS_DROPPED};
use crate::print::{PrintJob, PrintService, Printer};
use crate::{Services, VectorcraftApp, dialogs, menus, script_runs};
/// What the service was sent: (printer, title, bytes).
type Sent = Rc<RefCell<Vec<(Option<String>, String, Vec<u8>)>>>;
/// A print service that records the jobs it is sent, with the printers `names` (the first one the
/// default), which lets scripts print when `scripts` is true.
struct Spool {
sent: Sent,
names: Rc<RefCell<Vec<String>>>,
scripts: bool,
}
impl PrintService for Spool {
fn printers(&mut self) -> Vec<Printer> {
self.names.borrow().iter().enumerate().map(|(i, name)| Printer { name: name.clone(), default: i == 0 }).collect()
}
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
self.sent.borrow_mut().push((job.printer.map(str::to_string), job.title.to_string(), job.pdf.to_vec()));
Ok(format!("Sent to {}", job.printer.unwrap_or("the default printer")))
}
fn scripts_may_print(&self) -> bool {
self.scripts
}
}
/// An app with a document, a print service listing Office (the default) and Lab, and no warning
/// before a script runs.
fn print_app(scripts: bool) -> (VectorcraftApp, Sent, Rc<RefCell<Vec<String>>>) {
let sent = Sent::default();
let names = Rc::new(RefCell::new(vec!["Office".to_string(), "Lab".to_string()]));
let spool = Spool { sent: sent.clone(), names: names.clone(), scripts };
let mut app = VectorcraftApp::new(Session::new(), Services { print: Some(Box::new(spool)), ..Default::default() });
app.run("file.new", json!({})).unwrap();
app.session.prefs.show_external_script_warning = false;
(app, sent, names)
}
fn objects(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
}
/// Runs `source` as File › Scripts › Other Script… runs it, to its end.
fn run(app: &mut VectorcraftApp, source: &str) {
menus::run_ui_command(app, "ui.runScript", &json!({ "source": source, "name": "p.js" })).unwrap().unwrap();
for _ in 0..10_000 {
script_runs::poll(app);
if !app.session.script_running() {
return;
}
}
panic!("the script did not end");
}
const PRINT_TO_LAB: &str =
"var o = new PrintOptions(); o.printerName = 'Lab'; app.activeDocument.print(o); vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});";
fn open_kind(app: &VectorcraftApp) -> Option<&str> {
app.ui.dialog.as_ref().map(|d| d.kind.as_str())
}
/// A control request, handled as the app handles one: while `answering_control` is set.
fn control(app: &mut VectorcraftApp, method: &str, params: Value) -> Value {
let (req, _) = crate::control::ControlRequest::new(method, params);
app.ui.answering_control = true;
let outcome = crate::control::handle(app, &egui::Context::default(), &req);
app.ui.answering_control = false;
let crate::control::Outcome::Done(r) = outcome else { panic!("expected an immediate reply") };
r
}
/// The job is sent after the run's changes are kept, once, and only when the person at the
/// keyboard approves it: Print from a control request or synthetic input is refused.
#[test]
fn a_scripts_print_job_is_sent_only_when_the_person_approves_it() {
let (mut app, sent, _) = print_app(true);
run(&mut app, PRINT_TO_LAB);
assert_eq!(objects(&app), 1, "the run's changes are kept");
assert_eq!(open_kind(&app), Some(PRINT_KIND));
assert!(sent.borrow().is_empty(), "nothing is sent before the person answers");
let r = control(&mut app, "ui.dialog.confirm", json!({}));
assert_eq!(r["error"], PRINT_BY_PERSON, "{r}");
app.synthetic_frame = true;
assert_eq!(dialogs::confirm(&mut app).unwrap_err(), PRINT_BY_PERSON);
app.synthetic_frame = false;
assert_eq!(open_kind(&app), Some(PRINT_KIND), "the question stays open");
assert!(sent.borrow().is_empty());
dialogs::confirm(&mut app).unwrap();
assert_eq!(open_kind(&app), None);
{
let sent = sent.borrow();
assert_eq!(sent.len(), 1);
assert_eq!(sent[0].0.as_deref(), Some("Lab"));
assert!(sent[0].2.starts_with(b"%PDF"));
}
assert_eq!(app.ui.status, "Sent to Lab");
for _ in 0..5 {
script_runs::poll(&mut app);
}
assert_eq!(sent.borrow().len(), 1, "a job is sent once");
assert_eq!(open_kind(&app), None);
}
/// Cancel, from anyone, drops the jobs and keeps the run's changes.
#[test]
fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() {
let (mut app, sent, _) = print_app(true);
run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}"));
assert_eq!(app.session.script_prints().len(), 2);
let r = control(&mut app, "ui.dialog.cancel", json!({}));
assert!(r.get("error").is_none_or(Value::is_null), "{r}");
assert_eq!(open_kind(&app), None);
assert!(!app.session.script_prints_waiting());
assert_eq!(app.ui.status, PRINTS_DROPPED);
script_runs::poll(&mut app);
assert_eq!(open_kind(&app), None, "the question does not come back");
assert!(sent.borrow().is_empty());
assert_eq!(objects(&app), 1);
}
/// A run that fails asks nothing and sends nothing; a printer that went away before Print is
/// refused and no job is sent.
#[test]
fn a_failed_run_or_a_printer_that_went_away_sends_nothing() {
let (mut app, sent, names) = print_app(true);
run(&mut app, &format!("{PRINT_TO_LAB} throw new Error('late');"));
assert_eq!(open_kind(&app), None);
assert!(!app.session.script_prints_waiting());
assert_eq!(objects(&app), 0);
run(&mut app, &format!("app.activeDocument.print(); {PRINT_TO_LAB}"));
assert_eq!(open_kind(&app), Some(PRINT_KIND));
names.borrow_mut().retain(|n| n != "Lab");
let e = dialogs::confirm(&mut app).unwrap_err();
assert_eq!(e, "The printer Lab is no longer installed: the script's print jobs were not sent");
assert_eq!(app.ui.status, e);
assert!(sent.borrow().is_empty(), "neither job is sent");
assert_eq!(open_kind(&app), None);
}
/// Without a service that lets scripts print (the web's), or without any, printing to a printer
/// from a script throws and nothing is asked or sent.
#[test]
fn a_script_cannot_print_to_a_printer_without_a_service_that_allows_it() {
let (mut app, sent, _) = print_app(false);
run(&mut app, PRINT_TO_LAB);
assert!(app.ui.status.contains("Printing to a printer is not available here"), "{}", app.ui.status);
assert_eq!(open_kind(&app), None);
assert!(sent.borrow().is_empty());
let mut bare = VectorcraftApp::new(Session::new(), Services::default());
bare.run("file.new", json!({})).unwrap();
bare.session.prefs.show_external_script_warning = false;
run(&mut bare, "vc.log(app.printerList.length);");
assert!(bare.ui.status.contains("Application.printerList is not available here"), "{}", bare.ui.status);
// A run the app started lists the service's printers; a later run without one does not.
let (mut app, _, _) = print_app(true);
run(&mut app, "var l = app.printerList; vc.log([l.length, l[0].name, l[1].name]);");
assert_eq!(app.session.script_report().unwrap()["log"], json!([[2, "Office", "Lab"]]));
assert!(app.session.script_printers.is_none());
// A run that does not start leaves no list behind for a later one.
assert!(app.run("script.run", json!({"source": "1", "path": "x.js"})).is_err());
assert!(app.session.script_printers.is_none());
}
+24 -4
View File
@@ -2743,8 +2743,27 @@ 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
assigned, a print-ready PDF otherwise, 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
printer it throws `There is no default printer`. `print` composes the job as a print-ready PDF when it is called
and sends nothing while the run goes on. When the run ends and its changes are kept, the app asks before it sends
the jobs (dialog kind `scriptPrint`, listing each job's document, printer and pages). Only the person at the
keyboard can choose Print: `ui.dialog.confirm` and synthetic input are refused, and the dialog stays open. Cancel,
Escape and `ui.dialog.cancel` drop the jobs and keep the run's changes. A run that fails or is stopped sends
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),
`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/,
https://ai-scripting.docsforadobe.dev/jsobjref/Printer/). Its `name` is read-only and its `printerInfo` throws an
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
@@ -2753,7 +2772,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot
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
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
@@ -2959,7 +2978,8 @@ In the app, a script past the growth limit stops at a question to continue or to
`ui.dialog.cancel` all stop the run. A run with nobody to ask, such as a call over MCP or the command line, ends
with an error at that limit. The headless reply is `{ok: true, name, changed, written, log, fuelUsed, hostCalls,
runTimeMs, timingAvailable, hostCallCounts, slowestCommands, console, dialogs, dialogCount, dialogsTruncated}`. In
the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`. The
the app the reply is `{running: true, name}`, and the report appears later as `scriptReport` in `ui.inspect`, with
`prints`, the number of jobs the run prepared for a printer, when it prepared any. The
report of a failed run has the same fields after `kind`, `message`, `messageOrigin`, `line`, `column`, `file` (when
the error is in another file than the script) and `fuelLeft`. `messageOrigin` is `script` when `message` is text the
script supplied (a value it threw, or an error it made or whose name or message it changed) and `built-in` for the
+2 -1
View File
@@ -1026,7 +1026,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- 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. Printing to a printer from a script and `app.printerList` are not available yet (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`). `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 approves them, 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: 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`.