From d23dd117baa6e63e801b1819b1fc03cf2ead0b21 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 05:12:30 -0800 Subject: [PATCH 1/5] Print: the job asks CUPS for the paper size chosen On macOS and Linux the print job carried no media option, so the queue printed on its default paper whatever Size the Print dialog showed. The dialog now sends the driver's keyword for the chosen Size, and file.print takes it as `paper`; the job passes it to CUPS as `media`. A `paper` that is not a single keyword is an error, and so is `paper` with file output, with directPdf or on Windows, where the spooler does not apply it. While the chosen printer's sizes are still loading, Print is refused and the dialog stays open. A queue with no PPD on this machine (a driverless or remote printer) listed no paper sizes. Its sizes now come from `lpoptions -p NAME -l`, and when its server has no PPD either, from the queue's IPP media-supported attribute on the scheduler CUPS uses. CUPS's B4 and B5 keywords are the JIS sizes, and ISOB4 and ISOB5 the ISO ones. Builds on the printer paper lookup in apps/vectorcraft/src/printing.rs (#10511). --- apps/vectorcraft/src/printing.rs | 106 ++++++++++++- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/print.rs | 34 +++- crates/ui-egui/src/dialogs/tests_print.rs | 184 ++++++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/print.rs | 128 ++++++++++++++- docs/mcp.md | 7 +- 7 files changed, 440 insertions(+), 23 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index e7f5db9a69..eca59e3ab6 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -22,6 +22,9 @@ impl PrintService for SystemPrint { fn shared_print(&self) -> Option { Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e)))) } + fn applies_paper(&self) -> bool { + !cfg!(windows) + } fn turns_landscape(&self) -> bool { // macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright // paper. craft-print turns each sheet to its own orientation on Windows. @@ -113,14 +116,74 @@ mod system { const PPD_CAP: u64 = 16 << 20; let mut bytes = Vec::new(); let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); - if read.is_err() { - return Vec::new(); + let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; + if !papers.is_empty() { + return papers; } - vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) + // A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes. + let mut command = Command::new("lpoptions"); + command.args(["-p", printer, "-l"]); + let papers = paper_output(&mut command) + .map(|out| vectorcraft_ui_egui::print::lpoptions_papers(&String::from_utf8_lossy(&out))) + .unwrap_or_default(); + if !papers.is_empty() { + return papers; + } + // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. + let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(cups_server().as_deref(), printer) else { return papers }; + use std::io::Write as _; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let test_path = + std::env::temp_dir().join(format!("vectorcraft-printer-papers-{}-{}.test", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let Ok(mut test) = std::fs::File::options().write(true).create_new(true).open(&test_path) else { return papers }; + let written = test.write_all( + b"{\n\ + VERSION 1.1\n\ + OPERATION Get-Printer-Attributes\n\ + GROUP operation-attributes-tag\n\ + ATTR charset attributes-charset utf-8\n\ + ATTR language attributes-natural-language en\n\ + ATTR uri printer-uri $uri\n\ + ATTR keyword requested-attributes media-supported\n\ + STATUS successful-ok\n\ + }\n", + ); + drop(test); + if written.is_err() { + let _ = std::fs::remove_file(&test_path); + return papers; + } + let mut command = Command::new("ipptool"); + command.args(["-T", "10", "-tv", &uri]).arg(&test_path); + let output = paper_output(&mut command); + let _ = std::fs::remove_file(&test_path); + output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() } } + /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or + /// `/etc/cups/client.conf`; `None` for the local default. + #[cfg(not(windows))] + fn cups_server() -> Option { + if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) { + return Some(server.trim().to_string()); + } + let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf")); + home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| { + use std::io::Read as _; + let mut text = String::new(); + std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?; + text.lines().rev().find_map(|line| { + let line = line.trim(); + if line.starts_with('#') { + return None; + } + let (key, value) = line.split_once(char::is_whitespace)?; + (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) + }) + }) + } /// Drain output while polling the child, and stop discovery after ten seconds. - #[cfg(windows)] fn paper_output(command: &mut Command) -> Option> { use std::io::Read as _; use std::process::Stdio; @@ -163,10 +226,14 @@ mod system { if job.direct_pdf { return super::direct_pdf::print(job); } - // Copies, layout, marks and colour management are already in the PDF. Preserve its - // physical sheet size and the queue's duplex default without printing copies twice. - let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; - craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string()) + craft::print::submit(job.pdf, &settings(job)).map_err(|e| e.to_string()) + } + /// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve + /// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper + /// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for. + pub(crate) fn settings(job: &PrintJob) -> craft::print::Job { + let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect(); + craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() } } #[cfg(windows)] pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command { @@ -310,3 +377,26 @@ mod turn_tests { ); } } + +#[cfg(test)] +mod job_settings_tests { + use super::system::settings; + use vectorcraft_ui_egui::print::PrintJob; + + fn job(paper: Option<&str>) -> PrintJob<'_> { + PrintJob { printer: Some("Card"), title: "Badge", pdf: b"%PDF", paper, direct_pdf: false } + } + + #[test] + fn the_chosen_paper_goes_to_cups_as_media() { + let args = craft::print::lp_args(&settings(&job(Some("CR80")))); + assert!(args.windows(2).any(|w| w == ["-o", "media=CR80"]), "{args:?}"); + assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}"); + } + + #[test] + fn without_a_paper_the_queue_keeps_its_own() { + let args = craft::print::lp_args(&settings(&job(None))); + assert!(!args.iter().any(|a| a.starts_with("media=")), "{args:?}"); + } +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 8dfdfd28e3..a02bf08641 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1991,7 +1991,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", ), ( "print.printers", diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6546b2ff5b..b2b51e69cc 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -209,6 +209,17 @@ fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a P papers.iter().find(|p| p.key == key) } +/// The driver's keyword for the paper the Size row names, for the job to ask the queue for: the printer's own paper +/// (`printer:CR80`), or the driver's paper of the size of one of the dialog's own papers (`letter` on a driver that lists +/// `Letter`). `None` when the driver lists no such paper, or names it with characters a keyword can't hold. +fn driver_paper_key<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a str> { + let paper = printer_paper(fields, papers).or_else(|| { + let own = Media::from_name(fields.text("media")?).filter(|m| *m != Media::Custom)?; + papers.iter().find(|p| own_media_of(p) == Some(own)) + })?; + crate::print::is_paper_keyword(&paper.key).then_some(paper.key.as_str()) +} + /// Whether two papers have the same Width and Height, to within half a point. fn same_size(a: &Paper, b: &Paper) -> bool { (a.width - b.width).abs() <= 0.5 && (a.height - b.height).abs() <= 0.5 @@ -490,15 +501,16 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, // The paper chosen from the previous list, read before the list is replaced. let chosen = on(dialogs, |p| printer_paper(p.fields(), &open.papers.1).cloned()).flatten(); if printer_changed || open.papers_pending { + let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); // The held answer still names a paper from the previous list. if let Some(answer) = &mut d.ok && let Some(paper) = printer_paper(&answer.fields, &open.papers.1) + && (pending || !printer_paper(&answer.fields, &papers).is_some_and(|new| same_size(paper, new))) { answer.fields.set("width", paper.width); answer.fields.set("height", paper.height); answer.fields.set("media", Media::Custom.id()); } - let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); // While the new printer's lookup runs, the Size list keeps the sizes before it, so the paper chosen keeps its // name and size until the driver answers. papers_changed = !pending; @@ -638,7 +650,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, } if let Some(answer) = d.ok { let result = accept(app, open, &answer, &d.name); - on(dialogs, |p| p.answer_ok(result.map_err(Into::into))); + on(dialogs, |p| p.answer_ok(result.map_err(|e| crate::i18n::message(crate::i18n::current(), &e).into()))); } true } @@ -703,17 +715,23 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st if open.mode == PrintMode::PresetEditor { return save_preset(app, open, name, settings); } + let (printer, to_file) = match &answer.settings.destination { + Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false), + _ => ("", true), + }; + let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false); + let applies_paper = !to_file && !direct_pdf && app.services.print.as_ref().is_some_and(|s| s.applies_paper()); + if matches!(answer.finish, PrintFinish::Print) && applies_paper && (open.papers_pending || open.papers.0 != printer) { + return Err("The printer's paper sizes are still loading; try Print again in a moment.".into()); + } // Laid out first, so a bad range or overlap is refused before anything is kept. app.session.execute("print.preview", &json!({ "settings": settings })).map_err(|e| e.to_string())?; app.run("print.setup", json!({ "settings": settings }))?; match answer.finish { PrintFinish::Print => { - let (printer, to_file) = match &answer.settings.destination { - Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false), - _ => ("", true), - }; - let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false); - crate::print::run(app, &json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf })).map(|_| ()) + let paper = if applies_paper { driver_paper_key(&answer.fields, &open.papers.1) } else { None }; + let job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf, "paper": paper }); + crate::print::run(app, &job).map(|_| ()) } // Done only keeps the settings. _ => Ok(()), diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index d2ebf74122..fb122e1c67 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -650,6 +650,190 @@ fn windows_paper_sizes_are_read_in_hundredths_of_an_inch() { assert_eq!((got[3].0, got[3].1), ("256", "256"), "no name: the number"); } +#[test] +fn a_queue_without_a_ppd_lists_the_paper_sizes_lpoptions_reports() { + let out = "ColorModel/Color Mode: Gray *RGB\n\ + PageSize/Media Size: *Letter A4 Legal na_index-4x6_4x6in iso_a5_148x210mm B5 ISOB4 Custom.WIDTHxHEIGHT Unknown Letter\r\n\ + media/Media: om_cr80_54x85.6mm tiny_1x1mm\n\ + InputSlot/Source: *Auto Tray1\n"; + let papers = crate::print::lpoptions_papers(out); + let got: Vec<(&str, i64, i64)> = papers.iter().map(|p| (p.key.as_str(), p.width.round() as i64, p.height.round() as i64)).collect(); + // The custom size, the keyword of unknown size, the repeated Letter and a size below 72 pt are left out. + assert_eq!( + got, + [ + ("Letter", 612, 792), + ("A4", 595, 842), + ("Legal", 612, 1008), + ("na_index-4x6_4x6in", 288, 432), + ("iso_a5_148x210mm", 420, 595), + // CUPS names the JIS B sizes B4 and B5, and the ISO ones ISOB4 and ISOB5. + ("B5", 516, 729), + ("ISOB4", 709, 1001), + ("om_cr80_54x85.6mm", 153, 243) + ] + ); + assert!(crate::print::lpoptions_papers("PageSize: \nbroken\nInputSlot: *A4\n").is_empty()); +} + +#[test] +fn a_queue_without_any_ppd_lists_the_media_its_ipp_attributes_report() { + let out = "\"get-printer-attributes.test\":\n\ + \x20 media-default (keyword) = na_letter_8.5x11in\n\ + \x20 media-supported (1setOf keyword) = na_letter_8.5x11in,iso_a4_210x297mm,custom_min_1x1in,oe_photo-l_3.5x5in,na_letter_8.5x11in\r\n\ + \x20 media-ready (1setOf keyword) = iso_a5_148x210mm\n"; + let papers = crate::print::ipp_papers(out); + let got: Vec<(&str, i64, i64)> = papers.iter().map(|p| (p.key.as_str(), p.width.round() as i64, p.height.round() as i64)).collect(); + // Only media-supported counts; the custom range and the repeated Letter are left out. + assert_eq!(got, [("na_letter_8.5x11in", 612, 792), ("iso_a4_210x297mm", 595, 842), ("oe_photo-l_3.5x5in", 252, 360)]); + assert!(crate::print::ipp_papers("media-supported (1setOf keyword) = \n").is_empty()); +} + +#[test] +fn the_ipp_lookup_asks_the_scheduler_cups_uses_for_the_queue() { + use crate::print::ipp_queue_uri; + assert_eq!(ipp_queue_uri(None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor")); + assert_eq!(ipp_queue_uri(Some(" "), "Lab").as_deref(), Some("ipp://localhost/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), "Lab"), None, "a domain socket has no URI"); + assert_eq!(ipp_queue_uri(None, ""), None); +} + +/// What the paper-keyword service was asked to print on: each job's paper. +type SentPapers = Rc>>>; + +/// One printer, Card, whose driver lists US Letter and a CR80 card, and which keeps each job's paper keyword. +struct KeywordPrint(SentPapers, bool); + +impl PrintService for KeywordPrint { + fn applies_paper(&self) -> bool { + self.1 + } + + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true), Printer::new("Slow")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + self.0.borrow_mut().push(job.paper.map(str::to_string)); + Ok("Sent".into()) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + if printer == "Slow" { + return Papers::Pending; + } + let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height }; + Papers::Ready(vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)]) + } +} + +#[test] +fn the_job_asks_the_queue_for_the_driver_paper_chosen() { + let sent = SentPapers::default(); + let services = Services { print: Some(Box::new(KeywordPrint(sent.clone(), true))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + for (media, keyword) in [("printer:CR80", Some("CR80")), ("letter", Some("Letter")), ("custom", None)] { + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!(media)); + pump(&mut app); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), keyword, "{media}"); + } + assert_eq!(sent.borrow().len(), 3); + // Printing to Slow is refused while its paper sizes are still loading. + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("letter")); + set(&mut app, "printer", json!("Slow")); + pump(&mut app); + confirm(&mut app); + assert!(is_open(&app)); + assert_eq!(sent.borrow().len(), 3); + call(&mut app, "ui.dialog.cancel", json!({})); + // Without the dialog, the keyword is given as `paper`, and anything else is refused before printing. + app.run("file.print", json!({"printer": "Card", "paper": "iso_a4_210x297mm"})).unwrap(); + assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), Some("iso_a4_210x297mm")); + for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4)] { + assert!(app.run("file.print", json!({"printer": "Card", "paper": bad})).is_err(), "{bad}"); + } + assert!(app.run("file.print", json!({"toFile": true, "paper": "Letter"})).is_err()); + assert_eq!(sent.borrow().len(), 4, "no refused job was sent"); +} + +#[test] +fn a_job_without_a_paper_keyword_prints_while_the_paper_lookup_is_pending() { + let sent = SentPapers::default(); + let services = Services { print: Some(Box::new(KeywordPrint(sent.clone(), false))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Slow")); + pump(&mut app); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(*sent.borrow(), [None]); +} + +struct PendingKeywordPrint(Rc>, SentPapers); + +impl PrintService for PendingKeywordPrint { + fn printers(&mut self) -> Vec { + PendingTwin(self.0.clone()).printers() + } + + fn print(&mut self, job: &PrintJob) -> Result { + KeywordPrint(self.1.clone(), true).print(job) + } + + fn applies_paper(&self) -> bool { + true + } + + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + PendingTwin(self.0.clone()).papers(printer, fresh) + } +} + +#[test] +fn a_held_print_keeps_the_paper_keyword_when_the_lookup_finishes() { + let ready = Rc::new(Cell::new(false)); + let sent = SentPapers::default(); + let services = Services { print: Some(Box::new(PendingKeywordPrint(ready.clone(), sent.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + set(&mut app, "printer", json!("Twin")); + pump(&mut app); + let ctx = ctx(&app); + let (id, _) = top(&app).expect("the print dialog is open"); + let _ = app.dialogs().expect("a window host").with(|host| host.confirm_by_id(&ctx, id)); + ready.set(true); + pump(&mut app); + pump(&mut app); + assert!(!is_open(&app)); + assert_eq!(*sent.borrow(), [Some("CR80".to_string())]); +} + +#[test] +fn an_explicit_paper_is_refused_when_the_print_path_cannot_apply_it() { + let (mut app, jobs) = app(); + assert!(app.run("file.print", json!({"paper": "Letter"})).is_err()); + assert!(jobs.borrow().is_empty()); + + let sent = SentPapers::default(); + app.services.print = Some(Box::new(KeywordPrint(sent.clone(), true))); + assert!(app.run("file.print", json!({"paper": "Letter", "directPdf": true})).is_err()); + assert!(sent.borrow().is_empty()); +} + /// A print queue that puts each page on the paper as it is, as `lp` does. struct UprightQueue(Jobs); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 3e4a834cb8..98f4bc3b3e 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1992,7 +1992,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.print", "Print…", "Cmd+P", - "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", + "{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way", ), ( "print.printers", diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 0451cb5b5c..919b834d18 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -13,6 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::script::printing::{PreparedPrint, Printers}; +use vectorcraft_pdf::Media; use crate::{VectorcraftApp, io}; @@ -25,6 +26,9 @@ pub struct PrintJob<'a> { /// The job's name in the print queue. pub title: &'a str, pub pdf: &'a [u8], + /// The printer driver's keyword for the paper the job prints on (`Letter`, `CR80`, `iso_a4_210x297mm`), sent to + /// CUPS as the job's `media`; `None` leaves the paper to the queue. + pub paper: Option<&'a str>, /// Send the PDF to the printer's own PDF interpreter over its RAW TCP port instead of /// spooling it through the platform driver (Windows). pub direct_pdf: bool, @@ -39,6 +43,10 @@ pub trait PrintService { fn printers(&mut self) -> Vec; /// Send `job` to its printer → what happened, for the status bar. fn print(&mut self, job: &PrintJob) -> Result; + /// Whether the service applies the job's paper keyword when printing through the driver. + fn applies_paper(&self) -> bool { + false + } /// Desktop services can submit on the existing background worker; browser services stay /// on the UI thread to invoke their print dialog. fn shared_print(&self) -> Option { @@ -156,6 +164,99 @@ pub fn windows_papers(out: &str) -> Vec { papers } +/// The paper sizes of a queue that has no local PPD, from `lpoptions -p NAME -l` (`PageSize/Media Size: *Letter A4 +/// na_legal_8.5x14in`), which asks the queue's server: each choice of its `PageSize` or `media` line, sized by a PWG +/// self-describing name (`iso_a4_210x297mm`, `na_letter_8.5x11in`) or by one of the dialog's own paper names. Custom +/// sizes (`Custom.WxH`), keywords of unknown size and the limits of [`ppd_papers`] are left out. +pub fn lpoptions_papers(out: &str) -> Vec { + let mut papers: Vec = Vec::new(); + for line in out.lines() { + let Some((head, choices)) = line.trim_end_matches('\r').split_once(':') else { continue }; + let key = head.split('/').next().unwrap_or_default().trim(); + if !key.eq_ignore_ascii_case("PageSize") && !key.eq_ignore_ascii_case("media") { + continue; + } + for choice in choices.split_whitespace().map(|c| c.trim_start_matches('*')) { + if !is_paper_keyword(choice) || choice.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("custom.")) { + continue; + } + let size = pwg_size(choice).or_else(|| cups_b_size(choice)).or_else(|| Media::from_name(choice).and_then(Media::size)); + if let Some((width, height)) = size { + push_paper(&mut papers, Paper { key: choice.into(), label: choice.into(), width, height }); + } + } + } + papers +} + +/// The IPP URI of the queue `printer` on the CUPS scheduler `server` (`CUPS_SERVER` or a `ServerName`: `host`, +/// `host:port`, `host:port/version=1.1`; `None` or empty for this machine's). `None` for a domain-socket server (a path), +/// which `ipptool` can't reach by URI. The queue name is percent-encoded. +pub fn ipp_queue_uri(server: Option<&str>, printer: &str) -> Option { + let server = server.map(str::trim).filter(|s| !s.is_empty()).unwrap_or("localhost"); + if server.starts_with('/') || printer.is_empty() { + return None; + } + let host = server.split('/').next().unwrap_or_default(); + if host.is_empty() || host.contains(['@', '?', '#', ' ']) { + return None; + } + let mut name = String::new(); + for b in printer.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + name.push(char::from(b)); + } else { + name.push_str(&format!("%{b:02X}")); + } + } + Some(format!("ipp://{host}/printers/{name}")) +} + +/// The size in points of a CUPS PPD keyword for a B size: `B4` and `B5` are the JIS sizes, `ISOB4` and `ISOB5` the ISO +/// ones. +fn cups_b_size(keyword: &str) -> Option<(f64, f64)> { + let mm = match keyword.to_ascii_uppercase().as_str() { + "B4" => (257.0, 364.0), + "B5" => (182.0, 257.0), + "ISOB4" => (250.0, 353.0), + "ISOB5" => (176.0, 250.0), + _ => return None, + }; + Some((mm.0 * 72.0 / 25.4, mm.1 * 72.0 / 25.4)) +} + +/// The paper sizes of a queue that serves no PPD at all, from the `media-supported` line of `ipptool -tv URI +/// get-printer-attributes.test` (`media-supported (1setOf keyword) = na_letter_8.5x11in,iso_a4_210x297mm`): each PWG +/// self-describing name, sized by its name. Custom ranges (`custom_min_…`, `custom_max_…`) and the limits of +/// [`ppd_papers`] are left out. +pub fn ipp_papers(out: &str) -> Vec { + let mut papers: Vec = Vec::new(); + for line in out.lines() { + let Some((head, values)) = line.trim_end_matches('\r').split_once('=') else { continue }; + if head.split_whitespace().next() != Some("media-supported") { + continue; + } + for name in values.split(',').map(str::trim) { + if !is_paper_keyword(name) || name.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("custom_")) { + continue; + } + if let Some((width, height)) = pwg_size(name) { + push_paper(&mut papers, Paper { key: name.into(), label: name.into(), width, height }); + } + } + } + papers +} + +/// The size in points a PWG 5101.1 self-describing media name ends with (`_8.5x11in`, `_210x297mm`). +fn pwg_size(name: &str) -> Option<(f64, f64)> { + let dims = name.rsplit('_').next()?; + let (dims, scale) = if let Some(d) = dims.strip_suffix("mm") { (d, 72.0 / 25.4) } else { (dims.strip_suffix("in")?, 72.0) }; + let (w, h) = dims.split_once('x')?; + let (w, h) = (w.parse::().ok()?, h.parse::().ok()?); + (w.is_finite() && h.is_finite()).then_some((w * scale, h * scale)) +} + /// `print.printers`: the system's printers, and what the print service offers. pub fn printers(app: &mut VectorcraftApp) -> Value { let (printers, setup) = app.services.print.as_mut().map(|s| (s.printers(), s.has_setup())).unwrap_or_default(); @@ -219,7 +320,7 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec) -> Result, jobs: &[PreparedPrint]) -> Result, String> { let mut notes = Vec::new(); for (sent, job) in jobs.iter().enumerate() { - match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, direct_pdf: false }) { + match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, paper: None, direct_pdf: false }) { Ok(note) => notes.push(note), Err(e) if sent == 0 => return Err(e), Err(e) => return Err(format!("{e} ({sent} of {} print jobs were sent)", jobs.len())), @@ -228,6 +329,21 @@ fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result, jo Ok(notes) } +/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent or null: none). Anything but printable +/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, is an error. +fn paper_param(p: &Value) -> Result, String> { + match p.get("paper") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(k)) if is_paper_keyword(k) => Ok(Some(k.clone())), + Some(v) => Err(format!("paper must be a printer driver's paper keyword, such as `Letter` or `CR80`, not {v}")), + } +} + +/// A driver's paper keyword: 1 to 64 printable ASCII characters other than space, `,`, `/`, `:`, `=`, `"`, `'` and `\`. +pub fn is_paper_keyword(k: &str) -> bool { + !k.is_empty() && k.len() <= 64 && k.bytes().all(|b| b.is_ascii_graphic() && !matches!(b, b',' | b'/' | b':' | b'=' | b'"' | b'\'' | b'\\')) +} + /// `file.print` with settings: print the active document with `settings` (over the document's, or /// over those of the print preset `preset` names) on `printer` (default: the system's default), or /// save the job as a PDF at `path` (else a picked file, the web downloads it) with `toFile`, a @@ -238,6 +354,11 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); let postscript = s("format").as_deref() == Some("postscript") || s("path").is_some_and(|path| fileio::extension(&path) == "ps"); let to_file = p.get("toFile").and_then(Value::as_bool).unwrap_or(false) || s("path").is_some() || postscript; + let paper = paper_param(p)?; + let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false); + if paper.is_some() && (to_file || direct_pdf || !app.services.print.as_ref().is_some_and(|s| s.applies_paper())) { + return Err("The print service cannot apply a paper keyword for this job.".into()); + } let mut q = json!({}); for k in ["preset", "settings", "format", "level", "flattenerPreset"] { if let Some(v) = p.get(k).filter(|v| !v.is_null()) { @@ -270,7 +391,6 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let pdf = data.as_ref().and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or("the print job has no data")?; let title = app.session.active().map(|d| d.title()).unwrap_or_default(); let printer = s("printer").filter(|n| !n.is_empty()); - let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false); let service = app.services.print.as_mut().ok_or("no print service")?; if let Some(submit) = service.shared_print() { let pending_printer = printer.clone(); @@ -280,7 +400,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { format!("Printing {title}"), None, move |_| { - submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf }) + submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf }) .map(|note| json!({ "note": note, "printer": printer })) }, move |app, result| { @@ -302,7 +422,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { } return Ok(v); } - let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })?; + let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf })?; app.status(done); v["printer"] = json!(printer); v["printed"] = json!(true); diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..669e8dff94 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13223,7 +13223,12 @@ sheet, tile, ink and copy); headless it answers `dataBase64`. With `maxPages`, t prints at most that many pages, copies counted; with more, `file.print` composes and writes nothing and answers `{pages, format}`. In the app, `file.print` with no params opens the Print dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's -default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. +default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. `paper` names the printer +driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its +`media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is +not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or +remote queue) lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +of its IPP `media-supported` attribute. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} From f5b9e1a04b6c4530b07da640ab7c7fcc74f3d933 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 07:39:49 -0800 Subject: [PATCH 2/5] Print: a client.conf comment no longer spoils the CUPS server name cups_server() took everything after ServerName, so a line such as "ServerName print.example.com # office" gave a value that ipp_queue_uri rejects, and IPP paper discovery was skipped. The value is now read as CUPS reads the file: the first unescaped # starts a comment, and \# stands for a literal #. On macOS, which does not read ServerName, only CUPS_SERVER is used. --- apps/vectorcraft/src/printing.rs | 48 ++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index eca59e3ab6..d23195588d 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -162,25 +162,37 @@ mod system { } } /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or - /// `/etc/cups/client.conf`; `None` for the local default. + /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` + /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. #[cfg(not(windows))] fn cups_server() -> Option { if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) { return Some(server.trim().to_string()); } + if cfg!(target_os = "macos") { + return None; + } let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf")); home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| { use std::io::Read as _; let mut text = String::new(); std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?; - text.lines().rev().find_map(|line| { - let line = line.trim(); - if line.starts_with('#') { - return None; - } - let (key, value) = line.split_once(char::is_whitespace)?; - (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) - }) + client_conf_server_name(&text) + }) + } + /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a + /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is + /// dropped and the rest of the line is kept as written. + #[cfg(not(windows))] + pub(super) fn client_conf_server_name(text: &str) -> Option { + text.lines().rev().find_map(|line| { + let kept = match line.find('#') { + Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]), + Some(at) => line[..at].to_string(), + None => line.to_string(), + }; + let (key, value) = kept.trim().split_once(char::is_whitespace)?; + (key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string()) }) } /// Drain output while polling the child, and stop discovery after ten seconds. @@ -378,6 +390,24 @@ mod turn_tests { } } +#[cfg(all(test, not(windows)))] +mod client_conf_tests { + use super::system::client_conf_server_name; + + #[test] + fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { + assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName print.example.com # office\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName print.example.com#office\n").as_deref(), Some("print.example.com")); + assert_eq!(client_conf_server_name("ServerName /run/cups\\#1.sock\n").as_deref(), Some("/run/cups#1.sock")); + // After an escaped first `#`, a later `#` stays as written. + assert_eq!(client_conf_server_name("ServerName a\\#b#c\n").as_deref(), Some("a#b#c")); + // A later line that is only a comment, or a directive whose value is all comment, leaves the earlier one. + assert_eq!(client_conf_server_name("ServerName a.example\n# ServerName b.example\nServerName # none\n").as_deref(), Some("a.example")); + assert_eq!(client_conf_server_name("ServerName a.example\nServerName b.example\n").as_deref(), Some("b.example")); + } +} + #[cfg(test)] mod job_settings_tests { use super::system::settings; From f382526eb9a86a38c69c48d6a80ad92757048612 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 10:32:46 -0800 Subject: [PATCH 3/5] Print: the IPP paper lookup uses IPP_PORT for a server named without a port ipp_queue_uri built ipp://host/printers/name from CUPS_SERVER or the client.conf ServerName, so a server named without a port was always asked on 631, while CUPS clients use IPP_PORT for it. The app now reads IPP_PORT and passes it in; a port in the server name keeps precedence, and a bracketed IPv6 host counts as having a port only after its ]. With no server named, the lookup uses localhost on IPP_PORT only when none of the CUPS domain sockets exists, since CUPS otherwise talks to its socket. docs/mcp.md describes the lookup's server and port. --- apps/vectorcraft/src/printing.rs | 8 +++++- crates/ui-egui/src/dialogs/tests_print.rs | 33 +++++++++++++++++++---- crates/ui-egui/src/print.rs | 27 ++++++++++++++++--- docs/mcp.md | 4 ++- 4 files changed, 61 insertions(+), 11 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index d23195588d..5fa9535648 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -130,7 +130,13 @@ mod system { return papers; } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. - let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(cups_server().as_deref(), printer) else { return papers }; + let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); + // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. + let server = cups_server().or_else(|| { + let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; + (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) + }); + let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index fb122e1c67..bb5bb040a5 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -692,11 +692,34 @@ fn a_queue_without_any_ppd_lists_the_media_its_ipp_attributes_report() { #[test] fn the_ipp_lookup_asks_the_scheduler_cups_uses_for_the_queue() { use crate::print::ipp_queue_uri; - assert_eq!(ipp_queue_uri(None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor")); - assert_eq!(ipp_queue_uri(Some(" "), "Lab").as_deref(), Some("ipp://localhost/printers/Lab")); - assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab")); - assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), "Lab"), None, "a domain socket has no URI"); - assert_eq!(ipp_queue_uri(None, ""), None); + assert_eq!(ipp_queue_uri(None, None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor")); + assert_eq!(ipp_queue_uri(Some(" "), None, "Lab").as_deref(), Some("ipp://localhost/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), None, "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), None, "Lab"), None, "a domain socket has no URI"); + assert_eq!(ipp_queue_uri(None, None, ""), None); +} + +#[test] +fn the_ipp_lookup_uses_ipp_port_for_a_server_without_a_port() { + use crate::print::{ipp_port, ipp_queue_uri}; + assert_eq!(ipp_queue_uri(Some("print.example.com"), Some(8631), "Lab").as_deref(), Some("ipp://print.example.com:8631/printers/Lab")); + assert_eq!( + ipp_queue_uri(None, Some(8631), "Lab").as_deref(), + Some("ipp://localhost/printers/Lab"), + "with no server named, CUPS uses its domain socket, not IPP_PORT" + ); + assert_eq!( + ipp_queue_uri(Some("print.example.com:631"), Some(8631), "Lab").as_deref(), + Some("ipp://print.example.com:631/printers/Lab"), + "a port in the server name wins" + ); + assert_eq!(ipp_queue_uri(Some("[::1]"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:8631/printers/Lab")); + assert_eq!(ipp_queue_uri(Some("[::1]:632"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:632/printers/Lab")); + assert_eq!(ipp_port(Some("8631")), Some(8631)); + for invalid in [None, Some(""), Some("0"), Some("70000"), Some("ipp")] { + assert_eq!(ipp_port(invalid), None, "{invalid:?}"); + } + assert_eq!(ipp_queue_uri(Some("print.example.com"), ipp_port(Some("x")), "Lab").as_deref(), Some("ipp://print.example.com/printers/Lab")); } /// What the paper-keyword service was asked to print on: each job's paper. diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 919b834d18..1f1cf1981f 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -191,9 +191,14 @@ pub fn lpoptions_papers(out: &str) -> Vec { /// The IPP URI of the queue `printer` on the CUPS scheduler `server` (`CUPS_SERVER` or a `ServerName`: `host`, /// `host:port`, `host:port/version=1.1`; `None` or empty for this machine's). `None` for a domain-socket server (a path), -/// which `ipptool` can't reach by URI. The queue name is percent-encoded. -pub fn ipp_queue_uri(server: Option<&str>, printer: &str) -> Option { - let server = server.map(str::trim).filter(|s| !s.is_empty()).unwrap_or("localhost"); +/// which `ipptool` can't reach by URI. A server named without a port of its own gets `port` (from [`ipp_port`]) when +/// there is one; a bracketed IPv6 host (`[::1]`) has a port only after its `]`. With no server named, the URI is +/// `localhost` on the IPP default port, for a CUPS that reaches its own scheduler through its domain socket; a caller +/// whose CUPS has no socket names `localhost` to get `port`. The queue name is percent-encoded. +pub fn ipp_queue_uri(server: Option<&str>, port: Option, printer: &str) -> Option { + let named = server.map(str::trim).filter(|s| !s.is_empty()); + let port = if named.is_some() { port } else { None }; + let server = named.unwrap_or("localhost"); if server.starts_with('/') || printer.is_empty() { return None; } @@ -209,7 +214,21 @@ pub fn ipp_queue_uri(server: Option<&str>, printer: &str) -> Option { name.push_str(&format!("%{b:02X}")); } } - Some(format!("ipp://{host}/printers/{name}")) + let has_port = match host.strip_prefix('[') { + Some(rest) => rest.split_once(']').is_some_and(|(_, after)| after.starts_with(':')), + None => host.contains(':'), + }; + let port = match port { + Some(port) if !has_port => format!(":{port}"), + _ => String::new(), + }; + Some(format!("ipp://{host}{port}/printers/{name}")) +} + +/// The port CUPS clients use for a server named without one, from the value of `IPP_PORT`: `None` when it is unset, +/// empty or not a port number from 1 to 65535. +pub fn ipp_port(value: Option<&str>) -> Option { + value.and_then(|v| v.trim().parse::().ok()).filter(|p| *p != 0) } /// The size in points of a CUPS PPD keyword for a B size: `B4` and `B5` are the JIS sizes, `ISOB4` and `ISOB5` the ISO diff --git a/docs/mcp.md b/docs/mcp.md index 669e8dff94..8d0d9c3dff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13228,7 +13228,9 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue) lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes -of its IPP `media-supported` attribute. +of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, +`client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is +asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}} From af28b5380cd8666872de165e6b2f261e9da2248c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 12:51:04 -0800 Subject: [PATCH 4/5] Print: a remote CUPS scheduler supplies its own paper sizes When CUPS_SERVER or client.conf's ServerName names a remote scheduler, the Print dialog no longer reads a same-named PPD under /etc/cups/ppd. The job goes to the remote queue, so the sizes now come from that server through lpoptions and IPP. A domain socket, localhost, 127.0.0.1 and ::1, with an optional port and /version= suffix, still count as local and keep the PPD lookup. --- apps/vectorcraft/src/printing.rs | 67 ++++++++++++++++++++++++++++---- docs/mcp.md | 3 +- 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index f81ca95306..7bfb550876 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -169,12 +169,17 @@ mod system { if printer.contains(['/', '\\']) || printer.starts_with('.') { return Vec::new(); } - const PPD_CAP: u64 = 16 << 20; - let mut bytes = Vec::new(); - let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); - let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; - if !papers.is_empty() { - return papers; + let named = cups_server(); + // A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue, + // so its sizes come from the server. + if scheduler_is_local(named.as_deref()) { + const PPD_CAP: u64 = 16 << 20; + let mut bytes = Vec::new(); + let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); + let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() }; + if !papers.is_empty() { + return papers; + } } // A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes. let mut command = Command::new("lpoptions"); @@ -188,7 +193,7 @@ mod system { // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. - let server = cups_server().or_else(|| { + let server = named.or_else(|| { let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) }); @@ -242,6 +247,25 @@ mod system { client_conf_server_name(&text) }) } + /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, + /// or `localhost`, `127.0.0.1` or `::1`, each with an optional `:port` and `/version=` suffix. + #[cfg(not(windows))] + pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { + let Some(server) = server.map(str::trim) else { return true }; + if server.starts_with('/') { + return true; + } + // A network name may end in `/version=1.1`. + let server = server.split_once('/').map_or(server, |(server, _)| server); + let host = if let Some(rest) = server.strip_prefix('[') { + rest.split_once(']').map_or(rest, |(host, _)| host) + } else if server.matches(':').count() == 1 { + server.split_once(':').map_or(server, |(host, _)| host) + } else { + server + }; + host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" + } /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is /// dropped and the rest of the line is kept as written. @@ -557,7 +581,34 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::client_conf_server_name; + use super::system::{client_conf_server_name, scheduler_is_local}; + + #[test] + fn only_a_scheduler_on_this_machine_counts_as_local() { + for local in [ + None, + Some("/run/cups/cups.sock"), + Some("localhost"), + Some("LocalHost:631"), + Some("127.0.0.1:8631"), + Some("::1"), + Some("[::1]:631"), + Some("localhost/version=1.1"), + ] { + assert!(scheduler_is_local(local), "{local:?}"); + } + for remote in [ + "print.example.com", + "print.example.com:631", + "192.0.2.7", + "[2001:db8::1]:631", + "2001:db8::1", + "localhost.example.com", + "print.example.com:631/version=1.1", + ] { + assert!(!scheduler_is_local(Some(remote)), "{remote}"); + } + } #[test] fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() { diff --git a/docs/mcp.md b/docs/mcp.md index bf0f467ea4..fb72b22769 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13252,7 +13252,8 @@ default printer) or, with `toFile`, a `path` or no printing available, saves the driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or -remote queue) lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, +`localhost`, `127.0.0.1` or `::1`, lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. From 15d11beb8369075c7331edcf2f2b912559d862cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 15:48:30 -0800 Subject: [PATCH 5/5] Print: a second scheduler on a loopback port supplies its own paper sizes A `CUPS_SERVER` or `ServerName` of `localhost`, `127.0.0.1` or `::1` counts as this machine's scheduler only with no port or port 631. On another port (a second CUPS instance) the dialog no longer reads `/etc/cups/ppd`, whose queues belong to the default scheduler, and asks `lpoptions` and IPP instead. When the named server is one of CUPS's own domain sockets and neither the PPD nor `lpoptions` lists sizes, the IPP lookup asks `localhost` on the IPP default port, as it already does when no server is named. `ipptool` rejects a URI whose host is a socket path (`httpSeparateURI` in CUPS's `cups/http-support.c`), so another socket path is not asked. --- apps/vectorcraft/src/printing.rs | 61 +++++++++++++++++++++++++------- docs/mcp.md | 5 +-- 2 files changed, 51 insertions(+), 15 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index f77d74610c..4eb39067a0 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -199,11 +199,7 @@ mod system { } // A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses. let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref()); - // With no server named, CUPS uses its domain socket when it exists, and `localhost` on `IPP_PORT` otherwise. - let server = named.or_else(|| { - let sockets = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; - (!sockets.iter().any(|s| std::path::Path::new(s).exists())).then(|| "localhost".to_string()) - }); + let server = ipp_server(named, |s| std::path::Path::new(s).exists()); let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers }; use std::io::Write as _; use std::sync::atomic::{AtomicU64, Ordering}; @@ -235,6 +231,24 @@ mod system { output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() } } + /// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`. + #[cfg(not(windows))] + const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"]; + /// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server + /// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default + /// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local + /// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job + /// does not go to. + /// + /// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri + #[cfg(not(windows))] + pub(super) fn ipp_server(named: Option, exists: impl Fn(&str) -> bool) -> Option { + match named { + Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None, + Some(server) => Some(server), + None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()), + } + } /// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or /// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName` /// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts. @@ -255,7 +269,8 @@ mod system { }) } /// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path, - /// or `localhost`, `127.0.0.1` or `::1`, each with an optional `:port` and `/version=` suffix. + /// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback + /// name on another port is a second scheduler, whose queues the local PPD folder does not describe. #[cfg(not(windows))] pub(super) fn scheduler_is_local(server: Option<&str>) -> bool { let Some(server) = server.map(str::trim) else { return true }; @@ -264,14 +279,15 @@ mod system { } // A network name may end in `/version=1.1`. let server = server.split_once('/').map_or(server, |(server, _)| server); - let host = if let Some(rest) = server.strip_prefix('[') { - rest.split_once(']').map_or(rest, |(host, _)| host) + let (host, port) = if let Some(rest) = server.strip_prefix('[') { + rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':'))) } else if server.matches(':').count() == 1 { - server.split_once(':').map_or(server, |(host, _)| host) + server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port))) } else { - server + (server, None) }; - host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" + let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1"; + loopback && port.is_none_or(|port| port.trim() == "631") } /// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a /// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is @@ -588,7 +604,19 @@ mod turn_tests { #[cfg(all(test, not(windows)))] mod client_conf_tests { - use super::system::{client_conf_server_name, scheduler_is_local}; + use super::system::{client_conf_server_name, ipp_server, scheduler_is_local}; + + #[test] + fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() { + let none = |_: &str| false; + let socket = |s: &str| s == "/run/cups/cups.sock"; + assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631"); + assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None); + assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked"); + assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631")); + assert_eq!(ipp_server(None, socket), None); + assert_eq!(ipp_server(None, none).as_deref(), Some("localhost")); + } #[test] fn only_a_scheduler_on_this_machine_counts_as_local() { @@ -597,10 +625,13 @@ mod client_conf_tests { Some("/run/cups/cups.sock"), Some("localhost"), Some("LocalHost:631"), - Some("127.0.0.1:8631"), + Some("localhost:631"), + Some("127.0.0.1:631"), Some("::1"), Some("[::1]:631"), + Some("[::1]"), Some("localhost/version=1.1"), + Some("localhost:631/version=1.1"), ] { assert!(scheduler_is_local(local), "{local:?}"); } @@ -612,6 +643,10 @@ mod client_conf_tests { "2001:db8::1", "localhost.example.com", "print.example.com:631/version=1.1", + "localhost:8631", + "127.0.0.1:8631", + "[::1]:8631", + "localhost:8631/version=1.1", ] { assert!(!scheduler_is_local(Some(remote)), "{remote}"); } diff --git a/docs/mcp.md b/docs/mcp.md index 8a0b9f86ee..250806a975 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13344,10 +13344,11 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the `media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket, -`localhost`, `127.0.0.1` or `::1`, lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes +`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux, `client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is -asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. +asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the +server is asked as `localhost` on port 631; another socket path is not asked. In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once. The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available.