diff --git a/crates/print/src/spool.rs b/crates/print/src/spool.rs index 598a9a8ce6..7c671437df 100644 --- a/crates/print/src/spool.rs +++ b/crates/print/src/spool.rs @@ -420,7 +420,7 @@ pub(crate) fn with_job_info(job: &Job, owner: Option<&str>) -> Job { /// The job as the system spooler takes it. fn spooled(job: &Job) -> Job { #[cfg(all(unix, not(target_arch = "wasm32")))] - let job = &with_ppd_media(job, |printer| ppd_papers_in(printer, std::path::Path::new("/etc/cups/ppd"))); + let job = &with_ppd_media(job, queue_papers); #[cfg(target_os = "macos")] { with_job_info(job, std::env::var("USER").ok().as_deref()) @@ -523,22 +523,18 @@ fn printer_papers_internal(printer: &str) -> Vec { papers } -/// The paper sizes supported by `printer` on CUPS: its PPD's (see [`cups_paper_info`]); none on -/// the web. +/// The paper sizes supported by the selected CUPS queue or queue instance. #[cfg(not(windows))] pub fn printer_papers(printer: &str) -> Vec { cups_paper_info(printer).0 } -/// CUPS: the papers of the queue's PPD, each named by the driver's label, and its -/// `*DefaultPageSize` one (the stock a label printer is set up for, an office printer's tray -/// paper); none for a queue without a PPD and on the web. A job on one of them is fed it under -/// the PPD's own keyword ([`with_ppd_media`]). +/// The selected destination's paper labels and default in the print dialog. #[cfg(not(windows))] fn cups_paper_info(printer: &str) -> (Vec, Option) { #[cfg(all(unix, not(target_arch = "wasm32")))] { - cups_paper_info_in(printer, std::path::Path::new("/etc/cups/ppd")) + paper_info(queue_papers(printer)) } #[cfg(not(all(unix, not(target_arch = "wasm32"))))] { @@ -547,15 +543,13 @@ fn cups_paper_info(printer: &str) -> (Vec, Option) { } } -/// [`cups_paper_info`] with the PPD directory supplied, so tests need no system queue. #[cfg(all(unix, not(target_arch = "wasm32")))] -pub(crate) fn cups_paper_info_in(printer: &str, ppd_dir: &std::path::Path) -> (Vec, Option) { - let papers = ppd_papers_in(printer, ppd_dir); +pub(crate) fn paper_info(papers: Vec) -> (Vec, Option) { let default = papers.iter().find(|p| p.default).map(|p| (p.label.clone(), p.size)); (papers.into_iter().map(|p| (p.label, p.size)).collect(), default) } -/// A paper of a PPD: one `*PaperDimension` entry. +/// A named paper for the selected destination. #[cfg(any(test, all(unix, not(target_arch = "wasm32"))))] #[derive(Clone, Debug, PartialEq)] pub(crate) struct PpdPaper { @@ -566,80 +560,34 @@ pub(crate) struct PpdPaper { /// Width and height in points as the driver feeds it: a label's width is across the feed, /// so a 2.25 × 1.25 in label and a 1.25 × 2.25 in one are different stock. pub size: (f64, f64), - /// Whether it is the PPD's `*DefaultPageSize`. + /// Whether it is the effective default for this destination. pub default: bool, } -/// The papers of the queue's PPD in `ppd_dir`; none when the destination is not a plain name or -/// its queue has no PPD. +/// Keep the CUPS instance for user defaults while the shared catalog finds the queue's forms. #[cfg(all(unix, not(target_arch = "wasm32")))] -fn ppd_papers_in(printer: &str, ppd_dir: &std::path::Path) -> Vec { - queue_of(printer).and_then(|queue| read_ppd(ppd_dir, queue)).map(|ppd| parse_ppd_papers(&ppd_text(&ppd))).unwrap_or_default() +fn queue_papers(printer: &str) -> Vec { + if queue_of(printer).is_none() { + return Vec::new(); + } + catalog_papers(craft_print::cups::media_catalog(printer)) } -/// The largest side a PPD paper may have, in points: PDF's own page limit (200 inches). -#[cfg(any(test, all(unix, not(target_arch = "wasm32"))))] -const MAX_PAPER_SIDE: f64 = 14_400.0; -/// How many papers a PPD may list (PPDs are text files from the printer vendor). -#[cfg(any(test, all(unix, not(target_arch = "wasm32"))))] -const MAX_PAPERS: usize = 400; - -/// The paper sizes a PPD offers: its `*PaperDimension key/label: "width height"` entries in -/// file order and as written, each named by its own label, else its `*PageSize` label, else the -/// keyword, the `*DefaultPageSize` one marked as the default. Custom-size placeholders, -/// translations (`*fr.PaperDimension`), repeated keywords, keywords that could not be passed as -/// a CUPS option value, and sizes outside 1 pt to 200 in are left out. Lenient: malformed lines -/// are skipped. -#[cfg(any(test, all(unix, not(target_arch = "wasm32"))))] -pub(crate) fn parse_ppd_papers(ppd: &str) -> Vec { - // A keyword goes to `lp -o media=`: no space, quote, separator or `=`. - let keyword = |s: &str| { - !s.is_empty() && s.len() <= 64 && s.bytes().all(|b| b.is_ascii_graphic() && !matches!(b, b'/' | b':' | b'=' | b'"' | b'\'' | b'\\' | b',')) - }; - // `*Prefix key/label: value` → (key, label, value), the label falling back to the key. - let entry = |line: &str, prefix: &str| -> Option<(String, String, String)> { - let (head, value) = line.trim_end_matches('\r').strip_prefix(prefix)?.split_once(':')?; - let head = head.trim(); - let (key, label) = match head.split_once('/') { - Some((k, l)) if !l.trim().is_empty() => (k.trim(), l.trim()), - Some((k, _)) => (k.trim(), k.trim()), - None => (head, head), - }; - keyword(key).then(|| (key.to_string(), label.to_string(), value.trim().to_string())) - }; - let mut names: std::collections::BTreeMap = Default::default(); - for line in ppd.lines() { - if let Some((key, label, _)) = entry(line, "*PageSize ") - && label != key - { - names.entry(key).or_insert(label); - } - } - let default_key = ppd - .lines() - .find_map(|line| line.trim_end_matches('\r').strip_prefix("*DefaultPageSize:").map(str::trim)) - .filter(|k| keyword(k)) - .map(str::to_string); - let fits = |v: f64| v.is_finite() && (1.0..=MAX_PAPER_SIDE).contains(&v); - let mut out: Vec = Vec::new(); - for line in ppd.lines() { - if out.len() >= MAX_PAPERS { - break; - } - let Some((key, label, value)) = entry(line, "*PaperDimension ") else { continue }; - if key.starts_with("Custom") || out.iter().any(|p| p.key == key) { - continue; - } - let mut sides = value.trim_matches('"').split_whitespace().map(|v| v.parse::().ok()); - let (Some(Some(w)), Some(Some(h))) = (sides.next(), sides.next()) else { continue }; - if !fits(w) || !fits(h) { - continue; - } - let label = if label == key { names.get(&key).cloned().unwrap_or(label) } else { label }; - let default = default_key.as_deref() == Some(key.as_str()); - out.push(PpdPaper { key, label, size: (w, h), default }); - } - out +#[cfg(all(any(unix, test), not(target_arch = "wasm32")))] +pub(crate) fn catalog_papers(catalog: craft_print::cups::MediaCatalog) -> Vec { + // PdfCraft can address pages between one point and 200 inches per side. + let sides = 1.0..=14_400.0; + catalog + .sizes + .into_iter() + .filter_map(|paper| { + if !sides.contains(&paper.width) || !sides.contains(&paper.height) || matches!(paper.key.as_str(), "Custom" | "Custom.WIDTHxHEIGHT") { + return None; + } + let default = catalog.default.as_deref() == Some(paper.key.as_str()); + Some(PpdPaper { key: paper.key, label: paper.label, size: (paper.width, paper.height), default }) + }) + .collect() } /// The paper of `papers` of this size, within half a point a side: the one fed that way round diff --git a/crates/print/src/tests.rs b/crates/print/src/tests.rs index 057986901e..ad53a9effa 100644 --- a/crates/print/src/tests.rs +++ b/crates/print/src/tests.rs @@ -803,6 +803,7 @@ fn a_job_that_names_its_orientation_keeps_it() { /// A label printer's PPD: `*PageSize` labels, `*PaperDimension` sizes, and the lines that /// must not become papers (custom placeholders, repeats, translations, nonsense, malformed). +#[cfg(not(target_arch = "wasm32"))] const LABEL_PPD: &str = "*PPD-Adobe: \"4.3\"\n\ *OpenUI *PageSize/Media Size: PickOne\n\ *DefaultPageSize: w288h432\n\ @@ -831,9 +832,15 @@ const LABEL_PPD: &str = "*PPD-Adobe: \"4.3\"\n\ *PaperDimension Quo\"te: \"300 300\"\n\ *PaperDimension a,b: \"300 300\"\n"; +#[cfg(not(target_arch = "wasm32"))] +fn parse_ppd_papers(ppd: &str) -> Vec { + spool::catalog_papers(craft_print::cups::parse_ppd_media(ppd)) +} + +#[cfg(not(target_arch = "wasm32"))] #[test] fn ppd_papers_come_from_the_ppd() { - let papers = spool::parse_ppd_papers(LABEL_PPD); + let papers = parse_ppd_papers(LABEL_PPD); let listed: Vec<(&str, &str, (f64, f64))> = papers.iter().map(|p| (p.key.as_str(), p.label.as_str(), p.size)).collect(); assert_eq!( listed, @@ -853,21 +860,22 @@ fn ppd_papers_come_from_the_ppd() { assert_eq!(key((613.0, 792.0)), None); assert_eq!(key((f64::NAN, 792.0)), None); // A label fed either way is different stock: the exact way round wins when both exist. - let labels = spool::parse_ppd_papers("*PaperDimension w90h162/1.25x2.25: \"90 162\"\n*PaperDimension w162h90/2.25x1.25: \"162 90\"\n"); + let labels = parse_ppd_papers("*PaperDimension w90h162/1.25x2.25: \"90 162\"\n*PaperDimension w162h90/2.25x1.25: \"162 90\"\n"); let key = |size| spool::ppd_paper_of_size(&labels, size).map(|p| p.key.as_str()); assert_eq!((key((162.0, 90.0)), key((90.0, 162.0))), (Some("w162h90"), Some("w90h162"))); - assert!(spool::parse_ppd_papers("").is_empty()); - assert!(spool::parse_ppd_papers("*PaperDimension").is_empty()); + assert!(parse_ppd_papers("").is_empty()); + assert!(parse_ppd_papers("*PaperDimension").is_empty()); let many: String = (0..500).map(|i| format!("*PaperDimension P{i}: \"100 200\"\n")).collect(); - assert_eq!(spool::parse_ppd_papers(&many).len(), 400, "capped"); + assert_eq!(parse_ppd_papers(&many).len(), 400, "capped"); } /// A CUPS job on one of the PPD's papers, as the Print dialog and `doc_print` name it (by its /// label, or as custom points of its size), is fed it under the PPD's keyword; anything else /// goes as it is. +#[cfg(not(target_arch = "wasm32"))] #[test] fn a_job_on_a_ppd_paper_names_the_ppd_keyword() { - let papers = |printer: &str| if printer == "Label" { spool::parse_ppd_papers(LABEL_PPD) } else { Vec::new() }; + let papers = |printer: &str| if printer == "Label" { parse_ppd_papers(LABEL_PPD) } else { Vec::new() }; let media = |printer: Option<&str>, options: &[(&str, &str)]| { let job = Job { printer: printer.map(Into::into), @@ -891,6 +899,7 @@ fn a_job_on_a_ppd_paper_names_the_ppd_keyword() { } /// A driver that measures its label stock in millimetres, under keywords of its own. +#[cfg(not(target_arch = "wasm32"))] const METRIC_LABEL_PPD: &str = "*PPD-Adobe: \"4.3\"\n\ *PageSize 102x152/4\" x 6\": \"\"\n\ *PageSize 57x32/57 x 32 mm: \"\"\n\ @@ -899,11 +908,12 @@ const METRIC_LABEL_PPD: &str = "*PPD-Adobe: \"4.3\"\n\ *PaperDimension 57x32: \"161.57 90.71\"\n\ *PaperDimension 58x32: \"164.41 90.71\"\n"; +#[cfg(not(target_arch = "wasm32"))] #[test] fn a_job_on_a_standard_size_names_the_ppd_keyword_of_that_size() { let media = |value: &str| { let job = Job { printer: Some("Label".into()), options: vec![("media".into(), value.into())], ..Job::default() }; - let job = spool::with_ppd_media(&job, |_| spool::parse_ppd_papers(METRIC_LABEL_PPD)); + let job = spool::with_ppd_media(&job, |_| parse_ppd_papers(METRIC_LABEL_PPD)); job.options.into_iter().map(|(_, v)| v).collect::>() }; let label = cups_media(LABEL_PAPER).unwrap_or_default(); @@ -1048,23 +1058,19 @@ mod cups_options { std::fs::remove_dir_all(dir).unwrap(); } - /// `printer_papers` and `printer_default_paper` on CUPS: the queue's PPD papers by label and - /// its `*DefaultPageSize`, instances sharing their queue's PPD; nothing for a queue without - /// one or a destination that isn't a plain name. #[test] - fn printer_papers_are_read_from_the_queue_ppd() { - let dir = folder(); - std::fs::write(dir.join("Label.ppd"), super::LABEL_PPD).unwrap(); - for destination in ["Label", "Label/draft"] { - let (papers, default) = spool::cups_paper_info_in(destination, &dir); - let names: Vec<&str> = papers.iter().map(|(name, _)| name.as_str()).collect(); - assert_eq!(names, ["US Letter", "4 x 6 in", "Envelope #10", "Wide", "Key"], "{destination}"); - assert_eq!(default, Some(("4 x 6 in".to_string(), (288.0, 432.0))), "{destination}"); + fn printer_papers_use_the_effective_queue_default_and_driver_labels() { + let mut catalog = craft_print::cups::parse_ppd_media(super::LABEL_PPD); + for (key, expected) in [("w288h432", ("4 x 6 in", (288.0, 432.0))), ("Letter", ("US Letter", (612.0, 792.0)))] { + catalog.default = Some(key.into()); + let (papers, default) = spool::paper_info(spool::catalog_papers(catalog.clone())); + let names: Vec<_> = papers.iter().map(|(name, _)| name.as_str()).collect(); + assert_eq!(names, ["US Letter", "4 x 6 in", "Envelope #10", "Wide", "Key"]); + assert_eq!(default, Some((expected.0.into(), expected.1))); } - for destination in ["Missing", "../Label", "Label/a/b", "Label\\draft", "", ".", "-Label"] { - assert_eq!(spool::cups_paper_info_in(destination, &dir), (Vec::new(), None), "{destination:?}"); + for destination in ["../Label", "Label/a/b", "Label\\draft", "", ".", "-Label"] { + assert_eq!(spool::printer_paper_info(destination), (Vec::new(), None), "{destination:?}"); } - std::fs::remove_dir_all(dir).unwrap(); } #[test]