Refuse explicit print options dropped by Windows drivers

This commit is contained in:
skylar taylor-barrick
2026-10-13 04:48:42 +02:00
parent 6ba4d0b97a
commit 3929c3d14c
4 changed files with 106 additions and 5 deletions
+7
View File
@@ -113,3 +113,10 @@ with `ICM_DONE_OUTSIDEDC`, reapplied after `StartPage`; driver-managed RGB uses
Vendor driver automatic color correction remains a driver setting and requires qualification.
Other platforms return `rgb::PrintError::Unsupported`. The Windows PDF backend and its existing
completion dependency pin are independent of this additional MIT OR Apache-2.0 API.
Native Windows PDF submission checks the driver's validated copy count and explicit
simplex/duplex and grayscale requests before sending. Collation must be retained when both
the page count and copy count exceed one. A driver that drops or changes these options is
refused; select supported options or flatten grayscale into the print-ready page content.
Without an explicit duplex request, the queue default applies. Normal color output retains
the driver's color policy. Single-page or single-copy jobs have no collating order to check.
+9 -1
View File
@@ -411,8 +411,13 @@ fn windows_jobs_reach_the_spooler() {
}
let listed = spool::printers().into_iter().find(|p| p.name == name);
let mixed = test_pdf(&[LETTER, LETTER_LANDSCAPE, LETTER], true);
let job = Job { printer: Some(name.into()), copies: 2, duplex: Some(Duplex::LongEdge), title: "mixed.pdf".into(), ..Job::default() };
let job = Job { printer: Some(name.into()), title: "mixed.pdf".into(), ..Job::default() };
let sent = spool::submit(&mixed, &job);
let duplex_refused = if listed.as_ref().is_some_and(|p| p.two_sided == Some(false)) {
Some(spool::submit(&mixed, &Job { duplex: Some(Duplex::LongEdge), ..job.clone() }))
} else {
None
};
let tabloid = test_pdf(&[TABLOID, LETTER], false);
let shrink = Job { printer: Some(name.into()), scaling: Scaling::ShrinkToFit, title: "shrink".into(), ..Job::default() };
let shrunk = spool::submit(&tabloid, &shrink);
@@ -429,6 +434,9 @@ fn windows_jobs_reach_the_spooler() {
);
assert!(listed.as_ref().is_some_and(|p| p.two_sided.is_some()), "the new printer is listed, its duplex support known: {listed:?}");
assert_eq!(sent.as_deref(), Ok("spooled 3 sheet(s)"), "{sent:?}");
if let Some(refused) = duplex_refused {
assert!(matches!(refused, Err(Error::Spool(ref m)) if m.contains("simplex/duplex") && m.contains("nothing was sent")), "{refused:?}");
}
assert_eq!(shrunk.as_deref(), Ok("spooled 2 sheet(s)"), "{shrunk:?}");
assert!(matches!(exact_refused, Err(Error::Spool(ref m)) if m.contains("one paper size")), "{exact_refused:?}");
assert_eq!(queued.as_deref().map(str::trim), Ok("mixed.pdf 3|shrink.pdf 2"), "one job each, all sheets, in the paused queue: {queued:?}");
+66
View File
@@ -171,6 +171,41 @@ pub(crate) fn verify_ticket(xml: &str, paper: Option<(u32, u32)>, landscape: boo
Ok(size)
}
/// Confirm explicit job options survived driver validation. Collation only changes output
/// when both the document and copy count exceed one. Without a duplex request the queue's
/// default applies; without forced grayscale the driver's normal color policy applies.
pub(crate) fn verify_job_options(xml: &str, job: &Job, pages: usize) -> Result<(), Error> {
let document = roxmltree::Document::parse(xml).map_err(spool_error)?;
let root = document.root_element();
let option = |name: &str| {
root.children()
.find(|n| n.has_tag_name((NS_PSF, "Feature")) && named(*n, name))
.and_then(|f| f.children().find(|n| n.has_tag_name((NS_PSF, "Option"))))
};
let refused = |field: &str| spool_error(format!("the printer's driver did not retain the requested {field}; nothing was sent"));
let copies = job.copies.clamp(1, 999);
if integer(root, "ParameterInit", "JobCopiesAllDocuments") != Some(copies) {
return Err(refused("copy count"));
}
if copies > 1 && pages > 1 && !option("DocumentCollate").is_some_and(|n| named(n, if job.collate { "Collated" } else { "Uncollated" })) {
return Err(refused("collation"));
}
if let Some(duplex) = job.duplex {
let wanted = match duplex {
Duplex::Off => "OneSided",
Duplex::LongEdge => "TwoSidedLongEdge",
Duplex::ShortEdge => "TwoSidedShortEdge",
};
if !option("JobDuplexAllDocumentsContiguously").is_some_and(|n| named(n, wanted)) {
return Err(refused("simplex/duplex setting"));
}
}
if job.grayscale && !option("PageOutputColor").is_some_and(|n| named(n, "Monochrome") || named(n, "Grayscale")) {
return Err(refused("grayscale"));
}
Ok(())
}
/// The widest unprintable margin of the paper, in micrometres, from PrintCapabilities computed
/// for the job's ticket (`PageImageableSize`). The largest of the four, so content centred inside
/// it is clear of every edge whichever way the driver measures. `None` when the driver doesn't say.
@@ -262,6 +297,37 @@ mod tests {
assert!(verify_ticket("<not xml", Some(letter), false).is_err());
}
#[test]
fn a_driver_that_drops_explicit_job_options_is_refused() {
let job = Job { copies: 2, duplex: Some(Duplex::LongEdge), grayscale: true, ..Job::default() };
let xml = ticket_xml(&job, false);
assert!(verify_job_options(&xml, &job, 3).is_ok());
for (from, to) in
[(">2<", ">1<"), ("psk:Collated", "psk:Uncollated"), ("psk:TwoSidedLongEdge", "psk:OneSided"), ("psk:Monochrome", "psk:Color")]
{
assert!(verify_job_options(&xml.replace(from, to), &job, 3).is_err(), "{from}");
}
assert!(verify_job_options(&xml.replace("psk:Collated", "vendor:Collated"), &job, 3).is_err(), "namespace matters");
assert!(verify_job_options(&xml.replace("psk:Monochrome", "psk:Grayscale"), &job, 3).is_ok());
for feature in ["DocumentCollate", "JobDuplexAllDocumentsContiguously", "PageOutputColor"] {
let start = xml.find(&format!("<psf:Feature name=\"psk:{feature}\"")).unwrap();
let end = start + xml[start..].find("</psf:Feature>").unwrap() + "</psf:Feature>".len();
let mut dropped = xml.clone();
dropped.replace_range(start..end, "");
assert!(verify_job_options(&dropped, &job, 3).is_err(), "{feature}");
if feature == "DocumentCollate" {
assert!(verify_job_options(&dropped, &job, 1).is_ok(), "one page has no collating order");
}
}
let default = Job::default();
let xml = ticket_xml(&default, false);
assert!(verify_job_options(&xml, &default, 3).is_ok());
let simplex = Job { duplex: Some(Duplex::Off), ..Job::default() };
assert!(verify_job_options(&ticket_xml(&simplex, false), &simplex, 3).is_ok());
assert!(verify_job_options(&xml, &simplex, 3).is_err(), "explicit simplex must be confirmed");
assert!(verify_job_options("<not xml", &default, 1).is_err());
}
#[test]
fn the_driver_paper_named_like_the_standard_size_is_preferred() {
let paper = |width, height, name, keyword| Paper { width, height, name, keyword };
+24 -4
View File
@@ -38,7 +38,7 @@ pub(crate) fn printers() -> Vec<Printer> {
/// Whether the printer's driver takes two-sided settings: its PrintCapabilities offer a two-sided
/// option for the feature the job's ticket sets. `None` when the capabilities can't be read. A
/// driver without one drops two-sided from the ticket and prints its own way.
/// driver without one cannot confirm an explicit two-sided request, which is refused before submission.
fn two_sided(device: &PrinterDevice) -> Option<bool> {
let capabilities = PrintCapabilities::fetch(device).ok()?;
let duplex = OwnedName::qualified("JobDuplexAllDocumentsContiguously", NS_PSK, Some("psk"));
@@ -146,6 +146,8 @@ pub(crate) fn submit(pdf: &[u8], job: &Job) -> Result<String, Error> {
.name("print job".into())
.spawn_scoped(s, move || {
let (ticket, paper) = driver_ticket(&device, job, first, landscape)?;
let xml = std::str::from_utf8(ticket.get_xml()).map_err(spool_error)?;
ticket::verify_job_options(xml, job, count)?;
let (fit, paper) = match job.scaling {
Scaling::Exact => (Fit::Exact, first),
Scaling::ShrinkToFit => {
@@ -187,21 +189,39 @@ mod tests {
assert!(select_device(Vec::new(), None, None).is_err());
}
/// What a real driver makes of a job's ticket: Letter, portrait, two copies, two-sided on
/// the long edge, grayscale. Sends no job. `CRAFT_PRINT_TEST_PRINTER` names the queue;
/// What a real driver makes of a job's ticket: Letter, portrait, two copies. Checks explicit
/// option retention separately; unsupported options must fail before submission. Sends no job.
/// `CRAFT_PRINT_TEST_PRINTER` names the queue;
/// `CRAFT_PRINT_TEST_TICKET_OUTPUT` keeps the validated ticket, to see which options it kept.
#[test]
#[ignore = "needs CRAFT_PRINT_TEST_PRINTER naming an installed printer; sends no job"]
fn an_installed_driver_validates_the_ticket() {
let name = std::env::var("CRAFT_PRINT_TEST_PRINTER").unwrap();
let device = select_device(PrinterDevice::all().unwrap(), Some(&name), None).unwrap();
let job = Job { copies: 2, duplex: Some(crate::Duplex::LongEdge), grayscale: true, ..Job::default() };
let job = Job { copies: 2, ..Job::default() };
let (ticket, paper) = driver_ticket(&device, &job, (612.0, 792.0), false).unwrap();
ticket::verify_job_options(std::str::from_utf8(ticket.get_xml()).unwrap(), &job, 1).unwrap();
assert_eq!(paper, (215_900, 279_400));
eprintln!("unprintable margin: {} pt", imageable_margin(&device, &ticket));
if let Ok(path) = std::env::var("CRAFT_PRINT_TEST_TICKET_OUTPUT") {
std::fs::write(path, ticket.get_xml()).unwrap();
}
let capabilities = PrintCapabilities::fetch(&device).unwrap();
for (feature, wanted, requested) in [
("PageOutputColor", "Monochrome", Job { grayscale: true, ..Job::default() }),
("JobDuplexAllDocumentsContiguously", "TwoSidedLongEdge", Job { duplex: Some(crate::Duplex::LongEdge), ..Job::default() }),
("DocumentCollate", "Collated", Job { copies: 2, ..Job::default() }),
] {
let (ticket, _) = driver_ticket(&device, &requested, (612.0, 792.0), false).unwrap();
let retained = ticket::verify_job_options(std::str::from_utf8(ticket.get_xml()).unwrap(), &requested, 3);
eprintln!("{feature}={wanted}: {retained:?}");
let offered = capabilities
.options_for_feature(OwnedName::qualified(feature, NS_PSK, Some("psk")))
.any(|o| o.name.as_ref().is_some_and(|n| n.local_name == wanted));
if !offered {
assert!(retained.is_err(), "unsupported explicit option must not be silently dropped");
}
}
}
/// A real job, for checking a printer by hand (paper, or a paused queue's spool file):