Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge PR #2647: Print ▸ Properties…: the driver's options in the UI language

aionggb7075c89fb45
diff --cc crates/print/src/spool.rs
index 3d6576861,f0683ab4d..5ce3d9736
--- a/crates/print/src/spool.rs
+++ b/crates/print/src/spool.rs
@@@ -10,9 -10,16 +10,16 @@@ pub use craft_print::
/// empty when it has none or on other platforms. Reads files and runs `lpoptions`, so call it
/// when the user asks, not every frame.
pub fn printer_options(printer: &str) -> Vec<PrinterOption> {
+ printer_options_in(printer, "en")
+ }
+
+ /// [`printer_options`] with the driver's own names in `lang` (a UI language code such as `bg`,
+ /// `pt-br` or `zh-hans`) where its PPD has them (`*bg.Translation`, `*bg.InputSlot Tray2/…`);
+ /// the driver's default names otherwise.
+ pub fn printer_options_in(printer: &str, lang: &str) -> Vec<PrinterOption> {
#[cfg(all(unix, not(target_arch = "wasm32")))]
{
- printer_options_via_within(printer, std::path::Path::new("/etc/cups/ppd"), std::process::Command::new("lpoptions"), LPOPTIONS_LIMIT)
- printer_options_via(printer, std::path::Path::new("/etc/cups/ppd"), std::process::Command::new("lpoptions"), lang)
++ printer_options_via_within(printer, std::path::Path::new("/etc/cups/ppd"), std::process::Command::new("lpoptions"), LPOPTIONS_LIMIT, lang)
}
#[cfg(not(all(unix, not(target_arch = "wasm32"))))]
{
@@@ -20,86 -28,11 +28,87 @@@
}
}
+/// How long `lpoptions` may take: a CUPS that has stopped answering must not hold whoever asked
+/// (#1818). After this the PPD's own defaults stand.
+#[cfg(all(unix, not(target_arch = "wasm32")))]
+const LPOPTIONS_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
+
+/// The most of a command's output that is kept (`lpoptions -l` is a few kilobytes).
+#[cfg(any(test, all(unix, not(target_arch = "wasm32"))))]
+const OUTPUT_CAP: u64 = 4 << 20;
+
+/// Run `command` and collect its standard output, giving it `limit`: a command still running
+/// then is killed and reaped, and the error is `TimedOut`. Standard input and error are not
+/// connected. The exit status is not checked, as `Command::output` leaves it to the caller.
+/// Only CUPS runs a command today; the tests cover every desktop platform.
+#[cfg(any(test, all(unix, not(target_arch = "wasm32"))))]
+pub(crate) fn output_within(command: &mut std::process::Command, limit: std::time::Duration) -> std::io::Result<Vec<u8>> {
+ use std::io::Read as _;
+ use std::process::Stdio;
+ let mut child = command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()?;
+ let stop = |child: &mut std::process::Child| {
+ let _ = child.kill();
+ let _ = child.wait();
+ };
+ let Some(mut stdout) = child.stdout.take() else {
+ stop(&mut child);
+ return Err(std::io::Error::other("the command's output could not be read"));
+ };
+ // Read on a thread of its own, so a full pipe never holds the command while the deadline is
+ // kept here. Past the cap the rest is drained and dropped, so the command still finishes.
+ // The output comes back over a channel rather than through `join`: a process the command
+ // started can keep the pipe open after the command itself has exited or been killed, and
+ // the wait for the output must end at the deadline too. Such a reader is left to finish on
+ // its own when that process closes the pipe.
+ let (tx, rx) = std::sync::mpsc::channel();
+ let reader = std::thread::Builder::new().name("command output".into()).spawn(move || {
+ let mut out = Vec::new();
+ let read = (&mut stdout).take(OUTPUT_CAP).read_to_end(&mut out);
+ let _ = std::io::copy(&mut stdout, &mut std::io::sink());
+ let _ = tx.send(read.map(|_| out));
+ });
+ if let Err(e) = reader {
+ stop(&mut child);
+ return Err(e);
+ }
+ let timed_out = || std::io::Error::new(std::io::ErrorKind::TimedOut, format!("the command did not answer within {limit:?}"));
+ let deadline = std::time::Instant::now() + limit;
+ loop {
+ match child.try_wait() {
+ Ok(Some(_)) => {
+ // A moment's grace, so output written just before an exit at the deadline counts.
+ let left = deadline.saturating_duration_since(std::time::Instant::now()).max(std::time::Duration::from_millis(100));
+ return match rx.recv_timeout(left) {
+ Ok(read) => read,
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(timed_out()),
+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(std::io::Error::other("the command's output was lost")),
+ };
+ }
+ Ok(None) if std::time::Instant::now() >= deadline => {
+ stop(&mut child);
+ return Err(timed_out());
+ }
+ Ok(None) => std::thread::sleep(std::time::Duration::from_millis(10)),
+ Err(e) => {
+ stop(&mut child);
+ return Err(e);
+ }
+ }
+ }
+}
+
/// Read a destination's options with the PPD directory and command supplied, so tests need
/// neither a system queue nor a physical printer. CUPS instances share their queue's PPD but
-/// have their own defaults, queried with the complete `queue/instance` destination.
+/// have their own defaults, queried with the complete `queue/instance` destination. `limit` is
+/// how long the command may take before the PPD's defaults stand on their own.
#[cfg(all(unix, not(target_arch = "wasm32")))]
-pub(crate) fn printer_options_via(printer: &str, ppd_dir: &std::path::Path, mut lpoptions: std::process::Command, lang: &str) -> Vec<PrinterOption> {
+pub(crate) fn printer_options_via_within(
+ printer: &str,
+ ppd_dir: &std::path::Path,
+ mut lpoptions: std::process::Command,
+ limit: std::time::Duration,
++ lang: &str,
+) -> Vec<PrinterOption> {
let (queue, instance) = printer.split_once('/').map_or((printer, None), |(q, i)| (q, Some(i)));
// Retain the conservative name checks, applied to each component. Neither component is
// a path: reject dot components, backslashes and any additional separator before I/O.
@@@ -118,9 -51,11 +127,12 @@@
let mut bytes = Vec::new();
f.take(PPD_CAP).read_to_end(&mut bytes).ok().map(|_| bytes)
});
- let mut options = ppd.map(|b| parse_ppd(&ppd_text(&b))).unwrap_or_default();
+ let mut options = ppd.as_deref().map(|b| parse_ppd(&ppd_text(b))).unwrap_or_default();
+ if let Some(b) = &ppd {
+ localize(&mut options, b, lang);
+ }
- let current = lpoptions.args(["-p", printer, "-l"]).output().map(|o| parse_lpoptions(&String::from_utf8_lossy(&o.stdout))).unwrap_or_default();
+ let current =
+ output_within(lpoptions.args(["-p", printer, "-l"]), limit).map(|out| parse_lpoptions(&String::from_utf8_lossy(&out))).unwrap_or_default();
for (key, value) in current {
if let Some(o) = options.iter_mut().find(|o| o.key == key)
&& o.choices.iter().any(|(c, _)| *c == value)
diff --cc crates/print/src/tests.rs
index 27c8ec2c1,35fdd5008..47eab0162
--- a/crates/print/src/tests.rs
+++ b/crates/print/src/tests.rs
@@@ -582,7 -556,7 +582,7 @@@ mod cups_options
(boundary_queue.as_str(), "Tray2", "Tray2"),
(boundary_instance.as_str(), "Tray2", "Tray2"),
] {
- let options = spool::printer_options_via_within(destination, &dir, command(&dir, &format!("InputSlot/Paper tray: *{current}")), LIMIT);
- let options = spool::printer_options_via(destination, &dir, command(&dir, &format!("InputSlot/Paper tray: *{current}")), "en");
++ let options = spool::printer_options_via_within(destination, &dir, command(&dir, &format!("InputSlot/Paper tray: *{current}")), LIMIT, "en");
assert_eq!(options.len(), 1, "{destination}: the queue's PPD must be read");
assert_eq!(options[0].default, expected, "{destination}: only valid instance choices override the PPD default");
assert_eq!(options[0].choices, [("Auto".into(), "Automatic".into()), ("Tray2".into(), "Tray 2".into())]);
@@@ -623,7 -597,7 +623,7 @@@
long_queue_instance.as_str(),
long_instance.as_str(),
] {
- assert!(spool::printer_options_via_within(destination, &dir, command(&dir, "InputSlot: *Auto"), LIMIT).is_empty(), "{destination:?}");
- assert!(spool::printer_options_via(destination, &dir, command(&dir, "InputSlot: *Auto"), "en").is_empty(), "{destination:?}");
++ assert!(spool::printer_options_via_within(destination, &dir, command(&dir, "InputSlot: *Auto"), LIMIT, "en").is_empty(), "{destination:?}");
assert!(!dir.join("args").exists(), "{destination:?}: rejected before spawning");
}
std::fs::remove_dir_all(dir).unwrap();
@@@ -781,63 -744,32 +781,93 @@@ fn imposed_pages_preserve_large_user_un
}
}
+/// `output_within` (#1818): the bounded wait every platform's `lpoptions` call goes through.
+#[cfg(not(target_arch = "wasm32"))]
+mod bounded_commands {
+ const MODE: &str = "PDFCRAFT_COMMAND_TEST_MODE";
+
+ /// The child process stands in for a command: it answers, or it never does.
+ #[test]
+ fn stand_in_for_a_command() {
+ match std::env::var(MODE).as_deref() {
+ Ok("answer") => println!("hello from the command"),
+ Ok("hang") => std::thread::sleep(std::time::Duration::from_secs(60)),
+ // Holds the output pipe it inherited for a while, as a daemon a command starts can.
+ Ok("linger") => std::thread::sleep(LINGER),
+ // Starts a lingering process on its own output, then exits or hangs itself.
+ Ok(mode @ ("orphan-exit" | "orphan-hang")) => {
+ let _ = command("linger").spawn();
+ println!("started");
+ if mode == "orphan-hang" {
+ std::thread::sleep(std::time::Duration::from_secs(60));
+ }
+ }
+ _ => {}
+ }
+ }
+
+ const LINGER: std::time::Duration = std::time::Duration::from_secs(8);
+
+ fn command(mode: &str) -> std::process::Command {
+ let mut c = std::process::Command::new(std::env::current_exe().unwrap());
+ c.args(["--exact", "tests::bounded_commands::stand_in_for_a_command", "--nocapture", "--"]).env(MODE, mode);
+ c
+ }
+
+ #[test]
+ fn a_command_that_answers_gives_its_output() {
+ let out = crate::spool::output_within(&mut command("answer"), std::time::Duration::from_secs(60)).unwrap();
+ assert!(String::from_utf8_lossy(&out).contains("hello from the command"));
+ }
+
+ #[test]
+ fn a_command_that_never_answers_is_stopped_at_the_deadline() {
+ let started = std::time::Instant::now();
+ let err = crate::spool::output_within(&mut command("hang"), std::time::Duration::from_millis(500)).unwrap_err();
+ assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
+ assert!(started.elapsed() < std::time::Duration::from_secs(20), "stopped soon after the deadline, not when the command gives up");
+ }
+
+ /// A process the command started keeps the output pipe open after the command has exited,
+ /// or after it was killed at the deadline: the wait still ends at the deadline (#2108
+ /// review), not when that process lets go of the pipe.
+ #[test]
+ fn a_process_left_holding_the_output_does_not_extend_the_wait() {
+ for mode in ["orphan-exit", "orphan-hang"] {
+ let started = std::time::Instant::now();
+ let err = crate::spool::output_within(&mut command(mode), std::time::Duration::from_millis(1500)).unwrap_err();
+ assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "{mode}");
+ assert!(started.elapsed() < LINGER / 2, "{mode}: returned after {:?}, when the lingering process let go", started.elapsed());
+ }
+ }
+}
++
+ #[test]
+ fn driver_options_take_the_ppds_own_names_in_the_ui_language() {
+ use crate::spool::{PrinterOption, localize, parse_ppd, ppd_text};
+ // Latin-1 elsewhere (the é), UTF-8 in the localization lines, as drivers ship them.
+ let mut ppd = b"*cupsLanguages: \"bg pt_BR\"\n*OpenGroup: Finishing/Finishing Options\n*OpenUI *KMDuplex/Print Type: PickOne\n*DefaultKMDuplex: Single\n*KMDuplex Single/1-Sided: \"\"\n*KMDuplex Double/2-Sided: \"\"\n*CloseUI: *KMDuplex\n*OpenUI *Staple/Staple: PickOne\n*DefaultStaple: None\n*Staple None/None: \"\"\n*CloseUI: *Staple\n*CloseGroup: Finishing\n*fr.Translation KMDuplex/Type d'impression r".to_vec();
+ ppd.push(0xE9);
+ ppd.extend_from_slice("el: \"\"\n*bg.Translation Finishing/Довършителни операции: \"\"\n*bg.Translation KMDuplex/Тип печат: \"\"\n*bg.KMDuplex Single/Едностранен: \"\"\n*bg.KMDuplex Double/: \"\"\n*pt_BR.Translation KMDuplex/Tipo de impressão: \"\"\n".as_bytes());
+ let parsed = parse_ppd(&ppd_text(&ppd));
+ let label = |o: &[PrinterOption], key: &str| o.iter().find(|o| o.key == key).map(|o| o.label.clone()).unwrap();
+ let mut bg = parsed.clone();
+ localize(&mut bg, &ppd, "bg");
+ let duplex = bg.iter().find(|o| o.key == "KMDuplex").unwrap();
+ assert_eq!((duplex.label.as_str(), duplex.group.as_str()), ("Тип печат", "Довършителни операции"));
+ assert_eq!(
+ duplex.choices,
+ [("Single".to_string(), "Едностранен".to_string()), ("Double".to_string(), "2-Sided".to_string())],
+ "an empty translation keeps the driver's name"
+ );
+ assert_eq!(label(&bg, "Staple"), "Staple", "untranslated options keep theirs");
+ // Region-specific codes, then the language alone; languages the PPD lacks change nothing.
+ let mut pt = parsed.clone();
+ localize(&mut pt, &ppd, "pt-br");
+ assert_eq!(label(&pt, "KMDuplex"), "Tipo de impressão");
+ for lang in ["en", "de", "", "bg-"] {
+ let mut other = parsed.clone();
+ localize(&mut other, &ppd, lang);
+ assert_eq!(other == parsed, lang != "bg-", "{lang:?}");
+ }
+ }
diff --cc crates/ui-egui/src/print_ui.rs
index 21b8fd3d6,e42f1617e..cab6bfc23
--- a/crates/ui-egui/src/print_ui.rs
+++ b/crates/ui-egui/src/print_ui.rs
@@@ -251,10 -215,6 +251,10 @@@ impl PrintDraft
/// the network. Without a source the dialog reads them as it opens, so tests stay deterministic.
pub type PrinterSource = std::sync::Arc<dyn Fn() -> Vec<spool::Printer> + Send + Sync>;
- /// Where a printer's driver options come from: the spooler's (`spool::printer_options`) unless a
- /// test stands in. Called off the GUI thread.
++/// Where a printer's driver options come from: the spooler's (`spool::printer_options_in`, in the
++/// UI language) unless a test stands in. Called off the GUI thread.
+pub type OptionsSource = std::sync::Arc<dyn Fn(&str) -> Vec<spool::PrinterOption> + Send + Sync>;
+
/// The system spooler's printers, as the desktop app's [`PrinterSource`].
pub fn system_printers() -> PrinterSource {
std::sync::Arc::new(spool::printers)
@@@ -457,42 -391,7 +457,46 @@@ impl PdfCraftApp
self.print_tasks.printers = Some(rx);
}
- /// Pick up a printer list or a spooled job that finished (each frame).
+ /// Read `printer`'s driver options off the GUI thread (#1818); `poll_print` picks them up.
+ /// A read already under way for the same printer is left to finish.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn read_options_in_background(&mut self, printer: String) {
+ if self.print_tasks.options.iter().any(|(p, _)| *p == printer) {
+ return;
+ }
- let source: OptionsSource = self.options_source.clone().unwrap_or_else(|| std::sync::Arc::new(|p: &str| spool::printer_options(p)));
++ let source: OptionsSource = self.options_source.clone().unwrap_or_else(|| {
++ // The driver's own names in the UI language, as it is when Properties… is clicked.
++ let lang = crate::i18n::current().code();
++ std::sync::Arc::new(move |p: &str| spool::printer_options_in(p, lang))
++ });
+ let (tx, rx) = std::sync::mpsc::channel();
+ let wake = WakeOnExit(self.ctx.clone());
+ let name = printer.clone();
+ let spawned = std::thread::Builder::new().name("printer options".into()).spawn(move || {
+ let _wake = wake;
+ let tx = tx;
+ // The receiver may be gone (the app quit): nothing to report to then.
+ let _ = tx.send(source(&name));
+ });
+ match spawned {
+ Ok(_) => self.print_tasks.options.push((printer, rx)),
+ // No thread to read them on: the printer offers nothing this time.
+ Err(_) => self.receive_options(printer, Vec::new()),
+ }
+ }
+
+ /// The options read for `printer` arrived, or the read died. A read that a later click
+ /// superseded (another printer's is awaited) is dropped.
+ #[cfg(not(target_arch = "wasm32"))]
+ fn receive_options(&mut self, printer: String, options: Vec<spool::PrinterOption>) {
+ let d = &mut self.print_draft;
+ if d.driver_options_loading.as_deref() == Some(printer.as_str()) {
+ d.driver_options_loading = None;
+ d.driver_options = Some((printer, options));
+ }
+ }
+
+ /// Pick up a printer list, driver options or a spooled job that finished (each frame).
pub(crate) fn poll_print(&mut self) {
#[cfg(target_arch = "wasm32")]
self.poll_web_print();