Skip to content

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

Print: list driverless CUPS destinations, not only permanent queues (#658)

Eduardo Soaresade5dc4dcb6d
diff --git a/crates/print/README.md b/crates/print/README.md
index 2ba1515e4..6af6c3991 100644
--- a/crates/print/README.md
+++ b/crates/print/README.md
@@ -32,10 +32,11 @@ Each source page becomes a Form XObject (its content wrapped in q/Q, plus the pr
annotations); sheets place them with a clip. The result is a fresh, unencrypted,
garbage-collected file (callers check the print permission).
-`spool` talks to CUPS (`lpstat -p -d`, `lp` with copies, collation, duplex and monochrome
-options). The job is piped to `lp` on stdin and never written to a temp file, where another
-local user could read or swap it. Other platforms report that printing to a printer isn't available yet; the
-print-ready PDF can always be saved.
+`spool` talks to CUPS: printers come from `lpstat -p -d` (the queues) and `lpstat -e` (driverless
+destinations no queue exists for; CUPS builds a temporary one when the job arrives), jobs go to
+`lp` with copies, collation, duplex and monochrome options. The job is piped to `lp` on stdin and
+never written to a temp file, where another local user could read or swap it. Other platforms
+report that printing to a printer isn't available yet; the print-ready PDF can always be saved.
Not yet: Windows and web spoolers, print as image, poster labels, PostScript output, colour
conversion for grayscale.
diff --git a/crates/print/src/spool.rs b/crates/print/src/spool.rs
index 86ebd9c5c..91f447139 100644
--- a/crates/print/src/spool.rs
+++ b/crates/print/src/spool.rs
@@ -1,6 +1,7 @@
-//! The system print spooler. On macOS and Linux this is CUPS: printers come from `lpstat`, jobs
-//! are piped to `lp` with the job options (copies, collation, duplex, colour). Other platforms
-//! report that printing isn't available yet; the print-ready PDF can still be saved.
+//! The system print spooler. On macOS and Linux this is CUPS: printers come from `lpstat` — its
+//! queues, and the driverless destinations it can print to without one — and jobs are piped to
+//! `lp` with the job options (copies, collation, duplex, colour). Other platforms report that
+//! printing isn't available yet; the print-ready PDF can still be saved.
use crate::PrintError;
@@ -38,16 +39,26 @@ impl Default for Job {
}
}
+/// The `lpstat -d` line's destination name, when the spooler has a default.
+fn default_destination(out: &str) -> Option<&str> {
+ out.lines().find_map(|l| l.strip_prefix("system default destination:")).map(str::trim)
+}
+
/// Parse `lpstat -p -d` output.
pub fn parse_lpstat(out: &str) -> Vec<Printer> {
- let default = out.lines().find_map(|l| l.strip_prefix("system default destination:")).map(|s| s.trim().to_string());
+ let default = default_destination(out);
out.lines()
.filter_map(|l| l.strip_prefix("printer "))
.filter_map(|l| l.split_whitespace().next())
- .map(|n| Printer { name: n.to_string(), default: default.as_deref() == Some(n) })
+ .map(|n| Printer { name: n.to_string(), default: default == Some(n) })
.collect()
}
+/// Parse `lpstat -e` output: destination names, one per line.
+pub fn parse_lpstat_e(out: &str) -> Vec<String> {
+ out.lines().map(str::trim).filter(|l| !l.is_empty()).map(str::to_string).collect()
+}
+
/// The `lp` arguments for a job. There is no file argument: `lp` reads the job from stdin.
pub fn lp_args(job: &Job) -> Vec<String> {
let mut a = Vec::new();
@@ -259,24 +270,44 @@ pub fn open_printer_preferences(printer: &str) -> Result<(), PrintError> {
}
}
-/// `lpstat -p -d`, forced to print untranslated messages so [`parse_lpstat`] can read them.
+/// `lpstat`, forced to print untranslated messages so [`parse_lpstat`] and [`parse_lpstat_e`] can
+/// read them.
///
/// `LC_ALL`/`LANG=C` is enough on Linux. macOS CUPS ignores them and follows the user's
/// interface language (`AppleLanguages`) unless `SOFTWARE` is set, in which case it uses `LANG`.
-pub fn lpstat_command() -> std::process::Command {
+fn lpstat_with(args: &[&str]) -> std::process::Command {
let mut c = std::process::Command::new("lpstat");
- c.args(["-p", "-d"]).env("LC_ALL", "C").env("LANG", "C").env("SOFTWARE", "PdfCraft");
+ c.args(args).env("LC_ALL", "C").env("LANG", "C").env("SOFTWARE", "PdfCraft");
c
}
-/// The printers the system knows (empty when there are none or no spooler).
+/// `lpstat -p -d`: the spooler's queues and the default destination.
+pub fn lpstat_command() -> std::process::Command {
+ lpstat_with(&["-p", "-d"])
+}
+
+/// `lpstat -e`: every destination CUPS can print to, including driverless network printers no
+/// permanent queue exists for (a queue is built only when a job needs one). GTK's and macOS's
+/// print dialogs list them the same way. CUPS ≥ 1.7 (2013).
+///
+/// Gated like its only caller, `printers`' unix block: off unix this is dead code, and the
+/// Windows clippy gate builds with `-D warnings`.
+#[cfg(all(unix, not(target_arch = "wasm32")))]
+fn lpstat_e_command() -> std::process::Command {
+ lpstat_with(&["-e"])
+}
+
+/// The printers the system knows (empty when there are none or no spooler): its queues, then the
+/// driverless destinations CUPS can print to without one.
pub fn printers() -> Vec<Printer> {
#[cfg(all(unix, not(target_arch = "wasm32")))]
{
- match lpstat_command().output() {
- Ok(o) => parse_lpstat(&String::from_utf8_lossy(&o.stdout)),
- Err(_) => Vec::new(),
- }
+ let Some(queues) = lpstat_command().output().ok().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) else {
+ return Vec::new();
+ };
+ // A spooler without `-e`, or one whose discovery times out, only loses the driverless names.
+ let available = lpstat_e_command().output().ok().map(|o| String::from_utf8_lossy(&o.stdout).into_owned());
+ printers_parsed(&queues, available.as_deref())
}
#[cfg(not(all(unix, not(target_arch = "wasm32"))))]
{
@@ -284,6 +315,24 @@ pub fn printers() -> Vec<Printer> {
}
}
+/// The Print dialog's printers from lpstat's two answers: the spooler's queues (`-p -d`), then
+/// the driverless destinations of `available` (`-e`) that have no queue — CUPS builds a temporary
+/// queue when `lp` sends them a job. Each destination once, queues first; the default still comes
+/// from `-d`, so a driverless default keeps its marker. `None` when the spooler doesn't know `-e`
+/// (CUPS < 1.7, 2013), which loses only the driverless names.
+pub fn printers_parsed(queues: &str, available: Option<&str>) -> Vec<Printer> {
+ let mut printers = parse_lpstat(queues);
+ let default = default_destination(queues);
+ if let Some(names) = available {
+ for name in parse_lpstat_e(names) {
+ if !printers.iter().any(|p| p.name == name) {
+ printers.push(Printer { default: default == Some(name.as_str()), name });
+ }
+ }
+ }
+ printers
+}
+
/// Send a print-ready PDF to the spooler. Returns the spooler's message (the job id).
pub fn submit(pdf: &[u8], job: &Job) -> Result<String, PrintError> {
#[cfg(all(unix, not(target_arch = "wasm32")))]
diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs
index cfdab70cc..677762bea 100644
--- a/crates/print/src/tests.rs
+++ b/crates/print/src/tests.rs
@@ -219,6 +219,30 @@ fn lpstat_output_is_untranslated() {
assert!(envs.iter().any(|(k, v)| k == "SOFTWARE" && v.as_deref().is_some_and(|v| !v.is_empty())), "SOFTWARE missing: {envs:?}");
}
+#[test]
+fn driverless_printers_join_the_list_without_a_queue() {
+ // A driverless network printer (IPP, discovered on the LAN) has no queue, so `lpstat -p`
+ // never lists it — yet GTK's print dialog shows it and `lp` prints to it through a temporary
+ // queue. Only `lpstat -e` names it, and the Print dialog used to show Save as PDF alone.
+ let queues = "printer Office_Laser is idle. enabled since Thu Oct 1 09:00:00 2026\nsystem default destination: Office_Laser\n";
+ assert_eq!(
+ spool::printers_parsed(queues, Some("Basement_Color\nOffice_Laser\n")),
+ [spool::Printer { name: "Office_Laser".into(), default: true }, spool::Printer { name: "Basement_Color".into(), default: false },],
+ "queues first, then the driverless destination; the queue listed twice is not doubled"
+ );
+ // An old spooler without `-e` (CUPS < 1.7) keeps its queues; only the driverless names are lost.
+ assert_eq!(spool::printers_parsed(queues, None), [spool::Printer { name: "Office_Laser".into(), default: true }]);
+ // The default can itself be driverless (`lpoptions -d` names a destination no queue exists
+ // for): it keeps its marker, so the dialog preselects the user's default, not the first queue.
+ assert_eq!(
+ spool::printers_parsed("system default destination: Basement_Color\n", Some("Basement_Color\n")),
+ [spool::Printer { name: "Basement_Color".into(), default: true }],
+ "a default destination without a queue is still the default"
+ );
+ assert!(spool::parse_lpstat_e("\n \n").is_empty(), "no destinations is empty, not [\"\"]");
+ assert_eq!(spool::parse_lpstat_e("A\r\nB \n"), ["A".to_string(), "B".to_string()], "CRLF and stray spaces are trimmed");
+}
+
fn cut_stack(cols: usize, rows: usize) -> Layout {
Layout::Multiple { cols, rows, order: PageOrder::CutStack, border: false, auto_rotate: false }
}
diff --git a/packaging/linux/nfpm.yaml b/packaging/linux/nfpm.yaml
index 5bf20703a..b20bcb672 100644
--- a/packaging/linux/nfpm.yaml
+++ b/packaging/linux/nfpm.yaml
@@ -23,7 +23,9 @@ description: |-
# The binaries link only glibc and libgcc_s directly. Windowing (X11/Wayland, xkbcommon) and the
# GPU (Vulkan, EGL/GL) are loaded at runtime, so they are dependencies/recommendations here
-# rather than ELF NEEDED entries.
+# rather than ELF NEEDED entries. Printing likewise shells out to CUPS's lpstat/lp (cups-client);
+# without it the Print dialog still offers Save as PDF, so it is a recommendation, not a hard
+# dependency.
overrides:
deb:
depends:
@@ -32,6 +34,7 @@ overrides:
- libxkbcommon0
- libvulkan1 | libegl1
recommends:
+ - cups-client
- libwayland-client0
- libx11-6
- libx11-xcb1
@@ -45,6 +48,7 @@ overrides:
- libxkbcommon
- (vulkan-loader or libglvnd-egl)
recommends:
+ - cups-client
- libwayland-client
- libX11
- libXcursor
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index e5044faf2..1a84331b4 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -7832,8 +7832,8 @@ milestone = "M10"
status = "shipped"
commands = ["print.dialog"]
tools = ["printers", "printer_options", "doc_print"]
-evidence = ["crates/print/src/tests.rs::spooler_arguments_and_printer_list", "crates/print/src/tests.rs::printer_options_come_from_the_ppd", "crates/print/src/tests.rs::printer_option_defaults_and_job_arguments", "crates/ui-egui/tests/print.rs::print_dialog_shows_the_printer_driver_options"]
-notes = "CUPS printers via lpstat; Save as PDF; Windows spooler pending. Properties…: on CUPS the driver's own PPD job options (tray, paper type, finishing …, not installable options or what the dialog sets) for this job, sent as lp -o; on Windows the driver's Printing Preferences window (printui), saved as that printer's per-user defaults rather than per job"
+evidence = ["crates/print/src/tests.rs::spooler_arguments_and_printer_list", "crates/print/src/tests.rs::driverless_printers_join_the_list_without_a_queue", "crates/print/src/tests.rs::printer_options_come_from_the_ppd", "crates/print/src/tests.rs::printer_option_defaults_and_job_arguments", "crates/ui-egui/tests/print.rs::print_dialog_shows_the_printer_driver_options"]
+notes = "CUPS queues via lpstat -p -d and driverless destinations without a queue via lpstat -e; Save as PDF; Windows spooler pending. Properties…: on CUPS the driver's own PPD job options (tray, paper type, finishing …, not installable options or what the dialog sets) for this job, sent as lp -o; on Windows the driver's Printing Preferences window (printui), saved as that printer's per-user defaults rather than per job"
[[feature]]
id = "print.copies-collate"