From 8805761140411115344af4cc092cd19296a77ecd Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 17:25:03 +0000 Subject: [PATCH] platform-w7: net change of 2 commits - platform-w7: written from its sheet - platform-w7: review fixes (review-1) --- crates/print/Cargo.toml | 7 + crates/print/src/browser.rs | 66 ++++- crates/print/src/lib.rs | 2 + crates/print/src/spool.rs | 212 +++++++++++++-- crates/print/src/spool/isolated.rs | 369 ++++++++++++++++++++++++- crates/print/src/spool_tests.rs | 417 +++++++++++++++++++++++++++++ 6 files changed, 1048 insertions(+), 25 deletions(-) create mode 100644 crates/print/src/spool_tests.rs diff --git a/crates/print/Cargo.toml b/crates/print/Cargo.toml index 96a854bf4..a159747fa 100644 --- a/crates/print/Cargo.toml +++ b/crates/print/Cargo.toml @@ -66,6 +66,13 @@ roxmltree = "0.21" # Inflating the print-ready PDF's cross-reference and object streams (src/sheets.rs). miniz_oxide = "0.9" +[target.'cfg(target_arch = "wasm32")'.dependencies] +# The browser's print dialog (src/browser.rs): the PDF as an object URL in a hidden iframe +# (MIT OR Apache-2.0). +js-sys = "0.3" +wasm-bindgen = "0.2" +web-sys = { version = "0.3", features = ["Blob", "BlobPropertyBag", "Url", "HtmlIFrameElement", "HtmlElement", "Element", "Node", "Document", "Window", "CssStyleDeclaration"] } + [dev-dependencies] craft-ui = { workspace = true, features = ["testing"] } tempfile = "3" diff --git a/crates/print/src/browser.rs b/crates/print/src/browser.rs index 9f7fff303..3f95dc9a9 100644 --- a/crates/print/src/browser.rs +++ b/crates/print/src/browser.rs @@ -1,7 +1,69 @@ //! Printing in the browser. +use wasm_bindgen::JsCast; + +/// The hidden iframe the last print loaded its PDF into. +const PRINT_FRAME_ID: &str = "craft-print-frame"; + /// Prints `pdf` through one hidden iframe; the wasm `Spool` backend calls it. +/// +/// The PDF opens as an object URL in a hidden iframe whose own `print()` runs once it has +/// loaded: the browser's print dialog on the PDF, without a download or a popup window the +/// browser might block. The previous print's iframe and object URL are removed first, so only +/// one copy of a document's PDF stays in the page (the last one may still be printing). pub fn print_pdf(pdf: &[u8]) -> Result<(), String> { - let _ = pdf; - todo!("pf.C-PR4") + let js = |e: wasm_bindgen::JsValue| format!("{e:?}"); + let window = web_sys::window().ok_or("no window")?; + let document = window.document().ok_or("no document")?; + + if let Some(old) = document.get_element_by_id(PRINT_FRAME_ID) { + if let Ok(frame) = old.clone().dyn_into::() { + let src = frame.src(); + if src.starts_with("blob:") { + web_sys::Url::revoke_object_url(&src).ok(); + } + } + old.remove(); + } + + let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(pdf)); + let opts = web_sys::BlobPropertyBag::new(); + opts.set_type("application/pdf"); + let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?; + let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?; + + let iframe: web_sys::HtmlIFrameElement = + match document.create_element("iframe").map_err(js).and_then(|e| e.dyn_into().map_err(|_| "not an iframe".to_string())) { + Ok(f) => f, + Err(e) => { + web_sys::Url::revoke_object_url(&url).ok(); + return Err(e); + } + }; + iframe.set_id(PRINT_FRAME_ID); + let attached = iframe + .style() + .set_property("display", "none") + .map_err(js) + .and_then(|()| document.body().ok_or_else(|| "no body".to_string())) + .and_then(|body| body.append_child(&iframe).map_err(js)); + if let Err(e) = attached { + iframe.remove(); + web_sys::Url::revoke_object_url(&url).ok(); + return Err(e); + } + + // `onload` fires once the PDF has rendered inside the iframe; printing before that shows a + // blank page. The handler is set before `src` so a fast or cached load can't fire unheard. + let iframe_for_load = iframe.clone(); + let on_load = wasm_bindgen::closure::Closure::once_into_js(move || { + if let Some(w) = iframe_for_load.content_window() { + // Some browsers (Firefox with its built-in PDF viewer) print fine but report a + // benign cross-origin-style error back on this call. + let _ = w.print(); + } + }); + iframe.set_onload(Some(on_load.unchecked_ref())); + iframe.set_src(&url); + Ok(()) } diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rs index 6b6045306..02f26c655 100644 --- a/crates/print/src/lib.rs +++ b/crates/print/src/lib.rs @@ -21,6 +21,8 @@ mod progress; #[cfg(any(test, windows))] mod sheets; #[cfg(test)] +mod spool_tests; +#[cfg(test)] mod tests; #[cfg(any(test, windows))] mod ticket; diff --git a/crates/print/src/spool.rs b/crates/print/src/spool.rs index edcc31b62..ea7147e91 100644 --- a/crates/print/src/spool.rs +++ b/crates/print/src/spool.rs @@ -1,69 +1,172 @@ //! The print job layer: discovery of printers and submission of jobs as host jobs, per platform. #[cfg(any(windows, test))] -mod isolated; +pub mod isolated; -use std::marker::PhantomData; -use std::sync::Arc; use std::sync::mpsc::Receiver; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use crate::Job; -#[cfg(windows)] -pub use isolated::helper_main; - /// The print job layer, run as host jobs. Desktop backends call the existing /// [`submit_cancellable`](crate::submit_cancellable) and [`printer_queues`](crate::printer_queues). /// On wasm the backend prints through the browser, lists no printers and /// [`chooses_printer`](Spool::chooses_printer) is false. #[derive(Clone)] pub struct Spool { - stub: PhantomData<()>, + inner: Arc, +} + +struct Inner { + jobs: Arc, + backend: Arc, + /// Every submitted job until it is done or shut down, oldest first: `Jobs::spawn` gives no + /// handle, so shutdown reaches a job only through its entry. + entries: Mutex>, +} + +/// Whether a job's work has ended. A job being sent is told apart from a waiting one only by +/// its cancel's answer, at the moment it is asked; it is never stored. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Phase { + Waiting, + Done, +} + +type Done = Arc<(Mutex, Condvar)>; + +struct Entry { + cancel: Arc bool + Send + Sync>, + waits_after_cancel: bool, + done: Done, +} + +impl Entry { + fn finished(&self) -> bool { + *lock(&self.done.0) == Phase::Done + } + + fn wait(&self) { + let (phase, signal) = &*self.done; + let mut phase = lock(phase); + while *phase == Phase::Waiting { + phase = signal.wait(phase).unwrap_or_else(PoisonError::into_inner); + } + } +} + +/// Marks its job done when dropped: after the job ran, or when the host dropped it unrun (a +/// thread that could not start), so shutdown never waits on a job that will not run. +struct Finish(Done); + +impl Drop for Finish { + fn drop(&mut self) { + *lock(&self.0.0) = Phase::Done; + self.0.1.notify_all(); + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) } impl Spool { /// A spool for this platform that runs its work on `jobs`. pub fn new(jobs: Arc) -> Self { - let _ = jobs; - todo!("pf.C-PR1") + Self::with_backend(jobs, Arc::new(SystemBackend)) } /// A spool over `backend`, for trials and tests that fake the platform. pub fn with_backend(jobs: Arc, backend: Arc) -> Self { - let _ = (jobs, backend); - todo!("pf.C-PR1") + Self { inner: Arc::new(Inner { jobs, backend, entries: Mutex::new(Vec::new()) }) } } /// Whether the user chooses a printer (false on wasm, where the browser's dialog does). pub fn chooses_printer(&self) -> bool { - todo!("pf.C-PR1") + self.inner.backend.chooses_printer() } /// Lists the printers in a job; the list arrives on the receiver. pub fn discover(&self) -> Receiver> { - todo!("pf.C-PR1") + self.listed(|printer| printer) } /// The printer discovery the print dialog takes, mapping each printer to `ui::Printer`. #[cfg(feature = "ui")] pub fn discoverer(&self) -> crate::ui::Discover { - todo!("pf.C-PR1") + let spool = self.clone(); + Box::new(move || { + spool.listed(|printer| crate::ui::Printer { name: printer.name, label: printer.description, default: printer.default }) + }) + } + + /// Asks the backend for its printers in a job and sends them through `map`; a platform that + /// lists none sends an empty list. + fn listed(&self, map: impl Fn(crate::Printer) -> T + Send + 'static) -> Receiver> { + let (sender, receiver) = std::sync::mpsc::channel(); + let backend = self.inner.backend.clone(); + self.inner.jobs.spawn( + "print-discovery", + Box::new(move || { + let printers = backend.printers().unwrap_or_default(); + let _ = sender.send(printers.into_iter().map(map).collect()); + }), + ); + receiver } /// Prints `pdf` with `job` in a job; the job's id or the failure arrives on the receiver. + /// The job's copies are clamped to 1..=999, as [`Job::copies`] documents. pub fn submit(&self, pdf: Vec, job: Job) -> Receiver> { - let _ = (pdf, job); - todo!("pf.C-PR1") + let job = Job { copies: job.copies.clamp(1, 999), ..job }; + let pending = self.inner.backend.prepare(pdf, job); + let (sender, receiver) = std::sync::mpsc::channel(); + let done: Done = Arc::new((Mutex::new(Phase::Waiting), Condvar::new())); + { + let mut entries = lock(&self.inner.entries); + entries.retain(|entry| !entry.finished()); + entries.push(Entry { cancel: Arc::from(pending.cancel), waits_after_cancel: pending.waits_after_cancel, done: done.clone() }); + } + let finish = Finish(done); + let run = pending.run; + // The entry is listed before the spawn: `InlineJobs` runs the job inside this call. + self.inner.jobs.spawn( + "print-submit", + Box::new(move || { + let _finish = finish; + let sent = run().map_err(|error| error.to_string()); + let _ = sender.send(sent); + }), + ); + receiver } - /// Cancels the latest submitted job; whether there was one to cancel. + /// Cancels the latest submitted job; whether there was one to cancel. `true` also when no job + /// was submitted; `false` when the latest job was already being sent (or has been sent), so + /// its receipt still arrives. pub fn cancel_latest(&self) -> bool { - todo!("pf.C-PR1") + // Called outside the lock: a backend's cancel may wait for an acknowledgement. + let latest = lock(&self.inner.entries).last().map(|entry| entry.cancel.clone()); + latest.is_none_or(|cancel| cancel()) } - /// Stops the spool's work. + /// Stops the spool's work: every job is cancelled first, so a waiting job can't start sending + /// while another is waited for; then it waits for the jobs already being sent (their cancel + /// answered `false`) and for those whose backend still answers after a cancel, so the spooler + /// has them before the process exits. A job still waiting (on a sleeping printer's driver, say) + /// is never sent and not waited for. pub fn shutdown(&self) { - todo!("pf.C-PR1") + let entries = std::mem::take(&mut *lock(&self.inner.entries)); + let finishing: Vec = entries + .into_iter() + .filter(|entry| { + let cancelled = (entry.cancel)(); + entry.waits_after_cancel || !cancelled + }) + .collect(); + for entry in &finishing { + entry.wait(); + } } } @@ -74,14 +177,81 @@ pub trait SpoolBackend: Send + Sync { /// Prepares the print of `pdf` with `job`: how to cancel it and how to run it. fn prepare(&self, pdf: Vec, job: Job) -> Pending; + + /// Whether the user chooses a printer for a job; false where the platform's own print dialog + /// does (the browser). [`Spool::chooses_printer`] answers it. + + fn chooses_printer(&self) -> bool { + true + } } /// A prepared print: run it on a job, cancel it from anywhere. pub struct Pending { - /// Cancels the print; whether it was still cancellable. + /// Cancels the print. `true`: it will never be sent. `false`: it was already being sent, + /// which completes as usual (or it has been sent). pub cancel: Box bool + Send + Sync>, /// Sends the print and answers the job's id. pub run: Box Result + Send>, /// The print still ends with an answer after a cancel, which the caller waits for. pub waits_after_cancel: bool, } + +/// This platform's spooler: `lp` through [`submit_cancellable`](crate::submit_cancellable) on +/// macOS and Linux, a helper process per job on Windows, the browser's print dialog on wasm. +struct SystemBackend; + +impl SpoolBackend for SystemBackend { + fn printers(&self) -> Option> { + #[cfg(not(target_arch = "wasm32"))] + { + // No driver is asked: a networked printer in power save can hold a capability query + // for a long time, and the list must not wait on it. + Some(crate::printer_queues()) + } + #[cfg(target_arch = "wasm32")] + { + None + } + } + + fn chooses_printer(&self) -> bool { + cfg!(not(target_arch = "wasm32")) + } + + fn prepare(&self, pdf: Vec, job: Job) -> Pending { + #[cfg(windows)] + { + // One process per job: a cancelled driver cannot keep another job's provider lock. + let submission = isolated::Submission::new(); + let token = submission.clone(); + Pending { + cancel: Box::new(move || submission.cancel()), + run: Box::new(move || token.submit(&pdf, &job).map_err(crate::Error::Spool)), + waits_after_cancel: true, + } + } + #[cfg(target_arch = "wasm32")] + { + Pending { + // The browser's dialog takes the job at once; there is nothing left to cancel. + cancel: Box::new(|| false), + run: Box::new(move || { + let _ = job; + crate::browser::print_pdf(&pdf).map(|()| String::new()).map_err(crate::Error::Spool) + }), + waits_after_cancel: false, + } + } + #[cfg(not(any(windows, target_arch = "wasm32")))] + { + let cancel = crate::Cancel::new(); + let token = cancel.clone(); + Pending { + cancel: Box::new(move || cancel.cancel()), + run: Box::new(move || crate::submit_cancellable(&pdf, &job, &mut |_, _| {}, &token)), + waits_after_cancel: false, + } + } + } +} diff --git a/crates/print/src/spool/isolated.rs b/crates/print/src/spool/isolated.rs index a11fc7159..d371bdb79 100644 --- a/crates/print/src/spool/isolated.rs +++ b/crates/print/src/spool/isolated.rs @@ -1,10 +1,375 @@ //! The Windows print helper process and its protocol. The module compiles under //! `cfg(any(windows, test))` so its protocol trials run on every platform. +//! +//! One driver submission per process: a cancelled driver cannot retain another job's provider +//! lock. The child acknowledges its [`Cancel`](crate::Cancel) token before it exits. + +use std::{ + io::{BufRead, BufReader, Read, Write}, + path::Path, + process::{Child, ChildStdin, Command, Stdio}, + sync::{Arc, Condvar, Mutex}, + time::Duration, +}; + +use serde::{Deserialize, Serialize}; + +#[cfg(windows)] +const FLAG: &str = "--craft-print-helper"; +const PREFIX: &str = "CRAFT_PRINT:"; +const MAX_MESSAGE: u64 = 64 * 1024; +/// The job's options, and a driver's settings of up to 1 MiB written as hex. +const MAX_REQUEST: u64 = MAX_MESSAGE + 2 * 1024 * 1024; +const MAX_PDF: u64 = 512 * 1024 * 1024; +pub(crate) const CANCELLED: &str = "the print job was cancelled before anything was sent to the printer"; + +/// The wire form of [`crate::Duplex`], kept apart so the public type carries no serde. +#[derive(Serialize, Deserialize)] +enum Duplex { + Off, + LongEdge, + ShortEdge, +} + +/// The wire form of a [`crate::Job`]. +#[derive(Serialize, Deserialize)] +pub(crate) struct Request { + printer: Option, + copies: u32, + collate: bool, + duplex: Option, + grayscale: bool, + grey_pages: bool, + shrink: bool, + title: String, + options: Vec<(String, String)>, + /// The printer the driver's settings were chosen for, and their DEVMODE as hex. + driver_settings: Option<(String, String)>, +} + +impl Request { + /// Preserve all spooler options in a platform-independent wire representation. + pub(crate) fn from_job(job: &crate::Job) -> Self { + Self { + printer: job.printer.clone(), + copies: job.copies, + collate: job.collate, + duplex: job.duplex.map(|d| match d { + crate::Duplex::Off => Duplex::Off, + crate::Duplex::LongEdge => Duplex::LongEdge, + crate::Duplex::ShortEdge => Duplex::ShortEdge, + }), + grayscale: job.grayscale, + grey_pages: job.grey_pages, + shrink: job.scaling == crate::Scaling::ShrinkToFit, + title: job.title.clone(), + options: job.options.clone(), + driver_settings: job.driver_settings.as_ref().map(|settings| (settings.printer().to_owned(), settings.dev_mode().to_hex())), + } + } + + /// Restore the job without substituting printer defaults or changing copy semantics. + pub(crate) fn job(self) -> Result { + let driver_settings = match self.driver_settings { + Some((printer, hex)) => Some(crate::DriverSettings::new(printer, crate::rgb::DevMode::from_hex(&hex).map_err(error)?)), + None => None, + }; + Ok(crate::Job { + printer: self.printer, + copies: self.copies, + collate: self.collate, + duplex: self.duplex.map(|d| match d { + Duplex::Off => crate::Duplex::Off, + Duplex::LongEdge => crate::Duplex::LongEdge, + Duplex::ShortEdge => crate::Duplex::ShortEdge, + }), + grayscale: self.grayscale, + grey_pages: self.grey_pages, + scaling: if self.shrink { crate::Scaling::ShrinkToFit } else { crate::Scaling::Exact }, + title: self.title, + options: self.options, + driver_settings, + }) + } +} + +#[derive(Serialize, Deserialize)] +enum Event { + Ready, + Cancelled, + Sending, + Done(Result), +} + +enum State { + Starting, + Waking(Arc>), + Running(ChildStdin), + Sending(ChildStdin), + Cancelled, + Finished, +} + +/// The parent side of one helper process: its lifecycle, shared between the job that runs it +/// and whoever cancels it. +#[derive(Clone)] +pub(crate) struct Submission(Arc<(Mutex, Condvar)>); + +impl Submission { + /// Create one submission whose driver cannot run until the parent grants startup. + pub(crate) fn new() -> Self { + Self(Arc::new((Mutex::new(State::Starting), Condvar::new()))) + } + + /// Recover the lifecycle state after poisoning without invoking another driver call. + fn state(&self) -> std::sync::MutexGuard<'_, State> { + self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Only an acknowledgement of the child's token can cancel a running helper. A timeout + /// is a refusal, never permission to kill a process that may already be sending. + pub(crate) fn cancel(&self) -> bool { + let mut state = self.state(); + match &mut *state { + State::Starting => { + *state = State::Cancelled; + return true; + } + State::Waking(child) => { + let _ = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).kill(); + *state = State::Cancelled; + return true; + } + State::Cancelled => return true, + State::Finished | State::Sending(_) => return false, + State::Running(input) => { + if input.write_all(b"cancel\n").and_then(|_| input.flush()).is_err() { + return false; + } + } + } + let (state, _) = self + .0 + .1 + .wait_timeout_while(state, Duration::from_secs(1), |s| matches!(s, State::Running(_))) + .unwrap_or_else(std::sync::PoisonError::into_inner); + matches!(*state, State::Cancelled) + } + + /// Submit through this executable's private helper mode and await its final receipt. + #[cfg(windows)] + pub(crate) fn submit(&self, pdf: &[u8], job: &crate::Job) -> Result { + self.submit_with(pdf, job, |directory| { + let mut command = Command::new(std::env::current_exe()?); + command.arg(FLAG).arg(directory); + Ok(command) + }) + } + + /// Publish a terminal state on every result, waking a cancellation caller awaiting an ack. + /// `command` makes the helper process for the private input folder. + pub(crate) fn submit_with(&self, pdf: &[u8], job: &crate::Job, command: impl FnOnce(&Path) -> std::io::Result) -> Result { + let result = self.run(pdf, job, command); + let mut state = self.state(); + if !matches!(*state, State::Cancelled) { + *state = State::Finished; + } + self.0.1.notify_all(); + if matches!(*state, State::Cancelled) { Err(CANCELLED.into()) } else { result } + } + + /// Own the private inputs and child until receipt, acknowledged cancellation or failure. + fn run(&self, pdf: &[u8], job: &crate::Job, command: impl FnOnce(&Path) -> std::io::Result) -> Result { + if matches!(*self.state(), State::Cancelled) { + return Err(CANCELLED.into()); + } + if pdf.len() as u64 > MAX_PDF { + return Err("the print PDF exceeds the 512 MiB helper limit".into()); + } + let request = serde_json::to_vec(&Request::from_job(job)).map_err(error)?; + if request.len() as u64 > MAX_REQUEST { + return Err("the print settings exceed the helper message limit".into()); + } + let directory = tempfile::tempdir().map_err(error)?; + std::fs::write(directory.path().join("job.json"), request).map_err(error)?; + std::fs::write(directory.path().join("input.pdf"), pdf).map_err(error)?; + let child = + command(directory.path()).map_err(error)?.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().map_err(error)?; + let child = Arc::new(Mutex::new(child)); + let outcome = (|| { + let (input, output) = { + let mut process = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + (process.stdin.take().ok_or("print helper has no input pipe")?, process.stdout.take().ok_or("print helper has no output pipe")?) + }; + { + let mut state = self.state(); + if matches!(*state, State::Cancelled) { + return Err(CANCELLED.into()); + } + *state = State::Waking(child.clone()); + } + let mut output = BufReader::new(output); + loop { + let message = line(&mut output)?.ok_or("the print helper stopped before it was ready")?; + let Some((_, json)) = message.split_once(PREFIX) else { continue }; + if !matches!(serde_json::from_str::(json).map_err(error)?, Event::Ready) { + return Err("the print helper did not acknowledge startup".into()); + } + break; + } + { + let mut state = self.state(); + if matches!(*state, State::Cancelled) { + return Err(CANCELLED.into()); + } + *state = State::Running(input); + if let State::Running(input) = &mut *state { + input.write_all(b"start\n").and_then(|_| input.flush()).map_err(error)?; + } + } + while let Some(line) = line(&mut output)? { + let Some((_, json)) = line.split_once(PREFIX) else { continue }; + match serde_json::from_str::(json).map_err(error)? { + Event::Ready => return Err("the print helper repeated its startup acknowledgement".into()), + Event::Cancelled => { + *self.state() = State::Cancelled; + self.0.1.notify_all(); + return Err(CANCELLED.into()); + } + Event::Sending => { + let mut state = self.state(); + let previous = std::mem::replace(&mut *state, State::Finished); + *state = match previous { + State::Running(input) | State::Sending(input) => State::Sending(input), + other => other, + }; + self.0.1.notify_all(); + } + Event::Done(result) => return result, + } + } + Err("the print helper stopped without a receipt".into()) + })(); + // A cancelled child has acknowledged that it cannot send. Other outcomes are terminal + // receipts or a broken protocol/pipe; reap the process and its private input files. + if outcome.is_err() { + let _ = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).kill(); + } + let status = child.lock().unwrap_or_else(std::sync::PoisonError::into_inner).wait().map_err(error)?; + if outcome.is_ok() && !status.success() { + return Err("the print helper failed after its receipt".into()); + } + outcome + } +} + +/// Keep helper transport failures distinct from a printer's own error message. +fn error(error: impl std::fmt::Display) -> String { + format!("print helper: {error}") +} + +/// Read at most one byte beyond the cap so oversized files fail without unbounded allocation. +pub(crate) fn bounded(mut input: impl Read, limit: u64) -> Result, String> { + let mut bytes = Vec::new(); + input.by_ref().take(limit.saturating_add(1)).read_to_end(&mut bytes).map_err(error)?; + if bytes.len() as u64 > limit { Err("print helper input exceeds its limit".into()) } else { Ok(bytes) } +} + +/// Read one bounded UTF-8 protocol record, distinguishing EOF from an oversized message. +pub(crate) fn line(input: &mut impl BufRead) -> Result, String> { + let mut bytes = Vec::new(); + input.take(MAX_MESSAGE + 1).read_until(b'\n', &mut bytes).map_err(error)?; + if bytes.len() as u64 > MAX_MESSAGE { + return Err("print helper message exceeds its limit".into()); + } + if bytes.is_empty() { Ok(None) } else { String::from_utf8(bytes).map(|s| Some(s.trim_end().to_owned())).map_err(error) } +} + +/// Serialize complete events under stdout's lock so the driver and listener cannot interleave. +fn emit(event: &Event) -> Result<(), String> { + let mut output = std::io::stdout().lock(); + write!(output, "{PREFIX}").map_err(error)?; + serde_json::to_writer(&mut output, event).map_err(error)?; + writeln!(output).and_then(|_| output.flush()).map_err(error) +} + +/// Remove both plaintext inputs even when one fails; already-removed inputs count as success. +pub(crate) fn remove_inputs(directory: &Path) -> Result<(), String> { + let mut first_error = None; + for name in ["job.json", "input.pdf"] { + if let Err(failure) = std::fs::remove_file(directory.join(name)) + && failure.kind() != std::io::ErrorKind::NotFound + { + first_error.get_or_insert_with(|| error(format!("could not remove {name}: {failure}"))); + } + } + first_error.map_or(Ok(()), Err) +} + +/// The child side: load and erase the private inputs before driver work, while an independent +/// listener can cancel. `cancel_request` cancels the token and answers whether it was still +/// cancellable; `submit` is the driver. +pub(crate) fn helper( + directory: &Path, + cancel_request: impl Fn(&crate::Cancel) -> bool + Send + 'static, + submit: impl FnOnce(&[u8], &crate::Job, &crate::Cancel) -> Result, +) -> Result<(), String> { + let mut input = BufReader::new(std::io::stdin()); + emit(&Event::Ready)?; + if line(&mut input)?.as_deref() != Some("start") { + return Err("print helper requires a start acknowledgement".into()); + } + let cancel = crate::Cancel::new(); + let listener = cancel.clone(); + std::thread::Builder::new() + .name("print-cancel".into()) + .spawn(move || { + loop { + match line(&mut input) { + Ok(Some(command)) if command == "cancel" => { + if cancel_request(&listener) { + let _ = emit(&Event::Cancelled); + std::process::exit(0); + } + if emit(&Event::Sending).is_err() { + break; + } + } + _ => break, + } + } + // If the parent disappears, never leave a waiting driver process behind. Sending + // jobs finish normally so the OS gets their pages even if the UI has gone away. + if cancel_request(&listener) { + std::process::exit(0); + } + }) + .map_err(error)?; + let request: Request = + serde_json::from_slice(&bounded(std::fs::File::open(directory.join("job.json")).map_err(error)?, MAX_REQUEST)?).map_err(error)?; + let pdf = bounded(std::fs::File::open(directory.join("input.pdf")).map_err(error)?, MAX_PDF)?; + remove_inputs(directory)?; + let result = submit(&pdf, &request.job()?, &cancel); + emit(&Event::Done(result)) +} /// Runs the print helper when the process was started with `--craft-print-helper`: the app's /// `main` calls it first and exits with the code when it answers `Some`. The helper's reply lines -/// start `CRAFT_PRINT:`. +/// start `CRAFT_PRINT:`. It reads only its first argument, so it runs before logging or GUI +/// initialization. #[cfg(windows)] pub fn helper_main() -> Option { - todo!("pf.C-PR3") + let mut args = std::env::args_os().skip(1); + if args.next().as_deref() != Some(std::ffi::OsStr::new(FLAG)) { + return None; + } + let result = args.next().ok_or_else(|| "print helper directory missing".to_owned()).and_then(|dir| { + helper(Path::new(&dir), crate::Cancel::cancel, |pdf, job, cancel| { + crate::submit_cancellable(pdf, job, &mut |_, _| {}, cancel).map_err(error) + }) + }); + if let Err(message) = &result { + let _ = emit(&Event::Done(Err(message.clone()))); + } + Some(i32::from(result.is_err())) } diff --git a/crates/print/src/spool_tests.rs b/crates/print/src/spool_tests.rs new file mode 100644 index 000000000..4e8c750ba --- /dev/null +++ b/crates/print/src/spool_tests.rs @@ -0,0 +1,417 @@ +//! The `Spool` entry list and the Windows helper protocol. The protocol trials run a real child: +//! this test binary re-run with only [`stand_in_print_helper`] selected, so pipes, tokens and +//! process cleanup are the production ones, with no printer. + +use std::collections::VecDeque; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use craft_host::ManualJobs; +use craft_ui::testing::trial; + +use crate::spool::isolated::{self, CANCELLED, Request, Submission}; +use crate::spool::{Pending, Spool, SpoolBackend}; +use crate::{DriverSettings, Duplex, Job, Scaling}; + +/// A guard against a hang, never a timing the trials rely on. +const LIMIT: Duration = Duration::from_secs(10); +/// Set on the child: the job's private input folder. +const PRINT_DIR: &str = "CRAFT_TEST_PRINT_DIR"; +/// Set on the child: how it behaves (`waking`, `held`, `crash`, `sending`, or a plain receipt). +const PRINT_MODE: &str = "CRAFT_TEST_PRINT_MODE"; +/// Set on the child: where it marks the stages it reached, apart from the input folder, which +/// the parent removes. +const PRINT_MARKS: &str = "CRAFT_TEST_PRINT_MARKS"; +const PDF: &[u8] = b"synthetic PDF"; + +/// One prepared job of [`Fake`]: its cancel's answer, whether it answers after a cancel, and the +/// channel that lets its run finish. +struct Script { + cancels: bool, + waits_after_cancel: bool, + release: Receiver<()>, +} + +/// A backend whose jobs are named by their title, report each cancel asked of them and finish +/// only when released. +struct Fake { + scripts: Mutex>, + asked: Sender, + finished: Arc>>, +} + +impl Fake { + /// The next prepared job's behaviour; the sender releases its run. + fn script(&self, cancels: bool, waits_after_cancel: bool) -> Sender<()> { + let (release, wait) = channel(); + self.scripts.lock().unwrap().push_back(Script { cancels, waits_after_cancel, release: wait }); + release + } +} + +impl SpoolBackend for Fake { + fn printers(&self) -> Option> { + Some(Vec::new()) + } + + fn prepare(&self, pdf: Vec, job: Job) -> Pending { + assert_eq!(pdf, PDF); + + let Script { cancels, waits_after_cancel, release } = self.scripts.lock().unwrap().pop_front().expect("a script for every job"); + let name = job.title; + let asked = self.asked.clone(); + let asked_name = name.clone(); + let finished = self.finished.clone(); + Pending { + cancel: Box::new(move || { + let _ = asked.send(asked_name.clone()); + cancels + }), + run: Box::new(move || { + let _ = release.recv(); + finished.lock().unwrap().push(name.clone()); + Ok(name) + }), + waits_after_cancel, + } + } +} + +fn titled(title: &str) -> Job { + Job { title: title.into(), ..Job::default() } +} + +/// Shutdown waits for a job already being sent, so the spooler has it before the process exits, +/// and for one whose backend answers after a cancel (a helper process to reap), but not for one +/// still waiting on a driver: that one is cancelled, so it is never sent. Every job is cancelled +/// before any is waited for, so a waiting job can't start sending meanwhile. The Print page's +/// Cancel asks only the latest job. +#[trial] +fn shutdown_waits_for_sending_jobs_and_drops_waiting_ones() { + let jobs = Arc::new(ManualJobs::new()); + let (asked_tx, asked) = channel(); + let finished = Arc::new(Mutex::new(Vec::new())); + let fake = Arc::new(Fake { scripts: Mutex::new(VecDeque::new()), asked: asked_tx, finished: finished.clone() }); + let spool = Spool::with_backend(jobs.clone(), fake.clone()); + assert!(spool.cancel_latest(), "no job: nothing will be sent"); + + // A is being sent (its cancel refuses); B waits on a driver (its cancel succeeds). + let release_a = fake.script(false, false); + let release_b = fake.script(true, false); + let sent_a = spool.submit(PDF.to_vec(), titled("A")); + let _sent_b = spool.submit(PDF.to_vec(), titled("B")); + assert!(spool.cancel_latest(), "the latest job was still waiting: never sent"); + assert_eq!(asked.try_iter().collect::>(), ["B"], "an earlier job isn't the one being submitted"); + // C is cancelled but still answers afterwards. + let release_c = fake.script(true, true); + let sent_c = spool.submit(PDF.to_vec(), titled("C")); + + let runners: Vec<_> = (0..3) + .map(|_| { + let jobs = jobs.clone(); + std::thread::spawn(move || jobs.run_next()) + }) + .collect(); + let (returned, shutdown) = channel(); + let stopping = spool.clone(); + let done = finished.clone(); + std::thread::spawn(move || { + stopping.shutdown(); + let _ = returned.send(done.lock().unwrap().clone()); + }); + let mut cancelled: Vec = (0..3).map(|_| asked.recv_timeout(LIMIT).unwrap()).collect(); + cancelled.sort(); + assert_eq!(cancelled, ["A", "B", "C"], "every job is cancelled before any is waited for"); + assert!(shutdown.try_recv().is_err(), "shutdown waits for the job being sent"); + release_a.send(()).unwrap(); + assert_eq!(sent_a.recv_timeout(LIMIT).unwrap(), Ok("A".to_owned())); + assert!(shutdown.try_recv().is_err(), "shutdown waits for a job that answers after its cancel"); + release_c.send(()).unwrap(); + let done_at_shutdown = shutdown.recv_timeout(LIMIT).unwrap(); + assert!(done_at_shutdown.contains(&"A".to_owned()) && done_at_shutdown.contains(&"C".to_owned()), "{done_at_shutdown:?}"); + assert!(!done_at_shutdown.contains(&"B".to_owned()), "shutdown didn't wait for the waiting job"); + assert_eq!(sent_c.recv_timeout(LIMIT).unwrap(), Ok("C".to_owned())); + assert!(spool.cancel_latest(), "shutdown took every job"); + assert_eq!(asked.try_iter().count(), 0, "no job is left to ask"); + // The waiting job was left behind without blocking shutdown; let it end. + release_b.send(()).unwrap(); + for runner in runners { + assert!(runner.join().unwrap(), "each runner ran a job"); + } + + // A job that has already been sent answers false, so the Print page keeps its receipt. + let release_d = fake.script(false, false); + release_d.send(()).unwrap(); + let sent_d = spool.submit(PDF.to_vec(), titled("D")); + assert!(jobs.run_next()); + assert_eq!(sent_d.recv_timeout(LIMIT).unwrap(), Ok("D".to_owned())); + assert!(!spool.cancel_latest(), "a sent job isn't reported as cancelled"); + assert_eq!(asked.try_iter().collect::>(), ["D"]); +} + +/// Not a behaviour trial: the child the protocol trials launch. With [`PRINT_DIR`] unset (a +/// normal run of the suite) it returns at once. +#[trial] +fn stand_in_print_helper() { + let Some(directory) = std::env::var_os(PRINT_DIR) else { return }; + let directory = PathBuf::from(directory); + let marks = PathBuf::from(std::env::var_os(PRINT_MARKS).unwrap()); + let mode = std::env::var(PRINT_MODE).unwrap_or_default(); + if mode == "waking" { + std::fs::write(marks.join("waking"), b"starting").unwrap(); + loop { + std::thread::park(); + } + } + let refuses = mode == "sending"; + let result = isolated::helper(&directory, move |token| if refuses { false } else { token.cancel() }, |pdf, job, _token| { + assert_eq!(pdf, PDF); + assert_eq!(job.printer.as_deref(), Some("test queue")); + std::fs::write(marks.join("driver"), b"driver entered").unwrap(); + match mode.as_str() { + "held" => { + let provider = Mutex::new(()); + let _held = provider.lock(); + loop { + std::thread::park(); + } + } + "crash" => std::process::exit(7), + "sending" => { + std::fs::write(marks.join("sending"), b"sending").unwrap(); + while !marks.join("release").exists() { + std::thread::sleep(Duration::from_millis(5)); + } + Ok("spooled synthetic job".into()) + } + _ => Ok("spooled synthetic job".into()), + } + }); + std::process::exit(i32::from(result.is_err())); +} + +/// Launches [`stand_in_print_helper`] over `directory` in `mode`, marking its stages in `marks`. +fn helper_command(directory: &Path, marks: &Path, mode: &str) -> std::io::Result { + let mut command = Command::new(std::env::current_exe()?); + command + .args(["--exact", "spool_tests::stand_in_print_helper", "--nocapture", "--"]) + .env(PRINT_DIR, directory) + .env(PRINT_MARKS, marks) + .env(PRINT_MODE, mode); + Ok(command) +} + +/// A job naming a literal printer, which the child checks to verify the transport. +fn job() -> Job { + Job { printer: Some("test queue".into()), ..Job::default() } +} + +/// Waits until the child has marked `path`, failing after [`LIMIT`]. +fn wait_for(path: &Path) { + let deadline = Instant::now() + LIMIT; + while !path.exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + assert!(path.exists(), "the child never reached {path:?}"); +} + +/// Runs `submission` on a thread with the child in `mode`; the receiver gets its input folder. +fn submit_in( + submission: &Submission, + marks: &Path, + mode: &'static str, +) -> (std::thread::JoinHandle>, Receiver) { + let worker = submission.clone(); + let marks = marks.to_path_buf(); + let (folder, folders) = channel(); + let running = std::thread::spawn(move || { + worker.submit_with(PDF, &job(), |directory| { + folder.send(directory.to_path_buf()).unwrap(); + helper_command(directory, &marks, mode) + }) + }); + (running, folders) +} + +/// Cancelling before submission cannot launch a driver process. +#[trial] +fn a_cancelled_start_never_launches_a_helper() { + let submission = Submission::new(); + assert!(submission.cancel()); + let result = submission.submit_with(PDF, &job(), |_| Err(std::io::Error::other("must not launch"))); + assert_eq!(result, Err(CANCELLED.into())); +} + +/// A process without a start grant cannot send anything, so a cancel while it is created or +/// waking stops it at once, with or without its acknowledgement, and removes its inputs. +#[trial] +fn a_cancel_during_startup_never_starts_the_driver() { + let marks = tempfile::tempdir().unwrap(); + // Cancelled while the process is being created. + let submission = Submission::new(); + let worker = submission.clone(); + let held = marks.path().to_path_buf(); + let (started, starting) = channel(); + let (release, wait) = channel::<()>(); + let running = std::thread::spawn(move || { + worker.submit_with(PDF, &job(), |directory| { + started.send(directory.to_path_buf()).unwrap(); + wait.recv().unwrap(); + helper_command(directory, &held, "held") + }) + }); + let directory = starting.recv_timeout(LIMIT).unwrap(); + assert!(submission.cancel()); + release.send(()).unwrap(); + assert_eq!(running.join().unwrap(), Err(CANCELLED.into())); + assert!(!directory.exists(), "startup cancellation reaps the child and removes its inputs"); + + // Cancelled while the child is waking and has not acknowledged anything. + let submission = Submission::new(); + let (running, folders) = submit_in(&submission, marks.path(), "waking"); + let directory = folders.recv_timeout(LIMIT).unwrap(); + wait_for(&marks.path().join("waking")); + assert!(submission.cancel(), "a process without a start grant cannot send anything"); + assert_eq!(running.join().unwrap(), Err(CANCELLED.into())); + assert!(!directory.exists()); + assert!(!marks.path().join("driver").exists(), "neither child reached the driver"); +} + +/// A refused cancellation keeps the sending process alive until its receipt. +#[trial] +fn a_refusal_while_sending_keeps_the_job() { + let marks = tempfile::tempdir().unwrap(); + let submission = Submission::new(); + let (running, folders) = submit_in(&submission, marks.path(), "sending"); + let directory = folders.recv_timeout(LIMIT).unwrap(); + wait_for(&marks.path().join("sending")); + assert!(!submission.cancel(), "a sending job refuses cancellation"); + assert!(!submission.cancel(), "and keeps refusing it"); + assert!(!running.is_finished(), "the child is retained until it finishes sending"); + std::fs::write(marks.path().join("release"), b"continue").unwrap(); + assert_eq!(running.join().unwrap(), Ok("spooled synthetic job".into())); + assert!(!directory.exists()); +} + +/// A driver cancelled while it holds its lock is killed, and the next job starts at once: the +/// reason for one process per job. +#[trial] +fn a_cancelled_driver_does_not_block_the_next_job() { + let marks = tempfile::tempdir().unwrap(); + let submission = Submission::new(); + let (running, folders) = submit_in(&submission, marks.path(), "held"); + let directory = folders.recv_timeout(LIMIT).unwrap(); + wait_for(&marks.path().join("driver")); + assert!(!directory.join("input.pdf").exists(), "the stalled driver retains no plaintext PDF"); + assert!(!directory.join("job.json").exists(), "loaded settings were erased before driver work"); + assert!(submission.cancel(), "a stalled driver still acknowledges cancellation"); + let next_marks = tempfile::tempdir().unwrap(); + let next = Submission::new(); + assert_eq!(next.submit_with(PDF, &job(), |dir| helper_command(dir, next_marks.path(), "ready")), Ok("spooled synthetic job".into())); + assert_eq!(running.join().unwrap(), Err(CANCELLED.into())); + assert!(!directory.exists(), "the reaped helper's PDF and settings were removed"); + assert!(!next.cancel(), "a completed job keeps its receipt"); +} + +/// A crashed helper is an error and its inputs go; oversized messages, requests and files are +/// refused; a vanished parent ends a waiting child; input cleanup tolerates missing files and +/// reports real failures. +#[trial] +fn helper_crashes_are_errors_and_inputs_are_bounded() { + let marks = tempfile::tempdir().unwrap(); + let mut inputs = None; + assert!( + Submission::new() + .submit_with(PDF, &job(), |dir| { + inputs = Some(dir.to_path_buf()); + helper_command(dir, marks.path(), "crash") + }) + .is_err() + ); + assert!(!inputs.unwrap().exists(), "a helper crash removes the PDF and settings"); + + assert!(isolated::bounded(&b"abcd"[..], 3).is_err()); + assert_eq!(isolated::bounded(&b"abc"[..], 3), Ok(b"abc".to_vec())); + let long = vec![b'x'; 70 * 1024]; + assert!(isolated::line(&mut &long[..]).is_err()); + assert_eq!(isolated::line(&mut &b"start\n"[..]), Ok(Some("start".into()))); + let oversized = Job { options: vec![("x".into(), "y".repeat(3 << 20))], ..job() }; + let launched = std::cell::Cell::new(false); + let refused = Submission::new().submit_with(PDF, &oversized, |_| { + launched.set(true); + Err(std::io::Error::other("must not launch")) + }); + assert!(refused.is_err()); + assert!(!launched.get(), "an oversized request is refused before any process starts"); + + // The parent goes away while the driver waits: the child cancels its token and exits. + let marks = tempfile::tempdir().unwrap(); + let folder = tempfile::tempdir().unwrap(); + std::fs::write(folder.path().join("job.json"), serde_json::to_vec(&Request::from_job(&job())).unwrap()).unwrap(); + std::fs::write(folder.path().join("input.pdf"), PDF).unwrap(); + let mut child = + helper_command(folder.path(), marks.path(), "held").unwrap().stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn().unwrap(); + let mut input = child.stdin.take().unwrap(); + input.write_all(b"start\n").and_then(|_| input.flush()).unwrap(); + wait_for(&marks.path().join("driver")); + drop(input); + assert!(child.wait().unwrap().success(), "a vanished parent ends the waiting child"); + assert!(!folder.path().join("input.pdf").exists()); + + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("job.json"), b"settings").unwrap(); + std::fs::write(directory.path().join("input.pdf"), b"private PDF").unwrap(); + assert_eq!(isolated::remove_inputs(directory.path()), Ok(())); + assert_eq!(isolated::remove_inputs(directory.path()), Ok(()), "missing inputs are not an error"); + assert!(!directory.path().join("input.pdf").exists()); + std::fs::create_dir(directory.path().join("job.json")).unwrap(); + std::fs::write(directory.path().join("input.pdf"), b"private PDF").unwrap(); + assert!(isolated::remove_inputs(directory.path()).is_err()); + assert!(!directory.path().join("input.pdf").exists(), "a settings cleanup failure does not retain the PDF"); +} + +/// Job transport preserves every explicit setting, including Unicode, each duplex direction and +/// scaling, and the driver's own settings; damaged driver settings are refused rather than +/// printed with other settings. +#[trial] +fn job_options_survive_the_process_boundary() { + let across = |job: &Job| -> Result { + let bytes = serde_json::to_vec(&Request::from_job(job)).unwrap(); + serde_json::from_slice::(&bytes).unwrap().job() + }; + // A DEVMODEW header of 156 bytes (`dmSize` at 68) and a 4-byte private part (`dmDriverExtra` at 70). + let mut dev_mode = vec![0u8; 160]; + dev_mode[68..70].copy_from_slice(&156u16.to_le_bytes()); + dev_mode[70..72].copy_from_slice(&4u16.to_le_bytes()); + dev_mode[156..].copy_from_slice(&[1, 2, 3, 4]); + let dev_mode = crate::rgb::DevMode::from_bytes(dev_mode).unwrap(); + let expected = Job { + printer: Some("Office λ".into()), + copies: 3, + collate: false, + duplex: Some(Duplex::ShortEdge), + grayscale: true, + grey_pages: true, + scaling: Scaling::ShrinkToFit, + title: "A document".into(), + options: vec![("media".into(), "iso_a4_210x297mm".into())], + driver_settings: Some(DriverSettings::new("Office λ", dev_mode)), + }; + assert_eq!(across(&expected), Ok(expected)); + for duplex in [None, Some(Duplex::Off), Some(Duplex::LongEdge), Some(Duplex::ShortEdge)] { + for scaling in [Scaling::Exact, Scaling::ShrinkToFit] { + let job = Job { duplex, scaling, ..job() }; + assert_eq!(across(&job), Ok(job.clone()), "{duplex:?} {scaling:?}"); + } + } + for hex in ["", "0", "zz", "00"] { + let mut wire = serde_json::to_value(Request::from_job(&job())).unwrap(); + wire["driver_settings"] = serde_json::json!(["Office", hex]); + let request: Request = serde_json::from_value(wire).unwrap(); + assert!(request.job().is_err(), "{hex:?}"); + } +}