From 4c883f94ccbba24d177a4cd9e2cd5e6ea82c8dd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 16:28:48 -0800 Subject: [PATCH 1/5] 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. From c33f0cfa133d170df1bdd533a19704643a212038 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 18:06:39 -0800 Subject: [PATCH 2/5] Print: each printer choice reads the driver's paper sizes again A lookup that was still running when the person chose another printer stayed in the service, and choosing that printer again returned its old answer without reading the driver. Reopening the dialog on a printer whose lookup was still running did the same. `PrintService::papers` now takes `fresh`, which the dialog sets when it opens and when the printer changes. The desktop service keeps one lookup in flight and replaces it on a fresh call or a call for another printer, so an earlier answer is dropped. --- apps/vectorcraft/src/printing.rs | 87 +++++++++++++++++++---- crates/ui-egui/src/dialogs/print.rs | 11 +-- crates/ui-egui/src/dialogs/tests_print.rs | 46 +++++++++++- crates/ui-egui/src/print.rs | 4 +- 4 files changed, 126 insertions(+), 22 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 9e64fcc75c..e7f5db9a69 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -7,8 +7,8 @@ mod direct_pdf; #[derive(Default)] pub struct SystemPrint { - /// Channels for pending paper-size lookups, removed when each worker answers or disconnects. - papers: std::collections::HashMap>>, + /// The paper-size lookup in flight, dropped when its worker answers or disconnects. + papers: PaperLookup, } impl PrintService for SystemPrint { @@ -36,21 +36,33 @@ impl PrintService for SystemPrint { fn scripts_may_print(&self) -> bool { true } - fn papers(&mut self, printer: &str) -> Papers { - let receive = self.papers.entry(printer.to_string()).or_insert_with(|| { + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + self.papers.poll(printer, fresh, |printer| installed_papers(&printer)) + } +} + +/// The paper-size lookup in flight: the printer it reads and its worker's channel. +#[derive(Default)] +struct PaperLookup(Option<(String, std::sync::mpsc::Receiver>)>); + +impl PaperLookup { + /// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight + /// reads another printer, or when none is in flight; the earlier one's answer is dropped. + fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec + Send + 'static) -> Papers { + if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) { let (send, receive) = std::sync::mpsc::channel(); - let printer = printer.to_string(); + let name = printer.to_string(); let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { - let _ = send.send(installed_papers(&printer)); + let _ = send.send(read(name)); }); - 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.0 = Some((printer.to_string(), receive)); + } + let result = match self.0.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()), }; - self.papers.remove(printer); + self.0 = None; result } } @@ -233,6 +245,55 @@ mod tests { } } +#[cfg(test)] +mod paper_lookup_tests { + use super::PaperLookup; + use vectorcraft_ui_egui::print::{Paper, Papers}; + + fn paper(key: &str) -> Vec { + vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }] + } + + /// 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 { + let mut polled = lookup.poll(printer, true, move |_| paper(key)); + loop { + match polled { + Papers::Ready(papers) => return papers, + Papers::Pending => std::thread::yield_now(), + } + polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup")); + } + } + + /// A read that answers `key` once `gate` lets it. + fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> Vec + Send + 'static) { + let (open, gate) = std::sync::mpsc::channel::<()>(); + (open, move |_| { + let _ = gate.recv(); + paper(key) + }) + } + + #[test] + fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() { + let mut lookup = PaperLookup::default(); + let (open, read) = gated("Old"); + assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + let (other, read) = gated("Office"); + assert!(matches!(lookup.poll("Office", true, read), Papers::Pending)); + let _ = open.send(()); + let _ = other.send(()); + // Back on the card printer. + assert_eq!(answer(&mut lookup, "Card", "New"), paper("New")); + // 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, read), Papers::Pending)); + let _ = open.send(()); + assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer")); + } +} + #[cfg(test)] mod turn_tests { use super::sent; diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 3021537994..6828d54559 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -218,12 +218,13 @@ fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { 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) { +/// 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) { 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)) { + 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), @@ -296,7 +297,7 @@ fn start( let named = editing.clone(); let driver = driver(has_setup(app), &state.settings.destination); let printer = printer_of(&state.settings.destination); - let (papers, papers_pending) = papers_of(app, mode, &printer); + let (papers, papers_pending) = papers_of(app, mode, &printer, true); if papers_pending { ctx.request_repaint(); } @@ -491,7 +492,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, answer.fields.set("height", paper.height); answer.fields.set("media", Media::Custom.id()); } - let (papers, pending) = papers_of(app, open.mode, &d.printer); + let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); papers_changed = printer_changed || !pending; open.papers = (d.printer.clone(), papers); open.papers_pending = pending; diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 48002b08d8..c52e5782da 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -249,7 +249,7 @@ impl PrintService for PaperPrint { MockPrint(self.0.clone()).print(job) } - fn papers(&mut self, printer: &str) -> Papers { + 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 { @@ -271,11 +271,51 @@ impl PrintService for PendingPaperPrint { self.0.print(job) } - fn papers(&mut self, printer: &str) -> Papers { - if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer) } + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer, fresh) } } } +/// The lookups the dialog asked for, as (printer, fresh). +type Lookups = Rc>>; + +/// Two printers whose drivers never answer. +struct SlowPaperPrint(Jobs, Lookups); + +impl PrintService for SlowPaperPrint { + 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, fresh: bool) -> Papers { + self.1.borrow_mut().push((printer.to_string(), fresh)); + Papers::Pending + } +} + +#[test] +fn choosing_a_printer_again_starts_a_new_paper_lookup() { + let lookups = Lookups::default(); + let services = Services { print: Some(Box::new(SlowPaperPrint(Jobs::default(), lookups.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, "printer", json!("Card")); + pump(&mut app); + set(&mut app, "printer", json!("Office")); + pump(&mut app); + pump(&mut app); + let log = lookups.borrow(); + let fresh: Vec<&str> = log.iter().filter(|(_, f)| *f).map(|(p, _)| p.as_str()).collect(); + assert_eq!(fresh, ["Office", "Card", "Office"], "the opening and each printer change start a lookup: {log:?}"); + assert_eq!(log.last(), Some(&("Office".to_string(), false)), "later frames poll the lookup in flight: {log:?}"); +} + #[test] fn preset_editor_keeps_its_own_sizes_without_asking_the_default_printer() { let asked = Asked::default(); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index d6c7794912..0451cb5b5c 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -65,7 +65,9 @@ pub trait PrintService { } /// 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 { + /// `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()) } } From f251709e54caee8253c339a0bb839a462ea4fd1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:24:47 -0800 Subject: [PATCH 3/5] Print: a paper keyword at another size on the new printer becomes Custom Paper keywords belong to each printer's driver. When the printer changes and the new driver lists the chosen keyword at a different size, the Size row now keeps the previous Width and Height as a Custom size instead of taking the new printer's dimensions. A keyword listed at the same size stays chosen. --- crates/ui-egui/src/dialogs/print.rs | 10 ++++-- crates/ui-egui/src/dialogs/tests_print.rs | 41 +++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6828d54559..314e2bc032 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -208,6 +208,11 @@ fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a P papers.iter().find(|p| p.key == key) } +/// 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 +} + /// 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); @@ -500,12 +505,13 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, 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. + // A paper the new printer doesn't list, or lists under the same keyword at another size, 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() { + if printer_paper(fields, &open.papers.1).is_some_and(|new| chosen.as_ref().is_none_or(|old| same_size(old, new))) { return None; } if let Some(paper) = &chosen { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index c52e5782da..10ec8a5a70 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -403,6 +403,47 @@ fn switching_printers_keeps_an_unlisted_paper_as_a_custom_size() { assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); } +/// Three card printers: Card and Twin list a CR80 card at 153 × 243 points, and Badge lists a CR80 at 200 × 300. +struct CardPrinters; + +impl PrintService for CardPrinters { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true), Printer::new("Twin"), Printer::new("Badge")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + 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 }]) + } +} + +#[test] +fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() { + let services = Services { print: Some(Box::new(CardPrinters)), ..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); + // Twin's CR80 is the same size, so it stays chosen. + set(&mut app, "printer", json!("Twin")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + // Badge's CR80 is another size: the card keeps its size as a custom size. + set(&mut app, "printer", json!("Badge")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "custom", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); +} + #[test] fn confirming_after_switching_printers_keeps_the_selected_paper_size() { let jobs = Jobs::default(); From 8fa6a542077a803d45560050d99000ea47997cf9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:10:19 -0800 Subject: [PATCH 4/5] Print: a paper keeps its size while a printer is looked up and in a new preset While the newly chosen printer's driver has not answered, the Size list keeps the previous printer's sizes, so a printer paper stays chosen at its size. It becomes Custom only when the answer lists it at another size or not at all. A preset created in the same pass as a printer paper is chosen now saves that paper's Width and Height, the size the dialog shows, instead of the size before it. --- crates/ui-egui/src/dialogs/print.rs | 16 ++++-- crates/ui-egui/src/dialogs/tests_print.rs | 65 +++++++++++++++++++++++ 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 314e2bc032..8ec1176cfa 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -112,7 +112,8 @@ 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. + /// 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), /// Whether the chosen printer still has a lookup running. papers_pending: bool, @@ -498,8 +499,13 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, answer.fields.set("media", Media::Custom.id()); } let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); - papers_changed = printer_changed || !pending; - open.papers = (d.printer.clone(), papers); + // 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; + open.papers.0 = d.printer.clone(); + if !pending { + open.papers.1 = papers; + } open.papers_pending = pending; } if open.papers_pending { @@ -654,7 +660,9 @@ fn apply_preset_event(app: &mut VectorcraftApp, dialogs: &WindowDialogs, open: & } } NamedPresetEvent::Create { name, .. } => { - match app.run("print.presets.save", json!({ "name": name, "preset": DEFAULT_PRESET, "settings": settings })) { + // 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()); + 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), } diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 10ec8a5a70..f325276084 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -444,6 +444,71 @@ fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); } +/// Card lists a CR80 card; Twin's driver answers with the same CR80 once `ready` is set. +struct PendingTwin(Rc>); + +impl PrintService for PendingTwin { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true), Printer::new("Twin")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + if printer == "Twin" && !self.0.get() { Papers::Pending } else { CardPrinters.papers(printer, fresh) } + } +} + +#[test] +fn a_paper_stays_chosen_while_the_new_printer_looks_up_its_sizes() { + let ready = Rc::new(Cell::new(false)); + let services = Services { print: Some(Box::new(PendingTwin(ready.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); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "Twin's driver has not answered yet: {f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + // Twin lists the same CR80, so it stays chosen. + ready.set(true); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); +} + +#[test] +fn a_preset_saved_as_a_printer_paper_is_chosen_keeps_its_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); + press(&mut app, "New…"); + pump(&mut app); + call(&mut app, "ui.text", json!({"text": "Cards"})); + // The card is chosen in the frame the name is confirmed, before Width and Height take its size. + let ctx = ctx(&app); + let (enter, _reply) = craft::automation::ControlRequest::new("ui.key", json!({"key": "Enter"})); + let _ = crate::control::handle(&mut app, &ctx, &enter); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + pump(&mut app); + let saved = app.session.prefs.print_presets.iter().find(|p| p.name == "Cards").expect("the preset was saved").settings.clone(); + assert_eq!((saved.media, saved.width, saved.height), (vectorcraft_pdf::Media::Custom, 153.0, 243.0)); +} + #[test] fn confirming_after_switching_printers_keeps_the_selected_paper_size() { let jobs = Jobs::default(); From d54e2cf55b2a8d6497ec0e0efe1d90e520b4b9b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:04:15 -0800 Subject: [PATCH 5/5] Print: a kept paper the new printer lists at a built-in size becomes that size When the new printer listed the chosen paper at a size within half a point of one of the dialog's own papers, the Size row kept the `printer:` choice, but the new Size list offers that paper under the built-in id instead. The row then held a choice the list did not contain, and the list was rebuilt and repainted on every frame. The row now switches to the built-in paper the list offers. --- crates/ui-egui/src/dialogs/print.rs | 17 +++++++---- crates/ui-egui/src/dialogs/tests_print.rs | 36 +++++++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 8ec1176cfa..6546b2ff5b 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -512,24 +512,29 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ctx.request_repaint(); } // A paper the new printer doesn't list, or lists under the same keyword at another size, becomes a custom size of - // the same Width and Height. + // the same Width and Height. One the new printer lists at the size of one of the dialog's own papers becomes that + // paper, the choice the new list offers for it. if papers_changed && media.starts_with(PRINTER_PAPER) - && let Some(s) = on(dialogs, |p| { + && let Some((id, s)) = on(dialogs, |p| { let fields = p.fields_mut(); - if printer_paper(fields, &open.papers.1).is_some_and(|new| chosen.as_ref().is_none_or(|old| same_size(old, new))) { - return None; + if let Some(new) = printer_paper(fields, &open.papers.1) + && chosen.as_ref().is_none_or(|old| same_size(old, new)) + { + let own = own_media_of(new)?; + fields.set("media", own.id()); + return Some((own.id().to_string(), settings(fields))); } if let Some(paper) = &chosen { fields.set("width", paper.width); fields.set("height", paper.height); } fields.set("media", Media::Custom.id()); - Some(settings(fields)) + Some((Media::Custom.id().to_string(), settings(fields))) }) .flatten() { - media = Media::Custom.id().to_string(); + media = id; d.settings = s; } if papers_changed || (!media.is_empty() && !open.media.contains(&media)) { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index f325276084..d2ebf74122 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -444,6 +444,42 @@ fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); } +/// Two printers list a paper named Wide: Near at 611.2 × 792 points, Far at 611.6 × 792, within half a point of Letter. +struct NearLetter; + +impl PrintService for NearLetter { + fn printers(&mut self) -> Vec { + vec![Printer::new("Near").is_default(true), Printer::new("Far")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + 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 }]) + } +} + +#[test] +fn a_kept_paper_the_new_printer_lists_at_a_built_in_size_becomes_that_size() { + let services = Services { print: Some(Box::new(NearLetter)), ..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:Wide")); + pump(&mut app); + // Far's Wide is within half a point of Near's and of Letter, and its Size list offers it as Letter. + set(&mut app, "printer", json!("Far")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "letter", "{f}"); + assert!(try_set(&mut app, "media", json!("printer:Wide")).is_err(), "the Size list offers Letter in its place"); +} + /// Card lists a CR80 card; Twin's driver answers with the same CR80 once `ready` is set. struct PendingTwin(Rc>);