mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 20:18:38 -05:00
Keep Windows printer properties with the selected VectorCraft job
This commit is contained in:
1 parent
d708b00dee
commit
a0ffbeb6ff
6 files changed
+333
-35
No files matched your search
@@ -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")))]
|
||||
|
||||
@@ -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<isize>,
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -36,6 +59,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<bool, String> {
|
||||
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
|
||||
}
|
||||
@@ -223,14 +255,28 @@ mod system {
|
||||
}
|
||||
}
|
||||
pub fn print(job: &PrintJob) -> Result<String, String> {
|
||||
let settings = settings(job)?;
|
||||
if job.direct_pdf {
|
||||
return super::direct_pdf::print(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.
|
||||
let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
|
||||
craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn settings(job: &PrintJob) -> Result<craft::print::Job, String> {
|
||||
// Copies, layout, and marks are already in the PDF. The driver receives one copy at its
|
||||
// composed size, plus choices that were made for this exact queue.
|
||||
let mut settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..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());
|
||||
}
|
||||
Ok(settings)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
|
||||
let target = printer.map(str::trim).filter(|p| !p.is_empty()).or_else(|| default_printer.map(str::trim).filter(|p| !p.is_empty()));
|
||||
@@ -306,6 +352,34 @@ 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",
|
||||
direct_pdf: false,
|
||||
driver_settings: Some(&properties),
|
||||
};
|
||||
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()));
|
||||
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)]
|
||||
|
||||
@@ -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.
|
||||
@@ -112,6 +114,7 @@ struct Open {
|
||||
preview: Option<(Stamp, Arc<Result<Value, String>>)>,
|
||||
/// 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<Paper>),
|
||||
@@ -138,6 +141,7 @@ struct Drained {
|
||||
/// The preset editor's name.
|
||||
name: String,
|
||||
setup: Option<String>,
|
||||
direct_pdf: bool,
|
||||
moves: EditEvents<egui::Pos2>,
|
||||
events: Vec<NamedPresetEvent<String>>,
|
||||
ok: Option<PrintAnswer>,
|
||||
@@ -316,7 +320,11 @@ fn start(
|
||||
}));
|
||||
let taken: Vec<String> = 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()).show(ui)));
|
||||
}
|
||||
let printer = printer_of(&state.settings.destination);
|
||||
let (papers, papers_pending) = papers_of(app, mode, &printer, true);
|
||||
if papers_pending {
|
||||
@@ -352,6 +360,7 @@ fn start(
|
||||
art: None,
|
||||
preview: None,
|
||||
driver,
|
||||
properties: properties::Draft::default(),
|
||||
papers: (printer, papers),
|
||||
papers_pending,
|
||||
media,
|
||||
@@ -464,16 +473,21 @@ fn discover(app: &mut VectorcraftApp) -> mpsc::Receiver<Vec<Printer>> {
|
||||
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.
|
||||
@@ -536,10 +550,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,
|
||||
@@ -551,6 +566,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(),
|
||||
@@ -702,10 +718,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);
|
||||
@@ -824,21 +855,28 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st
|
||||
if open.mode == PrintMode::PresetEditor {
|
||||
return save_preset(app, open, name, settings);
|
||||
}
|
||||
let destination = if answer.finish == PrintFinish::Print {
|
||||
let (printer, to_file) = match &answer.settings.destination {
|
||||
Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false),
|
||||
_ => ("", true),
|
||||
};
|
||||
let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false);
|
||||
let properties = if to_file || direct_pdf { None } else { open.properties.for_job(printer)?.cloned() };
|
||||
Some((printer, to_file, direct_pdf, properties))
|
||||
} 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 (printer, to_file) = match &answer.settings.destination {
|
||||
Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false),
|
||||
_ => ("", true),
|
||||
};
|
||||
let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false);
|
||||
crate::print::run(app, &json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf })).map(|_| ())
|
||||
}
|
||||
// Done only keeps the settings.
|
||||
_ => Ok(()),
|
||||
if let Some((printer, to_file, direct_pdf, properties)) = destination {
|
||||
crate::print::run_with_driver_settings(
|
||||
app,
|
||||
&json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf }),
|
||||
properties,
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Save Preset (the preset editor's OK): `print.presets.save`, then back to Edit → Print Presets on it.
|
||||
|
||||
@@ -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<String, Queue>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Queue {
|
||||
applied: Option<DriverSettings>,
|
||||
refusal: Option<String>,
|
||||
}
|
||||
|
||||
impl Draft {
|
||||
pub(super) fn open(&mut self, printer: &str, dialog: impl FnOnce(&mut DriverJob) -> Result<bool, String>) -> 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<Option<&DriverSettings>, 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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1392,3 +1392,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<RefCell<Vec<String>>>,
|
||||
settings: Rc<RefCell<Vec<DriverSettings>>>,
|
||||
}
|
||||
|
||||
impl PrintService for PropertiesPrint {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
MockPrint(self.jobs.clone()).printers()
|
||||
}
|
||||
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
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<bool, String> {
|
||||
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)]);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ use vectorcraft_engine::script::printing::{PreparedPrint, Printers};
|
||||
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> {
|
||||
@@ -28,6 +29,8 @@ 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>,
|
||||
}
|
||||
|
||||
/// Submission callable from the desktop background worker.
|
||||
@@ -67,6 +70,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<bool, String> {
|
||||
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())
|
||||
@@ -282,7 +293,7 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec<PreparedPri
|
||||
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 }) {
|
||||
match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, direct_pdf: false, driver_settings: None }) {
|
||||
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())),
|
||||
@@ -298,9 +309,24 @@ fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result<String, String>, jo
|
||||
/// (`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<Value, String> {
|
||||
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<DriverSettings>) -> Result<Value, String> {
|
||||
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 printer = s("printer").filter(|n| !n.is_empty());
|
||||
let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false);
|
||||
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.
|
||||
@@ -337,8 +363,6 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
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 direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false);
|
||||
let service = app.services.print.as_mut().ok_or("no print service")?;
|
||||
if let Some(submit) = service.shared_print() {
|
||||
let pending_printer = printer.clone();
|
||||
@@ -348,7 +372,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
format!("Printing {title}"),
|
||||
None,
|
||||
move |_| {
|
||||
submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })
|
||||
submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf, driver_settings: driver_settings.as_ref() })
|
||||
.map(|note| json!({ "note": note, "printer": printer }))
|
||||
},
|
||||
move |app, result| {
|
||||
@@ -370,7 +394,8 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
}
|
||||
return Ok(v);
|
||||
}
|
||||
let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })?;
|
||||
let done =
|
||||
service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf, driver_settings: driver_settings.as_ref() })?;
|
||||
app.status(done);
|
||||
v["printer"] = json!(printer);
|
||||
v["printed"] = json!(true);
|
||||
|
||||
Reference in new issue
Block a user