From 4c883f94ccbba24d177a4cd9e2cd5e6ea82c8dd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 16:28:48 -0800 Subject: [PATCH] Print: the Size list shows the chosen printer's paper sizes File > Print offered the same built-in sizes for every printer, so a card printer's CR80 size could not be chosen. The Size list now holds the paper sizes the chosen printer's driver lists: the CUPS PPD's PaperDimension entries on macOS and Linux, and the printer's forms on Windows. A size the dialog has itself (Letter, A4) keeps its own id under the driver's name; others print as a custom size of the driver's width and height. Custom is always offered, and a printer whose driver lists nothing keeps the built-in list. The lookup runs on a worker thread and the dialog updates when it answers; the Windows lookup stops after 10 seconds. Each opening of the dialog and each printer change reads the driver again. A paper the new printer does not list becomes a custom size of the same width and height. The preset editor keeps the built-in list. --- apps/vectorcraft/src/host_services.rs | 2 +- apps/vectorcraft/src/printing.rs | 108 +++++++++- crates/ui-egui/src/dialogs/print.rs | 184 ++++++++++++++++- crates/ui-egui/src/dialogs/tests_print.rs | 238 +++++++++++++++++++++- crates/ui-egui/src/print.rs | 89 ++++++++ 5 files changed, 608 insertions(+), 13 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 47813f192e..9e416d7711 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -188,7 +188,7 @@ pub(crate) fn services(window: Parent) -> Services { check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. - print: Some(Box::new(printing::SystemPrint)), + print: Some(Box::new(printing::SystemPrint::default())), // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens // only while the active tool uses the wheel. #[cfg(all(windows, not(target_vendor = "win7")))] diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index fb28192f05..6725b72884 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -1,11 +1,16 @@ //! 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::{PrintJob, PrintService, Printer}; +use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer}; mod direct_pdf; -pub struct SystemPrint; +#[derive(Default)] +pub struct SystemPrint { + /// Channels for pending paper-size lookups, removed when each worker answers or disconnects. + papers: std::collections::HashMap>>, +} + impl PrintService for SystemPrint { fn printers(&mut self) -> Vec { system::printers() @@ -15,7 +20,7 @@ impl PrintService for SystemPrint { Ok(sent(job.title, job.printer, ¬e)) } fn shared_print(&self) -> Option { - Some(std::sync::Arc::new(|job| SystemPrint.print(job))) + Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e)))) } fn turns_landscape(&self) -> bool { // macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright @@ -28,6 +33,31 @@ impl PrintService for SystemPrint { fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { system::setup(printer) } + fn papers(&mut self, printer: &str) -> Papers { + let receive = self.papers.entry(printer.to_string()).or_insert_with(|| { + let (send, receive) = std::sync::mpsc::channel(); + let printer = printer.to_string(); + let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { + let _ = send.send(installed_papers(&printer)); + }); + receive + }); + let result = match receive.try_recv() { + Ok(papers) => Papers::Ready(papers), + Err(std::sync::mpsc::TryRecvError::Disconnected) => Papers::Ready(Vec::new()), + Err(std::sync::mpsc::TryRecvError::Empty) => return Papers::Pending, + }; + self.papers.remove(printer); + result + } +} + +/// Look up only an installed printer's own name. +fn installed_papers(printer: &str) -> Vec { + if printer.is_empty() || !system::printers().iter().any(|p| p.name == printer) { + return Vec::new(); + } + system::papers(printer) } /// The status after the job `title` went to `printer` (the default one without a name), with the @@ -40,10 +70,80 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String { } mod system { - use super::{Command, PrintJob, Printer}; + use super::{Command, Paper, PrintJob, Printer}; pub fn printers() -> Vec { craft::print::printers().into_iter().map(Printer::from).collect() } + /// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings. + pub fn papers(printer: &str) -> Vec { + #[cfg(windows)] + { + // The name goes in as an environment variable, never into the script's text. + const SCRIPT: &str = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Drawing; $s = New-Object System.Drawing.Printing.PrinterSettings; \ + $s.PrinterName = $env:VC_PRINTER; foreach ($p in $s.PaperSizes) { \"$($p.RawKind)`t$($p.PaperName)`t$($p.Width)`t$($p.Height)\" }"; + use std::os::windows::process::CommandExt as _; + // CREATE_NO_WINDOW: no console window opens over the app. + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut command = Command::new("powershell.exe"); + command.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("VC_PRINTER", printer).creation_flags(CREATE_NO_WINDOW); + paper_output(&mut command).map(|out| vectorcraft_ui_egui::print::windows_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() + } + #[cfg(not(windows))] + { + use std::io::Read as _; + // CUPS queue names never hold `/`, so the name can't leave the PPD folder. + 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)); + if read.is_err() { + return Vec::new(); + } + vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) + } + } + /// 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; + use std::time::{Duration, Instant}; + + const LIMIT: Duration = Duration::from_secs(10); + let started = Instant::now(); + let mut child = command.stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?; + let (send, receive) = std::sync::mpsc::channel(); + let stdout = child.stdout.take(); + let reader = std::thread::Builder::new().name("printer-paper-output".into()).spawn(move || { + let mut bytes = Vec::new(); + // Retain at most 16 MiB, but drain the rest so the child can finish. + let read = stdout.map(|mut out| { + out.by_ref().take(16 << 20).read_to_end(&mut bytes)?; + std::io::copy(&mut out, &mut std::io::sink()) + }); + let _ = send.send(read.and_then(Result::ok).map(|_| bytes)); + }); + if reader.is_err() { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + loop { + match child.try_wait() { + Ok(Some(status)) => { + return if status.success() { receive.recv_timeout(LIMIT.saturating_sub(started.elapsed())).ok().flatten() } else { None }; + } + Ok(None) if started.elapsed() < LIMIT => std::thread::sleep(Duration::from_millis(25)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + } + } pub fn print(job: &PrintJob) -> Result { if job.direct_pdf { return super::direct_pdf::print(job); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 05d46c3979..3021537994 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -46,6 +46,7 @@ use vectorcraft_pdf::{ }; use super::form; +use crate::print::{Paper, Papers}; use crate::{VectorcraftApp, graphics}; pub(crate) const SECTIONS: [&str; 7] = ["General", "Marks and Bleed", "Output", "Graphics", "Color Management", "Advanced", "Summary"]; @@ -111,6 +112,12 @@ struct Open { preview: Option<(Stamp, Arc>)>, /// The printer row's driver controls, as the dialog was last given them. driver: DriverControls, + /// The printer the Media list was made for, and the paper sizes its driver offers. + papers: (String, Vec), + /// Whether the chosen printer still has a lookup running. + papers_pending: bool, + /// The ids of the Size choices the dialog was last given. + media: Vec, } /// The document (uid, revision) and the settings a cached preview belongs to. @@ -132,24 +139,105 @@ struct Drained { ok: Option, settings: Value, sheet: usize, + /// The printer chosen (empty: the default printer or PDF File). + printer: String, } -/// The lists the rows offer that the app holds (the profiles, the flattener presets). +/// The lists the rows offer that the app holds (the profiles, the flattener presets, the printer's papers). #[derive(Default)] struct Lists { profiles: Vec, flatteners: Vec, + /// The Size choices: the printer's paper sizes, or the dialog's own papers when it offers none. + media: Vec<(String, String)>, } impl Lists { - fn of(app: &VectorcraftApp) -> Self { + fn of(app: &VectorcraftApp, papers: &[Paper], 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(), + media: media_choices(papers, media), } } } +/// The prefix of a Size choice that is one of the printer's own paper sizes (`printer:CR80`). +const PRINTER_PAPER: &str = "printer:"; + +/// The dialog's own papers, as (id, label). +fn own_media() -> Vec<(String, String)> { + Media::IDS.iter().zip(Media::LABELS).map(|(i, l)| (i.to_string(), tl!(*l).to_string())).collect() +} + +/// The Size choices for a printer whose driver offers `papers`, with `current` (the row's choice) kept when it is one of +/// 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)> { + let mut out = if papers.is_empty() { + own_media() + } else { + let mut out: Vec<(String, String)> = Vec::new(); + for p in papers { + let id = own_media_of(p).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string()); + if out.iter().all(|(i, _)| *i != id) { + out.push((id, p.label.clone())); + } + } + 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) { + // 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)); + } + out +} + +/// The dialog's own paper of the size of `p`, either way up, to within half a point. +fn own_media_of(p: &Paper) -> Option { + let (w, h) = (p.width.min(p.height), p.width.max(p.height)); + 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)) +} + +/// The printer's paper the Size row names (`printer:CR80`), when it is one of `papers`. +fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a Paper> { + let key = fields.text("media")?.strip_prefix(PRINTER_PAPER)?; + papers.iter().find(|p| p.key == key) +} + +/// The print settings of `fields`, with Width and Height at the size of the printer's paper the Size row names. +fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { + let mut out = settings(fields); + if let Some(paper) = printer_paper(fields, papers) { + out["width"] = json!(paper.width); + out["height"] = json!(paper.height); + } + out +} + +/// The paper sizes the driver of `printer` offers (none for preset editing, the default printer and PDF File). +fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str) -> (Vec, bool) { + if mode == PrintMode::PresetEditor || printer.is_empty() || printer == PDF_FILE { + return (Vec::new(), false); + } + match app.services.print.as_mut().map(|s| s.papers(printer)) { + Some(Papers::Ready(papers)) => (papers, false), + Some(Papers::Pending) => (Vec::new(), true), + None => (Vec::new(), false), + } +} + +/// The printer `destination` names, empty for none. +fn printer_of(destination: &Destination) -> String { + match destination { + Destination::Printer(name) => name.clone(), + _ => String::new(), + } +} + /// Open the Print dialog on the document's print settings and the system's default printer. pub fn open(app: &mut VectorcraftApp) -> Result { let st = app.session.active().ok_or("no document")?; @@ -207,7 +295,15 @@ fn start( let taken: Vec = taken_names(app); let named = editing.clone(); let driver = driver(has_setup(app), &state.settings.destination); - let mut hosted = HostedPrint::new(state, fields, sections(&Lists::of(app))) + let printer = printer_of(&state.settings.destination); + let (papers, papers_pending) = papers_of(app, mode, &printer); + if papers_pending { + ctx.request_repaint(); + } + let media = fields.text("media").map(str::to_string).unwrap_or_default(); + let lists = Lists::of(app, &papers, &media); + let media: Vec = lists.media.iter().map(|(i, _)| i.clone()).collect(); + let mut hosted = HostedPrint::new(state, fields, sections(&lists)) .mode(mode) .layout(PrintLayout::Sections) .driver(driver) @@ -220,7 +316,8 @@ fn start( hosted.set_json_field(&ctx, "name", json!(name))?; } let id = dialogs.with(|h| h.open(hosted)); - app.print_dialog.open = Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver }); + app.print_dialog.open = + Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver, papers: (printer, papers), papers_pending, media }); Ok(Value::Null) } @@ -320,6 +417,10 @@ pub(super) fn settings(fields: &DialogFields) -> Value { for k in NOT_SETTINGS { 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)) { + p.insert("media".into(), json!(Media::Custom.id())); + } Value::Object(nested(p)) } @@ -363,6 +464,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ok: p.take_ok(), settings: settings(p.fields_mut()), sheet: p.sheet_index(), + printer: printer_of(&p.state().settings.destination), } }) else { // Closed: its answer was acted on when the OK was held. @@ -372,6 +474,73 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, for event in std::mem::take(&mut d.events) { apply_preset_event(app, dialogs, open, &mut d.settings, event); } + // Another printer, or its driver's answer arriving: the Size list becomes the driver's paper sizes. A preset can + // choose a size the list lacks, so the Size row is read after the preset events and the list is made again to + // 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; + 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(); + if printer_changed || open.papers_pending { + // 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) + { + 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); + papers_changed = printer_changed || !pending; + open.papers = (d.printer.clone(), papers); + open.papers_pending = pending; + } + if open.papers_pending { + ctx.request_repaint(); + } + // A paper the new printer doesn't list becomes a custom size of the same Width and Height. + if papers_changed + && media.starts_with(PRINTER_PAPER) + && let Some(s) = on(dialogs, |p| { + let fields = p.fields_mut(); + if printer_paper(fields, &open.papers.1).is_some() { + return None; + } + if let Some(paper) = &chosen { + fields.set("width", paper.width); + fields.set("height", paper.height); + } + fields.set("media", Media::Custom.id()); + Some(settings(fields)) + }) + .flatten() + { + media = Media::Custom.id().to_string(); + d.settings = s; + } + if papers_changed || (!media.is_empty() && !open.media.contains(&media)) { + let lists = Lists::of(app, &open.papers.1, &media); + open.media = lists.media.iter().map(|(i, _)| i.clone()).collect(); + on(dialogs, |p| p.set_sections(sections(&lists))); + ctx.request_repaint(); + } + // One of the printer's papers: Width and Height hold its size, which is what prints. + let papers = &open.papers.1; + if let Some(s) = on(dialogs, |p| { + let fields = p.fields_mut(); + let paper = printer_paper(fields, papers)?; + let size = (fields.number("width"), fields.number("height")); + (size != (Some(paper.width), Some(paper.height))).then(|| { + fields.set("width", paper.width); + fields.set("height", paper.height); + settings(fields) + }) + }) + .flatten() + { + d.settings = s; + } if open.mode == PrintMode::Print { let same = serde_json::from_value::(d.settings.clone()) .ok() @@ -508,7 +677,9 @@ fn drags(moves: EditEvents) -> Vec<(f64, f64)> { /// Print, or Done: keep the settings with the document (one undo step when they changed), then print them; settings /// that can't print are refused, and the dialog stays open. The preset editor saves the preset under `name` instead. fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &str) -> Result<(), String> { - let settings = settings(&answer.fields); + // 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); if open.mode == PrintMode::PresetEditor { return save_preset(app, open, name, settings); } @@ -696,6 +867,7 @@ fn sections(lists: &Lists) -> Vec { let composite: Vec<&str> = OutputMode::IDS.iter().copied().filter(|i| *i != separations).collect(); let scaling_on: Vec<&str> = tiles.iter().copied().chain([PrintScaling::Custom.id()]).collect(); let counts: Vec = (2..=i64::from(vectorcraft_pdf::MAX_COPIES)).collect(); + let media = if lists.media.is_empty() { own_media() } else { lists.media.clone() }; let artboards = vec![ (PrintArtboards::All.id().to_string(), tl!("All").into()), (PrintArtboards::Range.id().to_string(), tl!("Range:").into()), @@ -712,7 +884,7 @@ fn sections(lists: &Lists) -> Vec { .under_option(PrintArtboards::Range.id()), flag("skipBlank", tl!("Skip Blank Artboards")).enabled_when_in("artboards", [PrintArtboards::All.id(), PrintArtboards::Range.id()]), Param::section(tl!("Media")), - pick::("media", tl!("Size:")), + 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"), Param::section(tl!("Orientation")), diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 183d6f1056..48002b08d8 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -1,14 +1,14 @@ //! File → Print: the Print dialog hosted on the window (Print and Done, the preview's drag), the //! print service it prints through (a mock here) and the PDF it saves without one. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use craft::print::ui::Printer; use serde_json::{Value, json}; use vectorcraft_engine::Session; -use crate::print::{PrintJob, PrintService}; +use crate::print::{Papers, PrintJob, PrintService}; use crate::{Services, VectorcraftApp}; /// What the mock service was sent: (printer, title, PDF). @@ -234,6 +234,240 @@ fn print_does_not_send_or_update_the_other_drawing() { assert!(!is_open(&app)); } +/// The printers the paper service was asked for, in order. +type Asked = Rc>>; + +/// Two printers: Office's driver lists no papers, and Card's lists US Letter and a CR80 card. +struct PaperPrint(Jobs, Asked); + +impl PrintService for PaperPrint { + fn printers(&mut self) -> Vec { + vec![Printer::new("Office").is_default(true), Printer::new("Card")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(self.0.clone()).print(job) + } + + fn papers(&mut self, printer: &str) -> 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![], + }) + } +} + +/// The driver returns its papers on the second test frame. +struct PendingPaperPrint(PaperPrint, Rc>); + +impl PrintService for PendingPaperPrint { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true)] + } + + fn print(&mut self, job: &PrintJob) -> Result { + self.0.print(job) + } + + fn papers(&mut self, printer: &str) -> Papers { + if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer) } + } +} + +#[test] +fn preset_editor_keeps_its_own_sizes_without_asking_the_default_printer() { + let asked = Asked::default(); + let service = PendingPaperPrint(PaperPrint(Jobs::default(), asked.clone()), Rc::new(Cell::new(2))); + let services = Services { print: Some(Box::new(service)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("ui.printPresetDialog", json!({})).unwrap(); + assert!(asked.borrow().is_empty()); + set(&mut app, "media", json!("a3")); + for _ in 0..2 { + pump(&mut app); + } + assert_eq!(fields(&app)["media"], "a3"); + assert!(asked.borrow().is_empty(), "preset editing never asks for printer paper sizes"); +} + +#[test] +fn pending_paper_sizes_arrive_on_a_later_frame() { + let asked = Asked::default(); + let frame = Rc::new(Cell::new(0)); + let service = PendingPaperPrint(PaperPrint(Jobs::default(), asked.clone()), frame.clone()); + let services = Services { print: Some(Box::new(service)), ..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(); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); + frame.set(1); + pump(&mut app); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); + set(&mut app, "media", json!("a3")); + frame.set(2); + pump(&mut app); + assert_eq!(fields(&app)["media"], "a3", "the chosen size survives discovery"); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_ok()); + pump(&mut app); + pump(&mut app); + assert_eq!(*asked.borrow(), ["Card"], "ready results are not polled again"); +} + +#[test] +fn the_media_sizes_follow_the_printer_chosen() { + let (jobs, asked) = (Jobs::default(), Asked::default()); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), asked.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); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err(), "Office's driver has no CR80 card"); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + // The card printer's Letter is the dialog's own Letter. + set(&mut app, "media", json!("letter")); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + let f = fields(&app); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); + let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap(); + assert_eq!(saved["media"], "custom", "the document keeps the card as its size"); + // Each printer's driver is asked once, when it is chosen. + assert_eq!(*asked.borrow(), ["Office", "Card"]); +} + +#[test] +fn switching_printers_keeps_an_unlisted_paper_as_a_custom_size() { + let services = Services { print: Some(Box::new(PaperPrint(Jobs::default(), Asked::default()))), ..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!("Card")); + pump(&mut app); + // The printer changes in the same frame as the card is chosen, before Width and Height take its size. + set(&mut app, "media", json!("printer:CR80")); + set(&mut app, "printer", json!("Office")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "custom"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); +} + +#[test] +fn confirming_after_switching_printers_keeps_the_selected_paper_size() { + let jobs = Jobs::default(); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), Asked::default()))), ..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!("Card")); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + set(&mut app, "printer", json!("Office")); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + assert_eq!(job.len(), 1); + assert_eq!(job[0].0.as_deref(), Some("Office")); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); +} + +#[test] +fn a_printer_paper_prints_at_its_size_and_a_preset_replaces_it() { + let jobs = Jobs::default(); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), Asked::default()))), ..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("print.presets.save", json!({"name": "Big", "settings": {"media": "custom", "width": 400, "height": 500}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + // A preset's own size replaces the card's. + set(&mut app, "preset", json!("Big")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!((f["media"].as_str(), f["width"].as_f64(), f["height"].as_f64()), (Some("custom"), Some(400.0), Some(500.0)), "{f}"); + // The card chosen and OK pressed before the dialog is served again still prints on the card. + set(&mut app, "media", json!("printer:CR80")); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); +} + +#[test] +fn a_preset_size_the_printer_does_not_list_stays_a_choice() { + let services = Services { print: Some(Box::new(PaperPrint(Jobs::default(), Asked::default()))), ..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("print.presets.save", json!({"name": "Tall", "settings": {"media": "a3"}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + assert!(try_set(&mut app, "media", json!("a3")).is_err(), "the card printer lists no A3"); + set(&mut app, "preset", json!("Tall")); + pump(&mut app); + pump(&mut app); + assert_eq!(fields(&app)["media"], "a3"); + // A3 is offered while it is chosen, so choosing another size and going back works. + set(&mut app, "media", json!("letter")); + set(&mut app, "media", json!("a3")); +} + +#[test] +fn a_ppd_lists_its_paper_dimensions_by_name() { + let ppd = "*OpenUI *PageSize/Media Size: PickOne\r\n\ + *PageSize Letter/US Letter: \"<>setpagedevice\"\r\n\ + *PageSize CR80/CR80 Card: \"<>setpagedevice\"\r\n\ + *CloseUI: *PageSize\r\n\ + *PaperDimension Letter: \"612 792\"\r\n\ + *PaperDimension CR80: \"153 243\"\r\n\ + *PaperDimension CR80: \"100 100\"\r\n\ + *PaperDimension Stamp/Stamp: \"20 20\"\r\n\ + *PaperDimension Bad: \"612\"\r\n\ + *PaperDimension Roll/Banner Roll: \"612 14400\"\r\n"; + let papers = crate::print::ppd_papers(ppd); + let got: Vec<(&str, &str, f64, f64)> = papers.iter().map(|p| (p.key.as_str(), p.label.as_str(), p.width, p.height)).collect(); + // The repeated CR80, a size below 72 pt and a line without a height are left out. + assert_eq!(got, [("Letter", "US Letter", 612.0, 792.0), ("CR80", "CR80 Card", 153.0, 243.0), ("Roll", "Banner Roll", 612.0, 14400.0)]); +} + +#[test] +fn windows_paper_sizes_are_read_in_hundredths_of_an_inch() { + let out = "1\tLetter\t850\t1100\r\n\ + 256\tCard\t213\t338\r\n\ + 256\tBanner\t850\t2000\r\n\ + 256\t\t213\t338\r\nbroken line\r\n9\tTiny\t10\t10\r\n"; + let papers = crate::print::windows_papers(out); + let got: Vec<(&str, &str, f64, f64)> = papers.iter().map(|p| (p.key.as_str(), p.label.as_str(), p.width, p.height)).collect(); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!((got[0].0, got[0].1), ("Letter", "Letter")); + assert!((got[0].2 - 612.0).abs() < 1e-9 && (got[0].3 - 792.0).abs() < 1e-9); + assert_eq!((got[1].0, got[1].1), ("Card", "Card")); + assert_eq!((got[2].0, got[2].1), ("Banner", "Banner")); + assert_eq!((got[3].0, got[3].1), ("256", "256"), "no name: the number"); +} + /// 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/print.rs b/crates/ui-egui/src/print.rs index 863c94673d..7989474924 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -52,6 +52,95 @@ pub trait PrintService { fn setup(&mut self, _printer: Option<&str>) -> Result<(), String> { Err("there are no printer settings to open here".into()) } + /// The driver's paper sizes, in its order, without waiting for a program. The dialog polls + /// pending lookups and offers its own sizes until the driver returns a nonempty list. + fn papers(&mut self, _printer: &str) -> Papers { + Papers::Ready(Vec::new()) + } +} + +/// 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), + /// Poll again on a later frame. + Pending, +} + +/// A paper size a printer's driver offers. +#[derive(Clone, Debug, PartialEq)] +pub struct Paper { + /// The driver's keyword for it (`Letter`, `CR80`), or its form name on Windows (the number when unnamed). + pub key: String, + /// What the driver calls it (`US Letter`); the keyword when it gives no name. + pub label: String, + /// Width in points. + pub width: f64, + /// Height in points. + pub height: f64, +} + +/// Most sizes kept from one driver; a PPD is a text file from the printer vendor. +const MAX_PAPERS: usize = 400; +/// Longest paper label kept, in characters. +const MAX_PAPER_LABEL: usize = 128; +/// The smallest and largest paper side the print settings take (`media: custom`), in points. +const PAPER_SIDE: std::ops::RangeInclusive = 72.0..=14400.0; + +/// `paper`, unless the list is full, its key is taken or a side is outside 72–14400 pt. +fn push_paper(papers: &mut Vec, paper: Paper) { + let fits = PAPER_SIDE.contains(&paper.width) && PAPER_SIDE.contains(&paper.height); + if fits && papers.len() < MAX_PAPERS && papers.iter().all(|p| p.key != paper.key) { + papers.push(Paper { label: paper.label.chars().take(MAX_PAPER_LABEL).collect(), ..paper }); + } +} + +/// The paper sizes of a PPD: each `*PaperDimension` entry (`*PaperDimension CR80/CR80 Card: "153 243"`), named by +/// its own label or else by the `*PageSize` entry with the same keyword. Sizes outside 72–14400 pt, repeated keywords +/// and malformed lines are skipped. +pub fn ppd_papers(ppd: &str) -> Vec { + fn entry<'a>(line: &'a str, key: &str) -> Option<(&'a str, &'a str, &'a str)> { + let rest = line.strip_prefix('*')?.strip_prefix(key)?.strip_prefix(' ')?; + let (head, value) = rest.split_once(':')?; + let (name, label) = head.split_once('/').map_or((head.trim(), ""), |(n, l)| (n.trim(), l.trim())); + (!name.is_empty() && !name.contains(char::is_whitespace)).then_some((name, label, value.trim())) + } + let mut labels: Vec<(&str, &str)> = Vec::new(); + let mut papers: Vec = Vec::new(); + for line in ppd.lines().map(|l| l.trim_end_matches('\r')) { + if let Some((name, label, _)) = entry(line, "PageSize") { + if !label.is_empty() && labels.len() < MAX_PAPERS { + labels.push((name, label)); + } + } else if let Some((name, label, value)) = entry(line, "PaperDimension") { + let mut nums = value.trim_matches('"').split_whitespace().map(str::parse::); + let (Some(Ok(width)), Some(Ok(height)), None) = (nums.next(), nums.next(), nums.next()) else { continue }; + push_paper(&mut papers, Paper { key: name.into(), label: label.into(), width, height }); + } + } + for p in &mut papers { + if p.label.is_empty() { + let label = labels.iter().find(|(n, _)| *n == p.key).map_or(p.key.as_str(), |(_, l)| l); + p.label = label.chars().take(MAX_PAPER_LABEL).collect(); + } + } + papers +} + +/// The paper sizes in tab-separated lines of number, name, width and height (hundredths of an inch), as Windows' +/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_papers`] apply. +pub fn windows_papers(out: &str) -> Vec { + let mut papers: Vec = Vec::new(); + for line in out.lines() { + let fields: Vec<&str> = line.trim_end_matches('\r').split('\t').map(str::trim).collect(); + let [key, label, w, h] = fields[..] else { continue }; + let (Ok(w), Ok(h)) = (w.parse::(), h.parse::()) else { continue }; + if !key.is_empty() { + let label = if label.is_empty() { key } else { label }; + push_paper(&mut papers, Paper { key: label.into(), label: label.into(), width: w * 0.72, height: h * 0.72 }); + } + } + papers } /// `print.printers`: the system's printers, and what the print service offers.