diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 9e416d7711..f730a69443 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -157,6 +157,7 @@ fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> { /// the framework's. pub(crate) fn services(window: Parent) -> Services { let probe_window = window.clone(); + let print = printing::SystemPrint::new(&window); Services { // Every format Copy offers and Paste reads. Its calls are marked for the hang report (`hang_watch`). clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(window)))), @@ -188,7 +189,7 @@ pub(crate) fn services(window: Parent) -> Services { check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. - print: Some(Box::new(printing::SystemPrint::default())), + print: Some(Box::new(print)), // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens // only while the active tool uses the wheel. #[cfg(all(windows, not(target_vendor = "win7")))] diff --git a/apps/vectorcraft/src/legacy_spool_copy.rs b/apps/vectorcraft/src/legacy_spool_copy.rs index 30bea883fe..26ad0b3487 100644 --- a/apps/vectorcraft/src/legacy_spool_copy.rs +++ b/apps/vectorcraft/src/legacy_spool_copy.rs @@ -10,11 +10,11 @@ use craft_pdf::{ }; /// Keep the submission's original vector PDF when no transparent RGB sheet can be rendered. -pub(super) fn flatten(bytes: &[u8], grayscale: bool) -> Option { +pub(super) fn flatten(bytes: &[u8], grayscale: bool, grayscale_composed: bool) -> Option { craft_pdf::check_input_size(bytes.len()).ok()?; let bytes = Arc::new(bytes.to_vec()); let doc = Document::open(bytes.clone()).ok()?; - if !rgb_spool_copy_allowed(&doc) { + if !colour_spool_copy_allowed(&doc, grayscale && grayscale_composed) { return None; } @@ -67,9 +67,9 @@ pub(super) fn flatten(bytes: &[u8], grayscale: bool) -> Option { } /// RGB tiles cannot preserve profiled output, process or spot plates, or driver-side overprint. -/// A plate made of DeviceGray paint also stays on the vector route. Check the composed job so -/// art arriving from a script or through a shared print resource follows the same policy. -fn rgb_spool_copy_allowed(doc: &Document) -> bool { +/// A plate made of DeviceGray paint stays on the vector route. The engine can identify its +/// grayscale composite explicitly. Inspect the PDF to protect colour choices on either route. +fn colour_spool_copy_allowed(doc: &Document, grayscale_composed: bool) -> bool { const MAX_OBJECTS: usize = 1 << 16; let mut budget = DecodeBudget::page(); let mut saw_rgb = false; @@ -105,7 +105,7 @@ fn rgb_spool_copy_allowed(doc: &Document) -> bool { } } } - saw_rgb + saw_rgb || grayscale_composed } fn paints_content(dict: &Dict) -> bool { @@ -201,7 +201,7 @@ pub(super) mod tests { #[test] fn transparent_rgb_sheet_is_opaque_and_the_vector_sheet_is_retained() { let source = pdf(b"/Alpha gs 1 0 0 rg 10 10 50 50 re f", false, false); - let copy = flatten(&source, false).unwrap(); + let copy = flatten(&source, false, false).unwrap(); assert_ne!(copy.pdf, source); assert!(!copy.every_sheet); let doc = Document::open(Arc::new(copy.pdf)).unwrap(); @@ -222,16 +222,18 @@ pub(super) mod tests { #[test] fn live_process_colour_overprint_and_plain_vectors_are_preserved() { - assert!(flatten(&pdf(b"/Alpha gs 0 1 0 0 k 10 10 50 50 re f", false, false), false).is_none()); - assert!(flatten(&pdf(b"/Alpha gs 1 0 0 rg 10 10 50 50 re f", true, false), false).is_none()); - assert!(flatten(&pdf(b"1 0 0 rg 10 10 50 50 re f", false, false), false).is_none()); - assert!(flatten(&pdf(b"/Alpha gs 0.6 g 10 10 50 50 re f", false, false), false).is_none()); + assert!(flatten(&pdf(b"/Alpha gs 0 1 0 0 k 10 10 50 50 re f", false, false), false, false).is_none()); + assert!(flatten(&pdf(b"/Alpha gs 1 0 0 rg 10 10 50 50 re f", true, false), false, false).is_none()); + assert!(flatten(&pdf(b"1 0 0 rg 10 10 50 50 re f", false, false), false, false).is_none()); + let gray = pdf(b"/Alpha gs 0.6 g 10 10 50 50 re f", false, false); + assert!(flatten(&gray, true, false).is_none()); + assert!(flatten(&gray, true, true).is_some()); } #[test] fn a_soft_masked_rgb_image_does_not_need_vector_colour_operators() { let source = pdf(b"q 50 0 0 50 10 10 cm /Image Do Q", false, true); - let copy = flatten(&source, false).unwrap(); + let copy = flatten(&source, false, false).unwrap(); assert_ne!(copy.pdf, source); assert!(!copy.every_sheet); } diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index e4db29ff71..0c0cee8018 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -1,6 +1,8 @@ //! Desktop printer transport. VectorCraft composes every page and copy before submission; //! craft-print owns discovery and spooling. use std::process::Command; +#[cfg(windows)] +use vectorcraft_ui_egui::print::DriverJob; use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer}; mod direct_pdf; @@ -9,6 +11,27 @@ mod direct_pdf; pub struct SystemPrint { /// The paper-size lookup in flight, dropped when its worker answers or disconnects. papers: PaperLookup, + #[cfg(windows)] + parent: Option, +} + +impl SystemPrint { + pub fn new(window: &super::host_services::Parent) -> Self { + #[cfg(windows)] + { + use winit::raw_window_handle::{HasWindowHandle as _, RawWindowHandle}; + let parent = window.as_ref().and_then(|window| match window.window_handle().ok()?.as_raw() { + RawWindowHandle::Win32(handle) => Some(handle.hwnd.get()), + _ => None, + }); + Self { parent, ..Self::default() } + } + #[cfg(not(windows))] + { + let _ = window; + Self::default() + } + } } impl PrintService for SystemPrint { @@ -28,6 +51,9 @@ impl PrintService for SystemPrint { fn applies_paper(&self) -> bool { !cfg!(windows) } + fn applies_job_options(&self) -> bool { + true + } fn turns_landscape(&self) -> bool { // macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright // paper. craft-print turns each sheet to its own orientation on Windows. @@ -39,6 +65,15 @@ impl PrintService for SystemPrint { fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { system::setup(printer) } + fn has_driver_properties(&self) -> bool { + craft::print::HAS_DRIVER_SETTINGS_DIALOG + } + #[cfg(windows)] + fn driver_properties(&mut self, job: &mut DriverJob) -> Result { + use vectorcraft_ui_egui::hang_beacon::{Activity, BEACON}; + let _waiting = BEACON.activity(Activity::Dialog); + craft::print::driver_settings_dialog(job, self.parent).map_err(|error| error.to_string()) + } fn scripts_may_print(&self) -> bool { true } @@ -348,17 +383,17 @@ mod system { } } pub fn print(job: &PrintJob) -> Result { + let settings = settings(job)?; if job.direct_pdf { return super::direct_pdf::print(job); } - let settings = settings(job); #[cfg(windows)] { let prepared = settings .printer .as_deref() .filter(|printer| craft::print::xps_driver(printer) == Some(false)) - .and_then(|_| super::legacy_spool_copy::flatten(job.pdf, settings.grayscale)); + .and_then(|_| super::legacy_spool_copy::flatten(job.pdf, settings.grayscale, job.grayscale_composed)); let pdf = prepared.map_or_else(|| job.pdf.to_vec(), |flat| flat.pdf); submit_driver(pdf, settings) } @@ -385,9 +420,37 @@ mod system { /// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve /// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper /// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for. - pub(crate) fn settings(job: &PrintJob) -> craft::print::Job { + pub(crate) fn settings(job: &PrintJob) -> Result { + use vectorcraft_engine::script::printing::{JobOptions, OutputColor, Sides}; + + if job.direct_pdf && job.options != JobOptions::default() { + return Err("Per-job colour and duplex require the printer driver".into()); + } let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect(); - craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() } + let mut settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() }; + if let Some(properties) = job.driver_settings { + if job.direct_pdf || job.printer != Some(properties.printer()) { + return Err("The job's printer properties do not match its print destination".into()); + } + let choices = properties.choices(); + settings.grayscale = choices.grayscale.unwrap_or(false); + settings.duplex = choices.duplex; + settings.driver_settings = Some(properties.clone()); + } + if let Some(color) = job.options.color { + settings.set_output_color(Some(match color { + OutputColor::Color => craft::print::OutputColor::Color, + OutputColor::Monochrome => craft::print::OutputColor::Monochrome, + })); + } + if let Some(duplex) = job.options.duplex { + settings.duplex = Some(match duplex { + Sides::OneSided => craft::print::Duplex::Off, + Sides::LongEdge => craft::print::Duplex::LongEdge, + Sides::ShortEdge => craft::print::Duplex::ShortEdge, + }); + } + Ok(settings) } #[cfg(windows)] pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command { @@ -464,6 +527,45 @@ mod tests { let args: Vec<&OsStr> = cmd.get_args().collect(); assert_eq!(args, ["ms-settings:printers"]); } + #[test] + fn exact_queue_uses_opaque_properties_without_repeating_composed_copies() { + let mut bytes = vec![0x4b; 228]; + bytes[68..70].copy_from_slice(&220u16.to_le_bytes()); + bytes[70..72].copy_from_slice(&8u16.to_le_bytes()); + bytes[72..76].copy_from_slice(&(0x800u32 | 0x1000).to_le_bytes()); + bytes[92..94].copy_from_slice(&1i16.to_le_bytes()); + bytes[94..96].copy_from_slice(&3i16.to_le_bytes()); + let properties = craft::print::DriverSettings::new("Proofer", craft::print::rgb::DevMode::from_bytes(bytes).unwrap()); + let mut job = vectorcraft_ui_egui::print::PrintJob { + printer: Some("Proofer"), + title: "Proof", + pdf: b"%PDF", + paper: None, + direct_pdf: false, + driver_settings: Some(&properties), + options: Default::default(), + grayscale_composed: false, + }; + let request = super::system::settings(&job).unwrap(); + assert_eq!(request.printer.as_deref(), Some("Proofer")); + assert_eq!(request.copies, 1); + assert!(request.grayscale); + assert_eq!(request.duplex, Some(craft::print::Duplex::ShortEdge)); + assert!(request.driver_settings == Some(properties.clone())); + use vectorcraft_engine::script::printing::{OutputColor, Sides}; + job.options.color = Some(OutputColor::Color); + job.options.duplex = Some(Sides::OneSided); + let explicitly_color = super::system::settings(&job).unwrap(); + assert_eq!(explicitly_color.output_color(), Some(craft::print::OutputColor::Color)); + assert_eq!(explicitly_color.duplex, Some(craft::print::Duplex::Off)); + assert_eq!(explicitly_color.driver_settings, Some(properties.clone())); + job.options = Default::default(); + job.printer = Some("Office"); + assert!(super::system::settings(&job).is_err()); + job.printer = Some("Proofer"); + job.direct_pdf = true; + assert!(super::system::settings(&job).is_err()); + } } #[cfg(test)] @@ -705,19 +807,28 @@ mod job_settings_tests { use vectorcraft_ui_egui::print::PrintJob; fn job(paper: Option<&str>) -> PrintJob<'_> { - PrintJob { printer: Some("Card"), title: "Badge", pdf: b"%PDF", paper, direct_pdf: false } + PrintJob { + printer: Some("Card"), + title: "Badge", + pdf: b"%PDF", + paper, + direct_pdf: false, + driver_settings: None, + options: Default::default(), + grayscale_composed: false, + } } #[test] fn the_chosen_paper_goes_to_cups_as_media() { - let args = craft::print::lp_args(&settings(&job(Some("CR80")))); + let args = craft::print::lp_args(&settings(&job(Some("CR80"))).unwrap()); assert!(args.windows(2).any(|w| w == ["-o", "media=CR80"]), "{args:?}"); assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}"); } #[test] fn without_a_paper_the_queue_keeps_its_own() { - let args = craft::print::lp_args(&settings(&job(None))); + let args = craft::print::lp_args(&settings(&job(None)).unwrap()); assert!(!args.iter().any(|a| a.starts_with("media=")), "{args:?}"); } } diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 77e6d03395..3d21cdc131 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -207,6 +207,30 @@ fn type_warnings(doc: &Document, which: PrintLayers, areas: &[Rect]) -> Vec bool { + set.color.grayscale && set.output.mode == vectorcraft_pdf::OutputMode::Composite +} + +/// A colour as gray with Rec. 709 weights (ink amount: 0 white, 1 black). +fn gray709(c: vectorcraft_color::Color) -> vectorcraft_color::Color { + use vectorcraft_color::Color; + if matches!(c, Color::Gray { .. }) { + return c; + } + let [r, g, b] = c.to_rgb(); + Color::gray((1.0 - (0.2126 * r + 0.7152 * g + 0.0722 * b)).clamp(0.0, 1.0)) +} + +/// Create the grayscale artwork for composition without editing the document. +pub fn grayscale_document(doc: &Document) -> Document { + use super::colorcmds::{Recolor, Scope}; + let mut out = doc.clone(); + let ids: Vec<_> = out.layers.iter().map(|l| l.id).collect(); + Recolor::new(Scope { fill: true, stroke: true, images: true, patterns: true }, &gray709).run(&mut out, &ids); + out +} + /// Whether `file.print` writes PostScript: `format`, else a `.ps` path. fn to_postscript(p: &Value) -> Result { match str_param(p, "format") { @@ -271,6 +295,8 @@ fn print(s: &mut Session, p: &Value) -> Result { // Raster effects print as images at the document's raster effects resolution. let flat = super::rasterfx::flatten_raster_effects(doc); let doc = flat.as_ref().unwrap_or(doc); + let grayed = prints_gray(&set).then(|| grayscale_document(doc)); + let doc = grayed.as_ref().unwrap_or(doc); // The flattener expands pattern fills whose tile images need flattening, in the layers that print. let tile_images = postscript && !bitmap && flattener.is_some_and(|o| has_transparent_tile_images(&vectorcraft_pdf::printed_document(doc, &set), &o)); @@ -293,7 +319,11 @@ fn print(s: &mut Session, p: &Value) -> Result { // What the job loses comes first, then the notes on the options. r.warnings.extend(typed); r.warnings.extend(r.setting_notes); - return write_or_return(path, &r.bytes, json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings })); + let mut reply = json!({ "pages": r.pages, "format": "pdf", "warnings": r.warnings }); + if grayed.is_some() { + reply["compositeGrayscale"] = json!(true); + } + return write_or_return(path, &r.bytes, reply); } // What the job loses, then the notes on the options: a reply lists them in that order. let (mut warnings, mut setting_notes) = (vec![], vec![]); diff --git a/crates/engine/src/script/dom/print.rs b/crates/engine/src/script/dom/print.rs index 13e9222864..34f8f26598 100644 --- a/crates/engine/src/script/dom/print.rs +++ b/crates/engine/src/script/dom/print.rs @@ -68,7 +68,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_color::cms; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref, host_ref_parts}; -use super::super::printing::{MAX_JOB_BYTES, MAX_JOBS, MAX_SHEETS, PreparedPrint, Printers}; +use super::super::printing::{JobOptions, MAX_JOB_BYTES, MAX_JOBS, MAX_SHEETS, OutputColor, PreparedPrint, Printers}; use super::save_open::{exactly, file_path, plain, refused}; use super::{ Answer, Described, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, arg, class, command, command_kept, current, float, get, given, later, method, @@ -256,6 +256,8 @@ const PRINT_OPTIONS: Class = Class { f("postScriptOptions", Kind::Child("PrintPostScriptOptions"), Start::None), kept("PPDName", Kind::Text, Start::Text("")), f("printerName", Kind::Text, Start::Text("")), + f("driverColor", Kind::Text, Start::Text("default")), + f("driverDuplex", Kind::Text, Start::Text("default")), f("printPreset", Kind::Text, Start::None), ], }; @@ -533,6 +535,7 @@ struct Job { file: Option, /// The assigned `printerName`. printer: Option, + driver: JobOptions, level: Option, /// The assigned `artboardRange`, checked whether or not it picks the artboards. range: Option, @@ -620,6 +623,8 @@ fn map_options(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(), "flattenerPreset" => job.flattener = Some(string_of(&v)), "printPreset" => job.preset = Some(string_of(&v)), "printerName" => job.printer = Some(string_of(&v)), + "driverColor" => job.driver.color = driver_value(&v, k)?, + "driverDuplex" => job.driver.duplex = driver_value(&v, k)?, "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), @@ -637,6 +642,14 @@ fn map_options(h: &Host, slot: usize, job: &mut Job) -> std::result::Result<(), Ok(()) } +fn driver_value(value: &Data, name: &str) -> std::result::Result, HostError> { + let value = string_of(value); + if value == "default" { + return Ok(None); + } + serde_json::from_value(Value::String(value)).map(Some).map_err(|error| HostError::Type(format!("PrintOptions.{name}: {error}"))) +} + fn map_job(h: &Host, slot: usize, job: &mut Job) { let set = assigned(h, slot); let value = |name: &str| set.iter().find(|(k, _)| *k == name).map(|(_, v)| v); @@ -888,6 +901,9 @@ fn doc_print(h: &Host, a: &[Data]) -> Answer { map_options(h, slot, &mut job)?; } let Some(file) = job.file.take() else { return prepare(h, doc, job) }; + if job.driver != JobOptions::default() { + return Err(HostError::Type("Printer colour and duplex choices require a native print job".into())); + } 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))?; @@ -964,6 +980,9 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer { 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)?; + if let Some(color) = job.driver.color { + job.group("color").insert("grayscale".into(), json!(color == OutputColor::Monochrome)); + } let mut p = print_params(&mut job); if for_printer { p.insert("forPrinter".into(), json!(true)); @@ -987,7 +1006,11 @@ fn prepare(h: &Host, doc: Doc, mut job: Job) -> Answer { } } let title = with_doc(h, doc, |_, st| st.title()); - state.jobs.borrow_mut().push(PreparedPrint { printer, title, pdf, sheets: pages }); + let grayscale_composed = printed["compositeGrayscale"] == true; + if grayscale_composed && job.driver.color.is_none() { + job.driver.color = Some(OutputColor::Monochrome); + } + state.jobs.borrow_mut().push(PreparedPrint { printer, title, pdf, sheets: pages, options: job.driver, grayscale_composed }); Ok(Data::Undefined) } diff --git a/crates/engine/src/script/printing.rs b/crates/engine/src/script/printing.rs index f33a12113b..3f1a5ccf5d 100644 --- a/crates/engine/src/script/printing.rs +++ b/crates/engine/src/script/printing.rs @@ -88,6 +88,38 @@ impl Printers { } } +/// A choice for the printer's output colour. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum OutputColor { + /// Ask for colour even when the queue defaults to monochrome. + Color, + /// Request monochrome. + Monochrome, +} + +/// A choice for the printer's sides. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Sides { + /// Print on one side of each sheet. + OneSided, + /// Flip two-sided sheets on their long edge. + LongEdge, + /// Flip two-sided sheets on their short edge. + ShortEdge, +} + +/// Optional per-job requests for the native driver. Unset values keep the queue or Properties choice. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(default, rename_all = "camelCase", deny_unknown_fields)] +pub struct JobOptions { + /// The requested output colour, if any. + pub color: Option, + /// The requested simplex or duplex mode, if any. + pub duplex: Option, +} + /// A job a run prepared for a printer: a print-ready PDF, every copy in it. #[derive(Clone, Debug, PartialEq)] pub struct PreparedPrint { @@ -98,4 +130,8 @@ pub struct PreparedPrint { pub pdf: Vec, /// The sheets of paper it prints, every copy counted. pub sheets: u64, + /// Only applied if the approved job reaches the native print service. + pub options: JobOptions, + /// The engine composed a grayscale composite, rather than a plate separation. + pub grayscale_composed: bool, } diff --git a/crates/engine/src/tests/script_print.rs b/crates/engine/src/tests/script_print.rs index ad542049a1..a2917963c2 100644 --- a/crates/engine/src/tests/script_print.rs +++ b/crates/engine/src/tests/script_print.rs @@ -223,6 +223,32 @@ fn printer_list_is_the_bounded_list_the_frontend_gave() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn prepared_jobs_keep_their_assigned_driver_options() { + use crate::script::printing::{JobOptions, OutputColor, Sides}; + + let base = folder("driver-options"); + let mut s = session(&base); + s.script_printers = Some(printers()); + let result = run( + &mut s, + &base, + "var o = new PrintOptions(); + o.driverColor = 'monochrome'; o.driverDuplex = 'longEdge'; app.activeDocument.print(o); + o.driverColor = 'color'; o.driverDuplex = 'oneSided'; app.activeDocument.print(o); + app.activeDocument.print();", + ) + .unwrap(); + assert_eq!(result["prints"], 3); + let jobs = s.take_script_prints(); + assert_eq!(jobs[0].options, JobOptions { color: Some(OutputColor::Monochrome), duplex: Some(Sides::LongEdge) }); + assert!(jobs[0].grayscale_composed); + assert_eq!(jobs[1].options, JobOptions { color: Some(OutputColor::Color), duplex: Some(Sides::OneSided) }); + assert!(!jobs[1].grayscale_composed); + assert_eq!(jobs[2].options, JobOptions::default()); + 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. diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 72234356db..32446d56d7 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -360,7 +360,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "PrintOptions.prototype.", "PPDName PPDName= colorManagementOptions colorManagementOptions= colorSeparationOptions colorSeparationOptions= \ - constructor coordinateOptions coordinateOptions= flattenerOptions flattenerOptions= flattenerPreset \ + constructor coordinateOptions coordinateOptions= driverColor driverColor= driverDuplex driverDuplex= flattenerOptions flattenerOptions= flattenerPreset \ flattenerPreset= fontOptions fontOptions= jobOptions jobOptions= pageMarksOptions pageMarksOptions= paperOptions \ paperOptions= postScriptOptions postScriptOptions= printPreset printPreset= printerName printerName= typename", ), diff --git a/crates/pdf/src/print/settings.rs b/crates/pdf/src/print/settings.rs index f6f3e5c563..960a8af52d 100644 --- a/crates/pdf/src/print/settings.rs +++ b/crates/pdf/src/print/settings.rs @@ -536,11 +536,13 @@ pub struct PrintColor { /// it with the intent (CMYK colours keep their numbers with `preserve_numbers`), and /// separations separate with it when it is a CMYK one. Empty: colours print as they are. pub profile: String, + /// Convert composite print artwork to gray when composing the job. + pub grayscale: bool, } impl Default for PrintColor { fn default() -> Self { - Self { intent: Intent::RelativeColorimetric, preserve_numbers: true, profile: String::new() } + Self { intent: Intent::RelativeColorimetric, preserve_numbers: true, profile: String::new(), grayscale: false } } } diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 3e58a287d5..0a49563631 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -49,6 +49,8 @@ use super::form; use crate::print::{Paper, Papers}; use crate::{VectorcraftApp, graphics}; +mod properties; + pub(crate) const SECTIONS: [&str; 7] = ["General", "Marks and Bleed", "Output", "Graphics", "Color Management", "Advanced", "Summary"]; /// The default print settings as JSON: what a field an agent left out reads as. @@ -61,7 +63,7 @@ static KEYS: LazyLock> = LazyLock::new(|| sections(&Lists::default()) const PLACED: &str = "tileOrigin.placed"; /// The fields that aren't print settings. -const NOT_SETTINGS: [&str; 1] = ["directPdf"]; +const NOT_SETTINGS: [&str; 3] = ["directPdf", "driverColor", "driverDuplex"]; /// The Printer list's entries besides the system's printers; `PDF_FILE` is the destination that /// saves the job as a PDF. @@ -112,6 +114,7 @@ struct Open { preview: Option<(Stamp, Arc>)>, /// The printer row's driver controls, as the dialog was last given them. driver: DriverControls, + properties: properties::Draft, /// The printer the Media list was made for, and the paper sizes its driver offers (while its lookup runs, the sizes /// of the printer before it). papers: (String, Vec), @@ -138,6 +141,7 @@ struct Drained { /// The preset editor's name. name: String, setup: Option, + direct_pdf: bool, moves: EditEvents, events: Vec>, ok: Option, @@ -321,13 +325,38 @@ fn start( } else { vec![] }; + if mode == PrintMode::Print && app.services.print.as_ref().is_some_and(|s| s.applies_job_options()) { + let choices = |entries: &[(&str, &str)]| { + ParamKind::choice(entries.iter().map(|(key, label)| (key.to_string(), label.to_string().into())).collect(), None) + }; + header.push(Param::new( + "driverColor", + tl!("Color:"), + choices(&[("", tl!("Printer default")), ("color", tl!("Color")), ("monochrome", tl!("Grayscale"))]), + )); + header.push(Param::new( + "driverDuplex", + tl!("Sides:"), + choices(&[ + ("", tl!("Printer default")), + ("oneSided", tl!("One-sided")), + ("longEdge", tl!("Two-sided, long edge")), + ("shortEdge", tl!("Two-sided, short edge")), + ]), + )); + } header.push(Param::custom("__discovery", "", |ui, fields, _| { let text = if fields.bool("__discovery") == Some(true) { tl!("Finding printers. PDF File and Done are available.") } else { "" }; Text::new(text).show(ui) })); let taken: Vec = taken_names(app); let named = editing.clone(); - let driver = driver(has_setup(app), &state.settings.destination); + let available = driver_support(app); + let driver = driver(available, &state.settings.destination, mode, false); + if available == DriverControls::Properties && mode == PrintMode::Print { + header + .push(Param::custom("__properties", "", |ui, fields, _| Text::new(fields.text("__properties").unwrap_or_default().to_owned()).show(ui))); + } let printer = printer_of(&state.settings.destination); let (papers, papers_pending) = papers_of(app, mode, &printer, true); if papers_pending { @@ -363,6 +392,7 @@ fn start( art: None, preview: None, driver, + properties: properties::Draft::default(), papers: (printer, papers), papers_pending, media, @@ -475,16 +505,21 @@ fn discover(app: &mut VectorcraftApp) -> mpsc::Receiver> { rx } -/// Whether the print service can open a printer's settings (`print.printerSetup`). -fn has_setup(app: &VectorcraftApp) -> bool { - app.services.print.as_ref().is_some_and(|s| s.has_setup()) +/// Choose the action the host offers for a queue. +fn driver_support(app: &VectorcraftApp) -> DriverControls { + match app.services.print.as_ref() { + Some(service) if service.has_driver_properties() => DriverControls::Properties, + Some(service) if service.has_setup() => DriverControls::Page, + _ => DriverControls::None, + } } -/// The printer row's Setup…: shown when the print service can open printer settings (`setup`) and `destination` -/// is a printer. -fn driver(setup: bool, destination: &Destination) -> DriverControls { - let printer = matches!(destination, Destination::Printer(name) if name != PDF_FILE); - if setup && printer { DriverControls::Page } else { DriverControls::None } +fn driver(available: DriverControls, destination: &Destination, mode: PrintMode, direct_pdf: bool) -> DriverControls { + let Destination::Printer(name) = destination else { return DriverControls::None }; + if name == PDF_FILE || (available == DriverControls::Properties && (name.is_empty() || mode != PrintMode::Print || direct_pdf)) { + return DriverControls::None; + } + available } /// The names a new preset may not take: [Default] and the saved presets. @@ -547,10 +582,11 @@ fn discovery_valid(p: &mut HostedPrint, mode: PrintMode, pending: bool) { /// One pass of the pump over the open dialog; false once it has closed. fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, open: &mut Open) -> bool { // Setup… looks the printers up again on some systems, so the row shows it once the discovery has ended. - let setup = has_setup(app) && open.discovery.is_none(); + let available = if open.discovery.is_none() { driver_support(app) } else { DriverControls::None }; let Some(mut d) = on(dialogs, |p| { // The printer row shows Setup… for the printer chosen, and none for PDF File. - let driver = driver(setup, &p.state().settings.destination); + let direct_pdf = p.fields().bool("directPdf").unwrap_or(false); + let driver = driver(available, &p.state().settings.destination, open.mode, direct_pdf); p.set_driver(driver); Drained { driver, @@ -562,6 +598,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, } else { None }, + direct_pdf, moves: p.take_moves(), events: p.take_preset_events(), ok: p.take_ok(), @@ -714,10 +751,25 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, }); } } - if let Some(printer) = d.setup - && let Err(e) = app.run("print.printerSetup", json!({ "printer": printer })) - { - app.status(e); + if let Some(printer) = d.setup { + if d.driver == DriverControls::Properties { + let result = open.properties.open(&printer, |job| app.services.print.as_mut().ok_or("Printing is unavailable")?.driver_properties(job)); + if let Err(error) = &result { + app.status(error); + announce(ctx, error.clone(), Politeness::Polite); + } + // Even if an Enter press was pending in this frame, only an explicit subsequent + // Print action may send a job after the driver dialog closes. + if d.ok.take().is_some() { + on(dialogs, |p| p.answer_ok(Err(tl!("Choose Print to send the job").into()))); + } + } else if let Err(error) = app.run("print.printerSetup", json!({ "printer": printer })) { + app.status(error); + } + } + if available == DriverControls::Properties { + let properties = if d.direct_pdf { String::new() } else { open.properties.summary(&d.printer) }; + on(dialogs, |p| p.set_field("__properties", properties.into())); } let doc = app.session.active().map_or((0, 0), |s| (s.uid, s.revision)); let stamp = (d.settings.to_string(), doc); @@ -845,14 +897,20 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st if matches!(answer.finish, PrintFinish::Print) && applies_paper && (open.papers_pending || open.papers.0 != printer) { return Err("The printer's paper sizes are still loading; try Print again in a moment.".into()); } + let properties = if answer.finish == PrintFinish::Print && !to_file && !direct_pdf { open.properties.for_job(printer)?.cloned() } else { None }; // Laid out first, so a bad range or overlap is refused before anything is kept. app.session.execute("print.preview", &json!({ "settings": settings })).map_err(|e| e.to_string())?; app.run("print.setup", json!({ "settings": settings }))?; match answer.finish { PrintFinish::Print => { let paper = if applies_paper { driver_paper_key(&answer.fields, &open.papers.1) } else { None }; - let job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf, "paper": paper }); - crate::print::run(app, &job).map(|_| ()) + let choice = |name| answer.fields.text(name).filter(|value| !value.is_empty()); + let driver_options = (!to_file && !direct_pdf).then(|| json!({ "color": choice("driverColor"), "duplex": choice("driverDuplex") })); + let job = json!({ + "settings": settings, "printer": printer, "toFile": to_file, + "directPdf": direct_pdf, "paper": paper, "driverOptions": driver_options + }); + crate::print::run_with_driver_settings(app, &job, properties).map(|_| ()) } // Done only keeps the settings. _ => Ok(()), diff --git a/crates/ui-egui/src/dialogs/print/properties.rs b/crates/ui-egui/src/dialogs/print/properties.rs new file mode 100644 index 0000000000..39df975651 --- /dev/null +++ b/crates/ui-egui/src/dialogs/print/properties.rs @@ -0,0 +1,74 @@ +//! Keep the driver's private settings in this print dialog and scope them to its exact queue. + +use std::collections::HashMap; + +use craft::print::Duplex as DriverDuplex; + +use crate::print::{DriverJob, DriverSettings}; + +#[derive(Default)] +pub(super) struct Draft { + by_queue: HashMap, +} + +#[derive(Default)] +struct Queue { + applied: Option, + refusal: Option, +} + +impl Draft { + pub(super) fn open(&mut self, printer: &str, dialog: impl FnOnce(&mut DriverJob) -> Result) -> Result<(), String> { + let queue = self.by_queue.entry(printer.to_owned()).or_default(); + let mut job = DriverJob { printer: Some(printer.to_owned()), driver_settings: queue.applied.clone(), ..DriverJob::default() }; + let result = match dialog(&mut job) { + Ok(false) => return Ok(()), + Ok(true) => job + .driver_settings + .filter(|settings| settings.printer() == printer) + .ok_or_else(|| tl!("The printer did not return properties for this queue").to_string()), + Err(error) => Err(error), + }; + match result { + Ok(settings) => { + queue.applied = Some(settings); + queue.refusal = None; + Ok(()) + } + Err(error) => { + queue.refusal = Some(error.clone()); + Err(error) + } + } + } + + pub(super) fn for_job(&self, printer: &str) -> Result, String> { + let Some(queue) = self.by_queue.get(printer) else { return Ok(None) }; + if let Some(error) = &queue.refusal { + return Err(error.clone()); + } + Ok(queue.applied.as_ref()) + } + + pub(super) fn summary(&self, printer: &str) -> String { + match self.for_job(printer) { + Err(error) => error, + Ok(Some(settings)) => { + let choices = settings.choices(); + let color = match choices.grayscale { + Some(true) => tl!("Grayscale"), + Some(false) => tl!("Color"), + None => tl!("Printer default"), + }; + let sides = match choices.duplex { + Some(DriverDuplex::Off) => tl!("One-sided"), + Some(DriverDuplex::LongEdge) => tl!("Two-sided, long edge"), + Some(DriverDuplex::ShortEdge) => tl!("Two-sided, short edge"), + _ => tl!("Printer default"), + }; + crate::i18n::fmt(tl!("Job properties: {color}, {sides}"), &[("color", color), ("sides", sides)]) + } + Ok(None) => String::new(), + } + } +} diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 35675bda64..4c57342399 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -1599,3 +1599,89 @@ fn print_past_max_pages_neither_prints_nor_saves() { assert!(app.run("file.print", json!({"maxPages": null})).is_err()); assert_eq!(jobs.borrow().len(), 1, "nothing more is sent"); } + +#[test] +fn properties_are_kept_for_the_exact_job_and_a_refusal_sends_nothing() { + use crate::print::{DriverJob, DriverSettings}; + use craft::print::rgb::DevMode; + + fn fixture_properties(printer: &str, marker: u8) -> DriverSettings { + let mut bytes = vec![marker; 228]; + bytes[68..70].copy_from_slice(&220u16.to_le_bytes()); + bytes[70..72].copy_from_slice(&8u16.to_le_bytes()); + bytes[72..76].copy_from_slice(&(0x800u32 | 0x1000).to_le_bytes()); + bytes[92..94].copy_from_slice(&1i16.to_le_bytes()); + bytes[94..96].copy_from_slice(&3i16.to_le_bytes()); + DriverSettings::new(printer, DevMode::from_bytes(bytes).unwrap()) + } + + struct PropertiesPrint { + jobs: Jobs, + opened: Rc>>, + settings: Rc>>, + } + + impl PrintService for PropertiesPrint { + fn printers(&mut self) -> Vec { + MockPrint(self.jobs.clone()).printers() + } + + fn print(&mut self, job: &PrintJob) -> Result { + self.settings.borrow_mut().extend(job.driver_settings.cloned()); + MockPrint(self.jobs.clone()).print(job) + } + + fn has_driver_properties(&self) -> bool { + true + } + + fn driver_properties(&mut self, job: &mut DriverJob) -> Result { + let printer = job.printer.as_deref().unwrap(); + self.opened.borrow_mut().push(printer.to_owned()); + match printer { + "Proofer" if job.driver_settings.is_none() => { + job.driver_settings = Some(fixture_properties(printer, 0x4b)); + Ok(true) + } + "Proofer" => { + assert!(job.driver_settings == Some(fixture_properties(printer, 0x4b))); + job.driver_settings = Some(fixture_properties(printer, 0x6a)); + Ok(false) + } + "Office" => { + assert!(job.driver_settings.is_none()); + Err("The driver's properties are unavailable".into()) + } + _ => panic!("a different printer was requested"), + } + } + } + + let jobs = Jobs::default(); + let opened = Rc::new(RefCell::new(Vec::new())); + let settings = Rc::new(RefCell::new(Vec::new())); + let service = PropertiesPrint { jobs: jobs.clone(), opened: opened.clone(), settings: settings.clone() }; + let services = Services { print: Some(Box::new(service)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + press(&mut app, "Properties…"); + press(&mut app, "Properties…"); + assert!(jobs.borrow().is_empty(), "opening or canceling Properties must never submit a job"); + set(&mut app, "printer", json!("Office")); + pump(&mut app); + press(&mut app, "Properties…"); + confirm(&mut app); + assert!(jobs.borrow().is_empty(), "an unsupported choice must never print with defaults"); + assert!(is_open(&app), "the user can correct the queue or try its properties again"); + assert!(settings.borrow().is_empty()); + assert!(!fields(&app).to_string().contains("devMode")); + + set(&mut app, "printer", json!("Proofer")); + confirm(&mut app); + assert_eq!(*opened.borrow(), ["Proofer", "Proofer", "Office"]); + assert_eq!(jobs.borrow().len(), 1); + assert_eq!(jobs.borrow()[0].0.as_deref(), Some("Proofer")); + assert!(settings.borrow().as_slice() == [fixture_properties("Proofer", 0x4b)]); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e131421a2a..5f22fc3c95 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1992,7 +1992,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), driverOptions?: {color?: color|monochrome, duplex?: oneSided|longEdge|shortEdge} (per native-driver job; either omitted choice keeps the queue or Properties value), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}", ), ( "print.printers", diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index c318aa4aa7..1928fdae5f 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -12,12 +12,13 @@ use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; -use vectorcraft_engine::script::printing::{PreparedPrint, Printers}; +use vectorcraft_engine::script::printing::{JobOptions, OutputColor, PreparedPrint, Printers}; use vectorcraft_pdf::Media; use crate::{VectorcraftApp, io}; pub use craft::print::ui::Printer; +pub use craft::print::{DriverSettings, Job as DriverJob}; /// A print job: a print-ready PDF, every copy and page in it. pub struct PrintJob<'a> { @@ -32,6 +33,12 @@ pub struct PrintJob<'a> { /// Send the PDF to the printer's own PDF interpreter over its RAW TCP port instead of /// spooling it through the platform driver (Windows). pub direct_pdf: bool, + /// Opaque per-job settings returned by the selected queue's Properties dialog. + pub driver_settings: Option<&'a DriverSettings>, + /// Choices supplied for this job through the native print driver. + pub options: JobOptions, + /// VectorCraft's composition used the grayscale composite mode. + pub grayscale_composed: bool, } /// Submission callable from the desktop background worker. @@ -50,6 +57,10 @@ pub trait PrintService { fn applies_paper(&self) -> bool { false } + /// Whether this service accepts explicit job colour and duplex choices. + fn applies_job_options(&self) -> bool { + false + } /// Desktop services can submit on the existing background worker; browser services stay /// on the UI thread to invoke their print dialog. fn shared_print(&self) -> Option { @@ -75,6 +86,14 @@ pub trait PrintService { fn scripts_may_print(&self) -> bool { false } + /// Whether this host can open per-job printer Properties. + fn has_driver_properties(&self) -> bool { + false + } + /// Run the native dialog for a named queue. Cancel leaves the job unchanged. + fn driver_properties(&mut self, _job: &mut DriverJob) -> Result { + Err("This printer has no per-job properties here".into()) + } /// 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()) @@ -357,6 +376,9 @@ const SCRIPT_PRINT_FAILED: &str = "Printing from a script failed"; /// `{background: true}` while the desktop's worker sends them. pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec) -> Result { let service = app.services.print.as_mut().filter(|s| s.scripts_may_print()).ok_or(NO_SCRIPT_PRINTING)?; + if jobs.iter().any(|job| job.options != JobOptions::default()) && !service.applies_job_options() { + return Err(tl!("This print service cannot apply per-job colour or duplex choices").into()); + } let listed: Vec = 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)); @@ -402,7 +424,16 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec) -> Result, jobs: &[PreparedPrint]) -> Result, 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, paper: None, direct_pdf: false }) { + match submit(&PrintJob { + printer: Some(&job.printer), + title: &job.title, + pdf: &job.pdf, + paper: None, + direct_pdf: false, + driver_settings: None, + options: job.options, + grayscale_composed: job.grayscale_composed, + }) { 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())), @@ -433,14 +464,37 @@ pub fn is_paper_keyword(k: &str) -> bool { /// (`format: "postscript"` or a `.ps` path, at `level`, flattened with `flattenerPreset`) is saved /// the same way. pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { + run_with_driver_settings(app, p, None) +} + +/// Submit the settings from the open print dialog without exposing them in command arguments. +pub(crate) fn run_with_driver_settings(app: &mut VectorcraftApp, p: &Value, driver_settings: Option) -> Result { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); let postscript = s("format").as_deref() == Some("postscript") || s("path").is_some_and(|path| fileio::extension(&path) == "ps"); let to_file = p.get("toFile").and_then(Value::as_bool).unwrap_or(false) || s("path").is_some() || postscript; let paper = paper_param(p)?; let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false); + let mut options = p + .get("driverOptions") + .filter(|value| !value.is_null()) + .map(|value| serde_json::from_value::(value.clone()).map_err(|error| error.to_string())) + .transpose()? + .unwrap_or_default(); + if options != JobOptions::default() && (to_file || direct_pdf || !app.services.print.as_ref().is_some_and(|s| s.applies_job_options())) { + return Err(tl!("This print service cannot apply per-job colour or duplex choices").into()); + } if paper.is_some() && (to_file || direct_pdf || !app.services.print.as_ref().is_some_and(|s| s.applies_paper())) { return Err("The print service cannot apply a paper keyword for this job.".into()); } + let printer = s("printer").filter(|n| !n.is_empty()); + if let Some(properties) = &driver_settings + && (to_file + || direct_pdf + || printer.as_deref() != Some(properties.printer()) + || !app.services.print.as_ref().is_some_and(|service| service.has_driver_properties())) + { + return Err(tl!("The job's printer properties do not match its print destination").into()); + } let mut q = json!({}); for k in ["preset", "settings", "format", "level", "flattenerPreset", "maxPages"] { // An explicit null `maxPages` goes on, so the engine rejects it instead of printing every page. @@ -448,6 +502,18 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { q[k] = v.clone(); } } + if let Some(color) = options.color { + if q["settings"].is_null() { + q["settings"] = json!({}); + } + let settings = q["settings"].as_object_mut().ok_or("print settings must be an object")?; + let colors = settings.entry("color").or_insert_with(|| json!({})); + if colors.is_null() { + *colors = json!({}); + } + let colors = colors.as_object_mut().ok_or("print color settings must be an object")?; + colors.insert("grayscale".into(), json!(color == OutputColor::Monochrome)); + } if postscript { // The path is taken off before the engine runs: it can't tell the format from it. q["format"] = json!("postscript"); @@ -477,8 +543,11 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let data = v.as_object_mut().and_then(|o| o.remove("dataBase64")); let pdf = data.as_ref().and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or("the print job has no data")?; let title = app.session.active().map(|d| d.title()).unwrap_or_default(); - let printer = s("printer").filter(|n| !n.is_empty()); let service = app.services.print.as_mut().ok_or("no print service")?; + let grayscale_composed = v["compositeGrayscale"] == true; + if grayscale_composed && options.color.is_none() && service.applies_job_options() && !direct_pdf { + options.color = Some(OutputColor::Monochrome); + } if let Some(submit) = service.shared_print() { let pending_printer = printer.clone(); let mut pending = crate::background::run( @@ -487,8 +556,17 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { format!("Printing {title}"), None, move |_| { - submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf }) - .map(|note| json!({ "note": note, "printer": printer })) + submit(&PrintJob { + printer: printer.as_deref(), + title: &title, + pdf: &pdf, + paper: paper.as_deref(), + direct_pdf, + driver_settings: driver_settings.as_ref(), + options, + grayscale_composed, + }) + .map(|note| json!({ "note": note, "printer": printer })) }, move |app, result| { let receipt = result?; @@ -509,7 +587,16 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { } return Ok(v); } - let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf })?; + let done = service.print(&PrintJob { + printer: printer.as_deref(), + title: &title, + pdf: &pdf, + paper: paper.as_deref(), + direct_pdf, + driver_settings: driver_settings.as_ref(), + options, + grayscale_composed, + })?; app.status(done); v["printer"] = json!(printer); v["printed"] = json!(true); diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index 327592a654..dca7079a4e 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -9,14 +9,15 @@ use craft::ui::dialog::DialogResult; use egui::{Pos2, Rect, vec2}; use serde_json::json; use vectorcraft_engine::Session; +use vectorcraft_engine::script::printing::{JobOptions, OutputColor, Sides}; use super::script_dialogs::{cancel, confirm, fields, is_open, pump, set}; use crate::dialogs::script_run::{self, PRINT_BY_PERSON, PRINT_ENABLE_DELAY_SECS, PRINT_KIND, PRINTS_DROPPED, PrintAnswer, ScriptPrint}; use crate::print::{PrintJob, PrintService, Printer}; use crate::{Services, VectorcraftApp, menus, script_runs}; -/// What the service was sent: (printer, title, bytes). -type Sent = Rc, String, Vec)>>>; +/// The service's recorded printer, title, PDF and explicit options. +type Sent = Rc, String, Vec, JobOptions)>>>; /// 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. @@ -38,7 +39,7 @@ impl PrintService for Spool { } fn print(&mut self, job: &PrintJob) -> Result { - self.sent.borrow_mut().push((job.printer.map(str::to_string), job.title.to_string(), job.pdf.to_vec())); + self.sent.borrow_mut().push((job.printer.map(str::to_string), job.title.to_string(), job.pdf.to_vec(), job.options)); Ok(format!("Sent to {}", job.printer.unwrap_or("the default printer"))) } @@ -46,6 +47,10 @@ impl PrintService for Spool { self.scripts } + fn applies_job_options(&self) -> bool { + true + } + fn shared_print(&self) -> Option { let error = self.spool_error?; Some(std::sync::Arc::new(move |_| if error.is_empty() { Ok("Sent".to_string()) } else { Err(error.to_string()) })) @@ -186,6 +191,28 @@ fn a_scripts_print_job_is_sent_only_when_the_person_clicks_print() { assert!(!asking(&app)); } +#[test] +fn approved_script_jobs_keep_separate_color_and_duplex_choices() { + let (mut app, sent, _) = print_app(true); + app.run("shape.rectangle", json!({ "x": 20, "y": 20, "width": 40, "height": 30 })).unwrap(); + app.run("paint.setFill", json!({ "color": "#2044d0" })).unwrap(); + run( + &mut app, + "var o = new PrintOptions(); o.printerName = 'Lab'; + o.driverColor = 'monochrome'; o.driverDuplex = 'longEdge'; app.activeDocument.print(o); + o.driverColor = 'color'; o.driverDuplex = 'oneSided'; app.activeDocument.print(o); + app.activeDocument.print();", + ); + assert!(asking(&app), "{} {:?}", app.ui.status, app.ui.status_notes); + assert!(sent.borrow().is_empty()); + click_after_delay(&mut app, 10.0, "Print"); + let sent = sent.borrow(); + assert_eq!(sent.len(), 3); + assert_eq!(sent[0].3, JobOptions { color: Some(OutputColor::Monochrome), duplex: Some(Sides::LongEdge) }); + assert_eq!(sent[1].3, JobOptions { color: Some(OutputColor::Color), duplex: Some(Sides::OneSided) }); + assert_eq!(sent[2].3, JobOptions::default()); +} + /// Enter does not print, and Print takes no click until [`PRINT_ENABLE_DELAY_SECS`] after the /// question was first drawn; a click after that prints. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1419fc3194..60052e7863 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3587,7 +3587,9 @@ through `$`: 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 + printer it throws `There is no default printer`. For a printer job, `driverColor` accepts + `default`, `color` and `monochrome`. `driverDuplex` accepts `default`, `oneSided`, `longEdge` + and `shortEdge`. The two choices apply only to that job. `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). The dialog does not open while a text field or text being typed on the canvas has the keyboard; it opens once neither does. The jobs are @@ -13543,7 +13545,10 @@ its raster effects are rendered. In the app, `file.print` with no params opens t dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. `paper` names the printer driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its -`media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is +`media` on macOS and Linux. `driverOptions.color` accepts `color` or `monochrome`, and +`driverOptions.duplex` accepts `oneSided`, `longEdge` or `shortEdge`. Omit either field to keep +the printer's choice. These per-job options require the desktop driver path. +`paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, `localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes