diff --git a/apps/pdfcraft-cli/build.rs b/apps/pdfcraft-cli/build.rs index ee77f13f6a..9a6500b7f3 100644 --- a/apps/pdfcraft-cli/build.rs +++ b/apps/pdfcraft-cli/build.rs @@ -6,12 +6,25 @@ //! cross-compile from macOS or Linux still links, unless `PDFCRAFT_REQUIRE_WINRES=1` turns it //! into an error (for release builds). +/// The in-box DLLs only printing uses (Windows.Data.Pdf draws the job, prntvpt reads the +/// driver's print capabilities). Trimmed Windows installations (NTLite) can lack them, and a +/// load-time import of a missing DLL stops the program before `main` (#2630). Delay-loaded, they +/// load on the first print; `pdfcraft_print::spool` checks they exist before calling in. +/// Same list in `apps/pdfcraft{,-cli}/build.rs`, `crates/print/build.rs` and `crates/print/src/spool.rs`. +const DELAY_LOADED: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; + fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-env-changed=PDFCRAFT_REQUIRE_WINRES"); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } + if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { + for dll in DELAY_LOADED { + println!("cargo:rustc-link-arg-bins=/DELAYLOAD:{dll}"); + } + println!("cargo:rustc-link-arg-bins=delayimp.lib"); + } let mut res = winresource::WindowsResource::new(); res.set("ProductName", "PdfCraft") .set("FileDescription", "PdfCraft command-line tool") diff --git a/apps/pdfcraft/build.rs b/apps/pdfcraft/build.rs index 35d519d99e..b6892e7b9d 100644 --- a/apps/pdfcraft/build.rs +++ b/apps/pdfcraft/build.rs @@ -9,6 +9,13 @@ #[path = "src/windows_manifest.rs"] mod windows_manifest; +/// The in-box DLLs only printing uses (Windows.Data.Pdf draws the job, prntvpt reads the +/// driver's print capabilities). Trimmed Windows installations (NTLite) can lack them, and a +/// load-time import of a missing DLL stops the program before `main` (#2630). Delay-loaded, they +/// load on the first print; `pdfcraft_print::spool` checks they exist before calling in. +/// Same list in `apps/pdfcraft{,-cli}/build.rs`, `crates/print/build.rs` and `crates/print/src/spool.rs`. +const DELAY_LOADED: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; + fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=../../assets/app-icon/pdfcraft.ico"); @@ -18,6 +25,12 @@ fn main() { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } + if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") { + for dll in DELAY_LOADED { + println!("cargo:rustc-link-arg-bins=/DELAYLOAD:{dll}"); + } + println!("cargo:rustc-link-arg-bins=delayimp.lib"); + } let mut res = winresource::WindowsResource::new(); res.set_icon("../../assets/app-icon/pdfcraft.ico") .set_icon_with_id("../../assets/app-icon/pdfcraft-document.ico", "2") diff --git a/crates/print/build.rs b/crates/print/build.rs new file mode 100644 index 0000000000..82b3ce3fac --- /dev/null +++ b/crates/print/build.rs @@ -0,0 +1,23 @@ +//! Windows (MSVC) only: delay-load the print DLLs in this crate's own test executable, as the +//! applications do (`apps/pdfcraft{,-cli}/build.rs`), so it starts on a Windows installation that +//! lacks them (#2630) and its tests of the missing-DLL guard in `src/spool.rs` run there. Link +//! arguments from a build script reach only this package's own executables (its tests), never +//! the crates that depend on it; each application sets its own. +//! +//! On every other target this does nothing. + +/// The in-box DLLs only printing uses (Windows.Data.Pdf draws the job, prntvpt reads the +/// driver's print capabilities). Same list in `apps/pdfcraft{,-cli}/build.rs` and +/// `src/spool.rs`. +const DELAY_LOADED: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") || std::env::var("CARGO_CFG_TARGET_ENV").as_deref() != Ok("msvc") { + return; + } + for dll in DELAY_LOADED { + println!("cargo:rustc-link-arg=/DELAYLOAD:{dll}"); + } + println!("cargo:rustc-link-arg=delayimp.lib"); +} diff --git a/crates/print/src/spool.rs b/crates/print/src/spool.rs index a83da3ed26..b16f57026d 100644 --- a/crates/print/src/spool.rs +++ b/crates/print/src/spool.rs @@ -3,9 +3,62 @@ pub use craft_print::{ Duplex, HANDLED_OPTIONS, HAS_PRINTER_PREFERENCES, Job, Printer, PrinterOption, Scaling, lp_args, lpstat_command, parse_lpoptions, parse_lpstat, - parse_lpstat_e, parse_ppd, parse_windows_printers, ppd_text, printers, printers_parsed, + parse_lpstat_e, parse_ppd, parse_windows_printers, ppd_text, printers_parsed, }; +/// Windows: the in-box DLLs printing draws and describes jobs with. The executables delay-load +/// them (`apps/pdfcraft{,-cli}/build.rs`, and `build.rs` for this crate's tests: the same list) +/// so a Windows installation without them still starts (#2630); a call into a missing +/// delay-loaded DLL would end the process, so printing checks for them first. +#[cfg(windows)] +pub(crate) const PRINT_DLLS: [&str; 2] = ["windows.data.pdf.dll", "prntvpt.dll"]; + +/// The first print DLL missing from `system32`, if any. +#[cfg(windows)] +pub(crate) fn missing_print_dll_in(system32: &std::path::Path) -> Option<&'static str> { + PRINT_DLLS.into_iter().find(|dll| !system32.join(dll).is_file()) +} + +#[cfg(all(windows, test))] +thread_local! { + /// Tests: the folder the print DLLs are looked for in, instead of the system's, so the + /// public entry points can be checked against a Windows that lacks them. + pub(crate) static SYSTEM32_FOR_TEST: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Tests: how many times [`printers`] asked the system's printer backend, so a test can tell + /// the guard answered without relying on the machine having no printers. + pub(crate) static PRINTER_BACKEND_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The first print DLL this Windows installation lacks. `None` when all are there, and when the +/// system folder is unknown (the loader then decides, as before). +fn missing_print_dll() -> Option<&'static str> { + #[cfg(windows)] + { + #[cfg(test)] + if let Some(dir) = SYSTEM32_FOR_TEST.with(|d| d.borrow().clone()) { + return missing_print_dll_in(&dir); + } + let root = std::env::var_os("SystemRoot").or_else(|| std::env::var_os("windir"))?; + missing_print_dll_in(&std::path::Path::new(&root).join("System32")) + } + #[cfg(not(windows))] + None +} + +fn unavailable(dll: &str) -> crate::PrintError { + crate::PrintError::Spool(format!("printing needs {dll}, which this Windows installation lacks; use Save as PDF instead")) +} + +/// The system's printers; none on a Windows installation without the print DLLs. +pub fn printers() -> Vec { + if missing_print_dll().is_some() { + return Vec::new(); + } + #[cfg(all(windows, test))] + PRINTER_BACKEND_CALLS.with(|c| c.set(c.get().saturating_add(1))); + craft_print::printers() +} + /// The driver's job options for a printer (CUPS: its PPD, with the queue's current defaults); /// empty when it has none or on other platforms. Reads files and runs `lpoptions`, so call it /// when the user asks, not every frame. @@ -192,12 +245,18 @@ fn spooled(job: &Job) -> Job { } pub fn submit(pdf: &[u8], job: &Job) -> Result { + if let Some(dll) = missing_print_dll() { + return Err(unavailable(dll)); + } craft_print::submit(pdf, &spooled(job)).map_err(|e| crate::PrintError::Spool(e.to_string())) } /// [`submit`], told `(sent, sheets)` as each sheet reaches the spooler (Windows; CUPS takes the /// whole PDF at once and reports nothing). pub fn submit_with_progress(pdf: &[u8], job: &Job, progress: &mut dyn FnMut(usize, usize)) -> Result { + if let Some(dll) = missing_print_dll() { + return Err(unavailable(dll)); + } craft_print::submit_with_progress(pdf, &spooled(job), progress).map_err(|e| crate::PrintError::Spool(e.to_string())) } diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs index a1026308ea..fb947c06f1 100644 --- a/crates/print/src/tests.rs +++ b/crates/print/src/tests.rs @@ -1334,6 +1334,52 @@ fn contents_pieces_join_with_a_space_across_a_trailing_comment() { assert_eq!(form_strings(printed_ctrl), [b"HIDDEN".to_vec(), b"SHOWN".to_vec()]); } +/// #2630: a Windows installation without the print DLLs is told so, before anything calls into +/// a delay-loaded DLL that is not there. +#[cfg(windows)] +#[test] +fn missing_print_dlls_are_named() { + use crate::spool::{PRINT_DLLS, missing_print_dll_in}; + let dir = std::env::temp_dir().join(format!("pdfcraft-print-dlls-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + assert_eq!(missing_print_dll_in(&dir), Some(PRINT_DLLS[0])); + std::fs::write(dir.join(PRINT_DLLS[0]), b"").unwrap(); + assert_eq!(missing_print_dll_in(&dir), Some(PRINT_DLLS[1])); + std::fs::write(dir.join(PRINT_DLLS[1]), b"").unwrap(); + assert_eq!(missing_print_dll_in(&dir), None); + let _ = std::fs::remove_dir_all(&dir); +} + +/// #2630: on a Windows without the print DLLs, the public entry points answer before any call +/// into the delay-loaded DLLs: no printers, and printing refused naming the DLL. The job names a +/// printer that doesn't exist and the bytes aren't a PDF, so a missing guard fails here with +/// another error rather than reaching a real printer. +#[cfg(windows)] +#[test] +fn printing_without_the_print_dlls_is_refused_before_the_spooler() { + use crate::spool::{PRINT_DLLS, PRINTER_BACKEND_CALLS, SYSTEM32_FOR_TEST, printers, submit, submit_with_progress}; + let dir = std::env::temp_dir().join(format!("pdfcraft-print-no-dlls-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + SYSTEM32_FOR_TEST.with(|d| *d.borrow_mut() = Some(dir.clone())); + let job = crate::spool::Job { printer: Some("PdfCraft test: no such printer".into()), ..Default::default() }; + let named = |r: Result| match r { + Err(crate::PrintError::Spool(m)) => m.contains(PRINT_DLLS[0]), + _ => false, + }; + assert!(named(submit(b"not a PDF", &job)), "submit names the missing DLL"); + let mut called = false; + assert!(named(submit_with_progress(b"not a PDF", &job, &mut |_, _| called = true)), "submit_with_progress names it"); + assert!(!called, "no sheet reached a spooler"); + // Not only an empty list, which a machine without printers gives anyway: the backend wasn't asked. + PRINTER_BACKEND_CALLS.with(|c| c.set(0)); + assert!(printers().is_empty(), "no printers are listed"); + assert_eq!(PRINTER_BACKEND_CALLS.with(|c| c.get()), 0, "the printer backend wasn't asked"); + SYSTEM32_FOR_TEST.with(|d| *d.borrow_mut() = None); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_page_form_without_annotations_shares_the_pages_indirect_resources() { let mut doc = fixture(2);