From 78a1fed433fb7bc7fd6327fe1d480d3eb2510173 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 2 Dec 2026 21:38:04 +0100 Subject: [PATCH] Apply advertised CUPS custom paper only on explicit selection Use the shared range catalog for the selected queue, preserve the editor size limits and carry the selected media keyword to lp. Keep normal Custom available for keeping PDF dimensions, and preserve distinct fixed media keys even when they share dimensions. --- apps/vectorcraft/src/printing.rs | 66 +++++++------- crates/ui-egui/src/dialogs/print.rs | 87 ++++++++++++------ crates/ui-egui/src/dialogs/tests_print.rs | 105 ++++++++++++++++++++-- crates/ui-egui/src/print.rs | 59 +++++++++++- docs/mcp.md | 5 +- 5 files changed, 252 insertions(+), 70 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 39a2b587b6..b0a4c8f556 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -1,7 +1,7 @@ //! Desktop printer transport. VectorCraft composes every page and copy before submission; //! craft-print owns discovery and spooling. use std::process::Command; -use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer}; +use vectorcraft_ui_egui::print::{PaperCatalog, Papers, PrintJob, PrintService, Printer}; mod direct_pdf; @@ -45,7 +45,7 @@ impl PrintService for SystemPrint { } /// A paper-size read that waits for the worker before it. -type PaperRead = Box Vec + Send>; +type PaperRead = Box PaperCatalog + Send>; /// How long the newest still-running worker runs before a waiting read may start beside it, and how long a read waits /// when no worker may start before its printer is given no paper sizes. @@ -59,7 +59,7 @@ const PAPER_WORKERS: usize = 4; /// the newest still-running worker has run [`PAPER_WAIT`] and fewer than [`PAPER_WORKERS`] are alive. #[derive(Default)] struct PaperLookup { - current: Option<(String, std::sync::mpsc::Receiver>)>, + current: Option<(String, std::sync::mpsc::Receiver)>, waiting: Option<(String, PaperRead, std::time::Instant)>, started: Vec<(std::time::Instant, std::sync::Arc)>, workers: std::sync::Arc, @@ -81,7 +81,7 @@ impl PaperLookup { /// waiting read starts, when the workers allow it at `now`. Each new or replacement read begins waiting at `now`. /// Finished workers do not delay a waiting read. A read that has waited [`PAPER_WAIT`] while /// [`PAPER_WORKERS`] workers stall is dropped, and the printer gets no paper sizes. - fn poll(&mut self, printer: &str, fresh: bool, now: std::time::Instant, read: impl FnOnce(String) -> Vec + Send + 'static) -> Papers { + fn poll(&mut self, printer: &str, fresh: bool, now: std::time::Instant, read: impl FnOnce(String) -> PaperCatalog + Send + 'static) -> Papers { let wanted = self.waiting.as_ref().map(|(p, ..)| p).or(self.current.as_ref().map(|(p, _)| p)); if fresh || wanted.is_none_or(|p| p != printer) { self.current = None; @@ -104,7 +104,7 @@ impl PaperLookup { let _ = send.send(papers); }); if spawned.is_err() { - return Papers::Ready(Vec::new()); + return Papers::Ready(PaperCatalog::default()); } self.started.push((now, running)); self.current = Some((name, receive)); @@ -114,12 +114,12 @@ impl PaperLookup { return Papers::Pending; } self.waiting = None; - return Papers::Ready(Vec::new()); + return Papers::Ready(PaperCatalog::default()); } let result = match self.current.as_ref().map(|(_, receive)| receive.try_recv()) { Some(Ok(papers)) => Papers::Ready(papers), Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending, - Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()), + Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(PaperCatalog::default()), }; self.current = None; result @@ -127,9 +127,9 @@ impl PaperLookup { } /// Look up only an installed printer's own name. -fn installed_papers(printer: &str) -> Vec { +fn installed_papers(printer: &str) -> PaperCatalog { if printer.is_empty() || !system::printers().iter().any(|p| p.name == printer) { - return Vec::new(); + return PaperCatalog::default(); } system::papers(printer) } @@ -144,26 +144,25 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String { } mod system { - use super::{Command, Paper, PrintJob, Printer}; + use super::{Command, PaperCatalog, PrintJob, Printer}; pub fn printers() -> Vec { craft::print::printers().into_iter().map(Printer::from).collect() } /// The paper sizes of an installed printer, discovered on the worker by craft-print. - pub fn papers(printer: &str) -> Vec { + pub fn papers(printer: &str) -> PaperCatalog { #[cfg(windows)] { let forms = craft::print::printer_papers(printer); - vectorcraft_ui_egui::print::windows_driver_papers(forms.into_iter().map(|form| (form.name, form.width, form.height))) + vectorcraft_ui_egui::print::windows_driver_papers(forms.into_iter().map(|form| (form.name, form.width, form.height))).into() } #[cfg(unix)] { - let catalog = craft::print::cups::media_catalog(printer); - vectorcraft_ui_egui::print::cups_driver_papers(catalog.sizes.into_iter().map(|size| (size.key, size.label, size.width, size.height))) + PaperCatalog::from_cups(craft::print::cups::media_catalog(printer)) } #[cfg(not(any(unix, windows)))] { let _ = printer; - Vec::new() + PaperCatalog::default() } } pub fn print(job: &PrintJob) -> Result { @@ -259,10 +258,10 @@ mod tests { #[cfg(test)] mod paper_lookup_tests { use super::PaperLookup; - use vectorcraft_ui_egui::print::{Paper, Papers}; + use vectorcraft_ui_egui::print::{Paper, PaperCatalog, Papers}; - fn paper(key: &str) -> Vec { - vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }] + fn paper(key: &str) -> PaperCatalog { + vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }].into() } /// The test clock: `secs` seconds after a fixed start. @@ -275,7 +274,7 @@ mod paper_lookup_tests { fn settle(lookup: &mut PaperLookup, printer: &str, now: std::time::Instant) -> Vec { loop { match lookup.poll(printer, false, now, |_| panic!("polling starts no lookup")) { - Papers::Ready(papers) => return papers, + Papers::Ready(papers) => return papers.sizes, Papers::Pending => std::thread::yield_now(), } } @@ -284,13 +283,13 @@ mod paper_lookup_tests { /// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers. fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec { match lookup.poll(printer, true, at(0), move |_| paper(key)) { - Papers::Ready(papers) => papers, + Papers::Ready(papers) => papers.sizes, Papers::Pending => settle(lookup, printer, at(0)), } } /// A read that answers `key` once `gate` lets it. - fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> Vec + Send + 'static) { + fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> PaperCatalog + Send + 'static) { let (open, gate) = std::sync::mpsc::channel::<()>(); (open, move |_| { let _ = gate.recv(); @@ -308,12 +307,12 @@ mod paper_lookup_tests { let _ = open.send(()); let _ = other.send(()); // Back on the card printer. - assert_eq!(answer(&mut lookup, "Card", "New"), paper("New")); + assert_eq!(answer(&mut lookup, "Card", "New"), paper("New").sizes); // The dialog opens again on the card printer while a lookup of it is still running. let (open, read) = gated("Stale"); assert!(matches!(lookup.poll("Card", true, at(0), read), Papers::Pending)); let _ = open.send(()); - assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer")); + assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer").sizes); } #[test] @@ -334,7 +333,7 @@ mod paper_lookup_tests { } let _ = open.send(()); // Only the newest choice is read, once the stalled worker ends. - assert_eq!(settle(&mut lookup, "Plotter", at(2)), paper("Changed")); + assert_eq!(settle(&mut lookup, "Plotter", at(2)), paper("Changed").sizes); assert_eq!(started.load(Ordering::SeqCst), 1); } @@ -352,7 +351,7 @@ mod paper_lookup_tests { assert!(matches!(lookup.poll("Office", false, at(15), |_| panic!("polling starts no lookup")), Papers::Pending)); assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the waiting read starts beside the stalled worker"); let _ = office.send(()); - assert_eq!(settle(&mut lookup, "Office", at(15)), paper("Office")); + assert_eq!(settle(&mut lookup, "Office", at(15)), paper("Office").sizes); // The worker that answered counts itself down once its thread ends. while lookup.workers.load(Ordering::SeqCst) > 1 { std::thread::yield_now(); @@ -370,7 +369,7 @@ mod paper_lookup_tests { assert_eq!(lookup.workers.load(Ordering::SeqCst), 2, "the next read starts without another wait"); began.recv().expect("the next read started"); let _ = open.send(()); - assert_eq!(settle(&mut lookup, "Next", at(16)), paper("Next")); + assert_eq!(settle(&mut lookup, "Next", at(16)), paper("Next").sizes); drop(card); } @@ -394,17 +393,17 @@ mod paper_lookup_tests { assert!(matches!(lookup.poll("Photo", false, at(91), |_| panic!("no worker may start")), Papers::Pending)); assert!(matches!(lookup.poll("Photo", false, at(105), |_| panic!("polling starts no lookup")), Papers::Pending)); match lookup.poll("Photo", false, at(106), |_| panic!("polling starts no lookup")) { - Papers::Ready(papers) => assert_eq!(papers, []), + Papers::Ready(papers) => assert!(papers.sizes.is_empty()), Papers::Pending => panic!("the wait for the stalled workers did not end"), } assert!(lookup.workers.load(Ordering::SeqCst) <= super::PAPER_WORKERS); // Once the stalled workers end, the next choice is read again. drop(stalls); let papers = match lookup.poll("Photo", true, at(107), |_| paper("Ready")) { - Papers::Ready(papers) => papers, + Papers::Ready(papers) => papers.sizes, Papers::Pending => settle(&mut lookup, "Photo", at(107)), }; - assert_eq!(papers, paper("Ready")); + assert_eq!(papers, paper("Ready").sizes); } } @@ -436,9 +435,12 @@ mod job_settings_tests { #[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:?}"); + for key in ["CR80", "ISOB5", "B5", "Custom.432x648"] { + let args = craft::print::lp_args(&settings(&job(Some(key)))); + let expected = format!("media={key}"); + assert!(args.windows(2).any(|w| w == ["-o", &expected]), "{args:?}"); + assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}"); + } } #[test] diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 372f2679c1..f462bc5f0e 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -46,7 +46,7 @@ use vectorcraft_pdf::{ }; use super::form; -use crate::print::{Paper, Papers}; +use crate::print::{Paper, PaperCatalog, Papers}; use crate::{VectorcraftApp, graphics}; pub(crate) const SECTIONS: [&str; 7] = ["General", "Marks and Bleed", "Output", "Graphics", "Color Management", "Advanced", "Summary"]; @@ -114,7 +114,7 @@ struct Open { driver: DriverControls, /// The printer the Media list was made for, and the paper sizes its driver offers (while its lookup runs, the sizes /// of the printer before it). - papers: (String, Vec), + papers: (String, PaperCatalog), /// Whether the chosen printer still has a lookup running. papers_pending: bool, /// The ids of the Size choices the dialog was last given. @@ -154,7 +154,7 @@ struct Lists { } impl Lists { - fn of(app: &VectorcraftApp, papers: &[Paper], media: &str) -> Self { + fn of(app: &VectorcraftApp, papers: &PaperCatalog, media: &str) -> Self { Self { profiles: vectorcraft_color::cms::profiles().iter().map(|p| p.name.clone()).collect(), flatteners: app.session.flattener_presets().iter().map(|p| p.name.clone()).collect(), @@ -165,6 +165,8 @@ impl Lists { /// The prefix of a Size choice that is one of the printer's own paper sizes (`printer:CR80`). const PRINTER_PAPER: &str = "printer:"; +/// An explicit custom-size request for a driver which offers variable media. +const QUEUE_CUSTOM: &str = "queue-custom"; /// The dialog's own papers, as (id, label). fn own_media() -> Vec<(String, String)> { @@ -175,7 +177,8 @@ fn own_media() -> Vec<(String, String)> { /// the dialog's own papers. A paper the dialog has itself, by size, keeps the dialog's id (so `letter` stays `letter`) /// under the driver's name; the others are `printer:`. Custom is always offered. No papers: the dialog's own /// list. -fn media_choices(papers: &[Paper], current: &str) -> Vec<(String, String)> { +fn media_choices(catalog: &PaperCatalog, current: &str) -> Vec<(String, String)> { + let papers = &catalog.sizes; let mut out = if papers.is_empty() { own_media() } else { @@ -189,7 +192,10 @@ fn media_choices(papers: &[Paper], current: &str) -> Vec<(String, String)> { out.push((Media::Custom.id().to_string(), tl!(Media::Custom.label()).to_string())); out }; - if !current.is_empty() && !current.starts_with(PRINTER_PAPER) && out.iter().all(|(i, _)| i != current) { + if catalog.offers_custom_media() { + out.push((QUEUE_CUSTOM.to_string(), tl!("Custom (printer)").to_string())); + } + if !current.is_empty() && current != QUEUE_CUSTOM && !current.starts_with(PRINTER_PAPER) && out.iter().all(|(i, _)| i != current) { // A built-in paper the printer doesn't list stays chosen until it is changed. let label = Media::from_name(current).map_or_else(|| current.trim_start_matches(PRINTER_PAPER).to_string(), |m| tl!(m.label()).to_string()); out.push((current.to_string(), label)); @@ -203,11 +209,13 @@ fn own_media_of(p: &Paper) -> Option { Media::ALL.iter().copied().find(|m| m.size().is_some_and(|(mw, mh)| (mw.min(mh) - w).abs() <= 0.5 && (mw.max(mh) - h).abs() <= 0.5)) } -/// [`own_media_of`] `p`, unless another of `papers` with a different size matches the same size: both then stay -/// the printer's own papers. +/// Keep the built-in id for the first choice at a matching size, and keep additional +/// keywords selectable. If the matching forms differ in size, each keeps its exact dimensions. fn own_media_choice(p: &Paper, papers: &[Paper]) -> Option { let own = own_media_of(p)?; - (!papers.iter().any(|q| own_media_of(q) == Some(own) && (q.width, q.height) != (p.width, p.height))).then_some(own) + let mut matching = papers.iter().filter(|q| own_media_of(q) == Some(own)); + let first = matching.next()?; + (p.key == first.key && matching.all(|q| (q.width, q.height) == (p.width, p.height))).then_some(own) } /// The printer's paper the Size row names (`printer:CR80`), when it is one of `papers`. @@ -244,14 +252,14 @@ fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { /// The paper sizes the driver of `printer` offers (none for preset editing, the default printer and PDF File). `fresh` /// starts a new lookup: the dialog opened or the printer changed. -fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str, fresh: bool) -> (Vec, bool) { +fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str, fresh: bool) -> (PaperCatalog, bool) { if mode == PrintMode::PresetEditor || printer.is_empty() || printer == PDF_FILE { - return (Vec::new(), false); + return (PaperCatalog::default(), false); } match app.services.print.as_mut().map(|s| s.papers(printer, fresh)) { Some(Papers::Ready(papers)) => (papers, false), - Some(Papers::Pending) => (Vec::new(), true), - None => (Vec::new(), false), + Some(Papers::Pending) => (PaperCatalog::default(), true), + None => (PaperCatalog::default(), false), } } @@ -443,7 +451,7 @@ pub(super) fn settings(fields: &DialogFields) -> Value { p.remove(k); } // A printer's own paper prints as a custom size: the pump keeps Width and Height at its size. - if p.get("media").and_then(Value::as_str).is_some_and(|m| m.starts_with(PRINTER_PAPER)) { + if p.get("media").and_then(Value::as_str).is_some_and(|m| m == QUEUE_CUSTOM || m.starts_with(PRINTER_PAPER)) { p.insert("media".into(), json!(Media::Custom.id())); } Value::Object(nested(p)) @@ -504,15 +512,27 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, // hold it. let mut media = on(dialogs, |p| p.fields().text("media").map(str::to_string)).flatten().unwrap_or_default(); let printer_changed = d.printer != open.papers.0; + if printer_changed && media == QUEUE_CUSTOM { + // A custom-media request belongs to the queue that advertised the range. Keep + // the composed size when changing printers and leave the new queue's media alone. + media = Media::Custom.id().to_owned(); + on(dialogs, |p| p.fields_mut().set("media", Media::Custom.id())); + } + if printer_changed + && let Some(answer) = &mut d.ok + && answer.fields.text("media") == Some(QUEUE_CUSTOM) + { + answer.fields.set("media", Media::Custom.id()); + } let mut papers_changed = false; // 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(); + let chosen = on(dialogs, |p| printer_paper(p.fields(), &open.papers.1.sizes).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))) + && let Some(paper) = printer_paper(&answer.fields, &open.papers.1.sizes) + && (pending || !printer_paper(&answer.fields, &papers.sizes).is_some_and(|new| same_size(paper, new))) { answer.fields.set("width", paper.width); answer.fields.set("height", paper.height); @@ -537,10 +557,10 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, && media.starts_with(PRINTER_PAPER) && let Some((id, s)) = on(dialogs, |p| { let fields = p.fields_mut(); - if let Some(new) = printer_paper(fields, &open.papers.1) + if let Some(new) = printer_paper(fields, &open.papers.1.sizes) && chosen.as_ref().is_none_or(|old| same_size(old, new)) { - let own = own_media_choice(new, &open.papers.1)?; + let own = own_media_choice(new, &open.papers.1.sizes)?; fields.set("media", own.id()); return Some((own.id().to_string(), settings(fields))); } @@ -563,7 +583,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ctx.request_repaint(); } // One of the printer's papers: Width and Height hold its size, which is what prints. - let papers = &open.papers.1; + let papers = &open.papers.1.sizes; if let Some(s) = on(dialogs, |p| { let fields = p.fields_mut(); let paper = printer_paper(fields, papers)?; @@ -685,7 +705,7 @@ fn apply_preset_event(app: &mut VectorcraftApp, dialogs: &WindowDialogs, open: & } NamedPresetEvent::Create { name, .. } => { // A printer's paper chosen this pass is saved at its size, which the dialog shows once the pump has run. - let saved = on(dialogs, |p| settings_with_paper(p.fields(), &open.papers.1)).unwrap_or_else(|| settings.clone()); + let saved = on(dialogs, |p| settings_with_paper(p.fields(), &open.papers.1.sizes)).unwrap_or_else(|| settings.clone()); match app.run("print.presets.save", json!({ "name": name, "preset": DEFAULT_PRESET, "settings": saved })) { Ok(r) => open.preset = r["name"].as_str().unwrap_or(&name).to_string(), Err(e) => app.status(e), @@ -718,7 +738,7 @@ fn drags(moves: EditEvents) -> Vec<(f64, f64)> { fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &str) -> Result<(), String> { // The answer holds the fields as they were when OK was pressed, which can be before the pump set a printer's // paper's size. - let settings = settings_with_paper(&answer.fields, &open.papers.1); + let settings = settings_with_paper(&answer.fields, &open.papers.1.sizes); if open.mode == PrintMode::PresetEditor { return save_preset(app, open, name, settings); } @@ -728,15 +748,28 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st }; 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()); - } + let paper = if matches!(answer.finish, PrintFinish::Print) && applies_paper { + if open.papers_pending || open.papers.0 != printer { + return Err("The printer's paper sizes are still loading; try Print again in a moment.".into()); + } + if answer.fields.text("media") == Some(QUEUE_CUSTOM) { + let custom = answer.fields.number("width").zip(answer.fields.number("height")); + Some( + custom + .and_then(|(width, height)| open.papers.1.custom_media(width, height)) + .ok_or_else(|| tl!("This printer does not support custom paper at the entered width and height.").to_string())?, + ) + } else { + driver_paper_key(&answer.fields, &open.papers.1.sizes).map(str::to_owned) + } + } else { + None + }; // 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 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(|_| ()) } @@ -930,8 +963,8 @@ fn sections(lists: &Lists) -> Vec { flag("skipBlank", tl!("Skip Blank Artboards")).enabled_when_in("artboards", [PrintArtboards::All.id(), PrintArtboards::Range.id()]), Param::section(tl!("Media")), Param::new("media", tl!("Size:"), ParamKind::choice(media.into_iter().map(|(i, l)| (i, l.into())).collect(), None)), - length("width", tl!("Width:")).enabled_when("media", "custom"), - length("height", tl!("Height:")).enabled_when("media", "custom"), + length("width", tl!("Width:")).enabled_when_in("media", [Media::Custom.id(), QUEUE_CUSTOM]), + length("height", tl!("Height:")).enabled_when_in("media", [Media::Custom.id(), QUEUE_CUSTOM]), Param::section(tl!("Orientation")), flag("autoRotate", tl!("Auto-Rotate (turn the paper to each artboard)")), pick::("orientation", tl!("Orientation:")).enabled_when("autoRotate", false), diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index f83acbb16c..5a00dc152e 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -252,10 +252,13 @@ impl PrintService for PaperPrint { fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { self.1.borrow_mut().push(printer.to_string()); let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height }; - Papers::Ready(match printer { - "Card" => vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)], - _ => vec![], - }) + Papers::Ready( + match printer { + "Card" => vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)], + _ => vec![], + } + .into(), + ) } } @@ -417,7 +420,7 @@ impl PrintService for CardPrinters { fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { let (width, height) = if printer == "Badge" { (200.0, 300.0) } else { (153.0, 243.0) }; - Papers::Ready(vec![crate::print::Paper { key: "CR80".into(), label: "CR80 Card".into(), width, height }]) + Papers::Ready(vec![crate::print::Paper { key: "CR80".into(), label: "CR80 Card".into(), width, height }].into()) } } @@ -458,7 +461,7 @@ impl PrintService for NearLetter { fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { let width = if printer == "Far" { 611.6 } else { 611.2 }; - Papers::Ready(vec![crate::print::Paper { key: "Wide".into(), label: "Wide".into(), width, height: 792.0 }]) + Papers::Ready(vec![crate::print::Paper { key: "Wide".into(), label: "Wide".into(), width, height: 792.0 }].into()) } } @@ -678,7 +681,7 @@ impl PrintService for KeywordPrint { 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)]) + Papers::Ready(vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)].into()) } } @@ -730,7 +733,7 @@ impl PrintService for WindowsForms { fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { let out = if printer == "Reverse" { self.0.lines().rev().collect::>().join("\n") } else { self.0.to_string() }; - Papers::Ready(crate::print::windows_papers(&out)) + Papers::Ready(crate::print::windows_papers(&out).into()) } } @@ -770,6 +773,92 @@ fn the_job_asks_the_queue_for_the_driver_paper_chosen() { assert_eq!(sent.borrow().len(), 4, "no refused job was sent"); } +#[cfg(unix)] +struct RollPrint(SentPapers); + +#[cfg(unix)] +impl PrintService for RollPrint { + fn applies_paper(&self) -> bool { + true + } + + fn printers(&mut self) -> Vec { + vec![Printer::new("Roll").is_default(true), Printer::new("Other")] + } + + 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 { + use craft::print::cups::{CustomMediaRange, MediaCatalog, MediaSize}; + let letter = |key: &str| MediaSize { key: key.into(), label: key.into(), width: 612.0, height: 792.0 }; + let catalog = MediaCatalog { + sizes: vec![letter("Letter"), letter("LetterAlternate")], + custom_ranges: vec![ + CustomMediaRange { min_width: 288.0, max_width: 288.0, min_height: 216.0, max_height: 432.0 }, + CustomMediaRange { min_width: 432.0, max_width: 432.0, min_height: 216.0, max_height: 864.0 }, + ], + ..Default::default() + }; + Papers::Ready(crate::print::PaperCatalog::from_cups(catalog)) + } +} + +#[cfg(unix)] +#[test] +fn shared_cups_ranges_apply_only_for_an_explicit_supported_size() { + let sent = SentPapers::default(); + let services = Services { print: Some(Box::new(RollPrint(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!("queue-custom")); + set(&mut app, "width", json!(288.0)); + set(&mut app, "height", json!(648.0)); + confirm(&mut app); + assert!(is_open(&app), "the longer length only fits the wider roll"); + assert!(sent.borrow().is_empty()); + + set(&mut app, "width", json!(432.0)); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(sent.borrow().as_slice(), [Some("Custom.432x648".into())]); + + // The composed dimensions survive a reopen, with the per-queue selection reset. + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + assert_eq!(fields(&app)["media"], "custom"); + assert_eq!(fields(&app)["height"].as_f64(), Some(648.0)); + + set(&mut app, "media", json!("queue-custom")); + set(&mut app, "printer", json!("Other")); + pump(&mut app); + assert_eq!(fields(&app)["media"], "custom"); + confirm(&mut app); + assert_eq!(sent.borrow().last(), Some(&None)); +} + +#[cfg(unix)] +#[test] +fn shared_cups_forms_with_the_same_dimensions_keep_distinct_job_keywords() { + let sent = SentPapers::default(); + let services = Services { print: Some(Box::new(RollPrint(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(); + for (choice, key) in [("letter", "Letter"), ("printer:LetterAlternate", "LetterAlternate")] { + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!(choice)); + confirm(&mut app); + assert!(!is_open(&app)); + assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), Some(key)); + } +} + #[test] fn a_job_without_a_paper_keyword_prints_while_the_paper_lookup_is_pending() { let sent = SentPapers::default(); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index c91a2f8369..31ef337fd9 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -75,18 +75,73 @@ pub trait PrintService { /// `fresh` is set when the dialog opens or the printer changes: the driver is read again, /// and a lookup still running from an earlier choice is dropped. fn papers(&mut self, _printer: &str, _fresh: bool) -> Papers { - Papers::Ready(Vec::new()) + Papers::Ready(PaperCatalog::default()) } } /// A driver's paper sizes, or a lookup still running on a worker. pub enum Papers { /// The lookup finished; an empty list uses the dialog's sizes. - Ready(Vec), + Ready(PaperCatalog), /// Poll again on a later frame. Pending, } +/// The fixed sizes and optional custom media supported by one queue. +#[derive(Default)] +pub struct PaperCatalog { + /// Driver forms within the limits of the paper editor. + pub sizes: Vec, + #[cfg(unix)] + cups: craft::print::cups::MediaCatalog, +} + +impl From> for PaperCatalog { + fn from(sizes: Vec) -> Self { + Self { sizes, ..Self::default() } + } +} + +impl PaperCatalog { + /// Apply the editor's size limits while retaining the driver's separate custom media ranges. + #[cfg(unix)] + pub fn from_cups(mut catalog: craft::print::cups::MediaCatalog) -> Self { + let sizes = std::mem::take(&mut catalog.sizes); + let sizes = cups_driver_papers(sizes.into_iter().map(|size| (size.key, size.label, size.width, size.height))); + Self { sizes, cups: catalog } + } + + pub(crate) fn offers_custom_media(&self) -> bool { + #[cfg(unix)] + { + self.cups.custom_ranges.iter().any(|range| { + range.min_width <= *PAPER_SIDE.end() + && range.max_width >= *PAPER_SIDE.start() + && range.min_height <= *PAPER_SIDE.end() + && range.max_height >= *PAPER_SIDE.start() + }) + } + #[cfg(not(unix))] + { + false + } + } + + pub(crate) fn custom_media(&self, width: f64, height: f64) -> Option { + if !PAPER_SIDE.contains(&width) || !PAPER_SIDE.contains(&height) { + return None; + } + #[cfg(unix)] + { + self.cups.custom_media(width, height) + } + #[cfg(not(unix))] + { + None + } + } +} + /// A paper size a printer's driver offers. #[derive(Clone, Debug, PartialEq)] pub struct Paper { diff --git a/docs/mcp.md b/docs/mcp.md index dce6d0bbef..ad1b94cf3e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13271,7 +13271,10 @@ driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. For CUPS queues, the system's CUPS clients select the scheduler, including its configured port. VectorCraft reads local PPD dimensions, queue options from `lpoptions -l`, and IPP media for driverless queues. For remote schedulers -the installed `ipptool` client can supplement the queue options over TLS. +the installed `ipptool` client can supplement the queue options over TLS. The Print dialog offers +**Custom (printer)** when the queue accepts variable media within the editor's size limits. That choice sends the +entered dimensions as a CUPS media keyword if they fit one advertised range. **Custom** sets the PDF dimensions and +keeps the queue's paper setting. ```json {"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}}