From c7965ebf52bc245d100697bb944981d85e34fecd Mon Sep 17 00:00:00 2001 From: Aldo Zarate Date: Sun, 11 Oct 2026 20:46:50 -0600 Subject: [PATCH] Plot to system printers on macOS and Linux through CUPS (#670 step 2) The CUPS destinations (`lpstat -e`) are devices next to the built-in ones, each with the papers and printable areas of its PPD (PageSize, PaperDimension, ImageableArea, DefaultPageSize). PLOT to one renders the PDF the PDF plotter writes for that paper and sends it to `lp` with the paper's PageSize, the copies, and no scaling (the plot's scale is already applied); the reply is the job id. EXPORTPDF to a printer still writes the PDF. - doc: PlotterConfig.system (never read from or written to files). - engine: SystemPrinters host hook (list, print), listed after the built-in devices and cached for a few seconds; plot_options adds `printer` and the paper for PLOT; run_plot prints when `printer` is given (`copies` 1..999). - io: cups.rs with the PPD / lpstat / lp parsers (tested on text) and, on Unix, the commands. - app: installs CUPS printers on Unix. - ui: the Plot dialog prints straight to a printer (no file dialog) with a Number of copies field. Co-Authored-By: Claude Opus 5.5 --- apps/cadcraft/src/main.rs | 6 + crates/doc/src/plotter.rs | 5 + crates/engine/src/cmd/layout.rs | 16 +- crates/engine/src/cmd/plotters.rs | 81 ++++++- crates/engine/tests/system_printers.rs | 77 +++++++ crates/io/src/cups.rs | 287 +++++++++++++++++++++++++ crates/io/src/lib.rs | 1 + crates/ui-egui/src/managers.rs | 20 +- 8 files changed, 487 insertions(+), 6 deletions(-) create mode 100644 crates/engine/tests/system_printers.rs create mode 100644 crates/io/src/cups.rs diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index 43f6b7607..7fbf6380b 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -115,6 +115,12 @@ pub fn install_io() { cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); + // System printers: CUPS on macOS and Linux. + #[cfg(unix)] + cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters { + list: cadcraft_io::cups::printers, + print: |j| cadcraft_io::cups::print(j.printer, j.paper, j.copies, j.title, j.pdf), + }); } fn services() -> Services { diff --git a/crates/doc/src/plotter.rs b/crates/doc/src/plotter.rs index abcdb9903..81b12ab8a 100644 --- a/crates/doc/src/plotter.rs +++ b/crates/doc/src/plotter.rs @@ -113,6 +113,10 @@ pub struct PlotterConfig { /// Name of the paper chosen when a page setup switches to this device. pub default_paper: String, pub papers: Vec, + /// A printer of the operating system (listed by the host, never read from or written to a + /// file): a plot to it is a PDF the host prints rather than a file. + #[serde(skip)] + pub system: bool, } impl Default for PlotterConfig { @@ -125,6 +129,7 @@ impl Default for PlotterConfig { orientation: Orientation::Landscape, default_paper: String::new(), papers: Vec::new(), + system: false, } } } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index c4acffab9..4e9c74de5 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -80,7 +80,7 @@ pub fn specs() -> Vec { .menu(&["File", "Print..."]) .key("Cmd+P") .alias(&["print"]) - .params("{path? (else returns base64 `data`), layout?: current|\"Model\", paper?, landscape?, fit?: bool, scale?: number | \"1:50\", lineweights?: bool, plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)") + .params("{path? (else returns base64 `data`), device?: plotter or system printer (then printed, `copies`?: 1..999, and the reply is the `job`), layout?: current|\"Model\", paper?, landscape?, fit?: bool, scale?: number | \"1:50\", lineweights?: bool, plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)") .noundo(), CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf")) .menu(&["File", "Export to PDF..."]) @@ -773,8 +773,13 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { Some(n) => Space::Paper(layout_name(cmd, s.doc()?, n)?), None => s.space(), }; + let printer = str_param(p, "printer").map(str::trim).filter(|n| !n.is_empty()); let mut opts = if p.is_object() { p.clone() } else { json!({}) }; if let Some(o) = opts.as_object_mut() { + // A printer takes the PDF. + if printer.is_some() { + o.insert("output".into(), json!("pdf")); + } if let Some(v) = p.get("scale") { let k = parse_scale(v).ok_or_else(|| bad(cmd, "`scale` must be positive: paper units per drawing unit, or a ratio such as \"1:50\""))?; o.insert("scale".into(), json!(k)); @@ -790,6 +795,15 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result { (None, Space::Paper(n)) => n.clone(), }; let pages = sheets.as_ref().map_or(1, Vec::len); + if let Some(printer) = printer { + let copies = p.get("copies").and_then(Value::as_u64).unwrap_or(1); + let title = format!("{} - {layout}", s.state()?.title); + let paper = str_param(p, "printerPaper").or_else(|| str_param(p, "paper")).unwrap_or_default(); + let job = super::plotters::print_pdf(cmd, printer, paper, copies, &title, &bytes)?; + return Ok( + json!({ "printer": printer, "job": job, "copies": copies.clamp(1, super::plotters::MAX_COPIES), "bytes": bytes.len(), "layout": layout, "pages": pages }), + ); + } match str_param(p, "path") { Some(_path) => { #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/cmd/plotters.rs b/crates/engine/src/cmd/plotters.rs index a682728c5..56ed8c3dd 100644 --- a/crates/engine/src/cmd/plotters.rs +++ b/crates/engine/src/cmd/plotters.rs @@ -132,6 +132,69 @@ fn store() -> PlotterStore { }) } +/// A plot for a system printer: the PDF the PDF plotter wrote, and how to print it. +pub struct PrintJob<'a> { + pub printer: &'a str, + /// The paper's name as the printer's device lists it. + pub paper: &'a str, + pub copies: u32, + pub title: &'a str, + pub pdf: &'a [u8], +} + +/// The host's printers: `list` gives them as devices (`system` set), `print` sends a job and +/// returns its id. +#[derive(Clone, Copy)] +pub struct SystemPrinters { + pub list: fn() -> Vec, + pub print: fn(&PrintJob) -> std::result::Result, +} + +static PRINTERS: OnceLock = OnceLock::new(); + +/// Install the host's printers (first call wins). Without them only files are plotted. +pub fn set_system_printers(p: SystemPrinters) { + let _ = PRINTERS.set(p); +} + +/// Most copies of one print job. +pub const MAX_COPIES: u64 = 999; + +/// The system printers, listed again at most every few seconds (listing asks the system). +fn system_printers() -> Vec { + let Some(h) = PRINTERS.get() else { return Vec::new() }; + #[cfg(not(target_arch = "wasm32"))] + { + use std::time::{Duration, Instant}; + type Cached = Option<(Instant, Vec)>; + static CACHE: Mutex = Mutex::new(None); + const TTL: Duration = Duration::from_secs(5); + let mut c = CACHE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some((at, list)) = c.as_ref() + && at.elapsed() < TTL + { + return list.clone(); + } + let list: Vec = (h.list)().into_iter().filter(|p| p.system && !is_builtin(&p.name)).collect(); + *c = Some((Instant::now(), list.clone())); + list + } + #[cfg(target_arch = "wasm32")] + { + (h.list)().into_iter().filter(|p| p.system && !is_builtin(&p.name)).collect() + } +} + +/// Print `pdf` on the system printer `printer`; returns the job id. +pub(crate) fn print_pdf(cmd: &str, printer: &str, paper: &str, copies: u64, title: &str, pdf: &[u8]) -> Result { + let h = PRINTERS.get().ok_or_else(|| bad(cmd, "there are no system printers in this build"))?; + let Some(dev) = system_printers().into_iter().find(|p| p.name.eq_ignore_ascii_case(printer.trim())) else { + return Err(bad(cmd, format!("unknown printer `{printer}`"))); + }; + let copies = copies.clamp(1, MAX_COPIES) as u32; + (h.print)(&PrintJob { printer: &dev.name, paper, copies, title, pdf }).map_err(|e| bad(cmd, format!("{}: {e}", dev.name))) +} + /// Most user devices listed. const MAX_DEVICES: usize = 1000; @@ -159,6 +222,7 @@ fn builtin(name: &str, output: PlotOutput, description: &str) -> PlotterConfig { orientation: Orientation::Landscape, default_paper, papers, + system: false, } } @@ -185,10 +249,13 @@ fn user_devices() -> Vec { out } -/// Every device: the built-in ones first, then the user's. +/// Every device: the built-in ones first, then the system printers, then the user's. pub fn devices() -> Vec { let mut v = builtins(); - v.extend(user_devices()); + let printers = system_printers(); + v.extend(user_devices().into_iter().filter(|u| !printers.iter().any(|p| p.name.eq_ignore_ascii_case(&u.name)))); + let at = BUILTIN.len(); + v.splice(at..at, printers); v } @@ -207,6 +274,9 @@ pub fn find_device(name: &str) -> Option { if let Some((b, o, d)) = BUILTIN.iter().find(|(b, _, _)| b.eq_ignore_ascii_case(n)) { return Some(builtin(b, *o, d)); } + if let Some(p) = system_printers().into_iter().find(|p| p.name.eq_ignore_ascii_case(n)) { + return Some(p); + } let st = store(); let direct = cadcraft_doc::plotter_file_name(n).and_then(|f| PlotterConfig::from_file_text(&(st.read)(&f).ok()?).ok()); direct.filter(|c| c.name.eq_ignore_ascii_case(n)).or_else(|| user_devices().into_iter().find(|c| c.name.eq_ignore_ascii_case(n))) @@ -314,6 +384,13 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result { None if layout.is_none() => dev.default_paper(), None => None, }; + // A system printer gets the plotter's PDF, on the paper by its name on that printer + // (EXPORTPDF still writes the PDF). + if dev.system && cmd == "plot" { + o.insert("printer".into(), json!(dev.name)); + let on = paper.map(|pp| pp.name.clone()).or_else(|| layout.as_ref().map(|pg| pg.paper.clone())).unwrap_or_default(); + o.insert("printerPaper".into(), json!(on)); + } if let Some(pp) = paper { o.remove("paper"); o.insert("width".into(), json!(pp.width)); diff --git a/crates/engine/tests/system_printers.rs b/crates/engine/tests/system_printers.rs new file mode 100644 index 000000000..ecee727e9 --- /dev/null +++ b/crates/engine/tests/system_printers.rs @@ -0,0 +1,77 @@ +//! System printers (#670 step 2): the host lists them as devices, and PLOT to one sends the +//! plotter's PDF to the host instead of returning a file. + +use std::sync::Mutex; + +use cadcraft_doc::{DevicePaper, Drawing, PlotterConfig, Space}; +use cadcraft_engine::Session; +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, set_plotter_store, set_system_printers}; +use serde_json::{Value, json}; + +/// The jobs printed: printer, paper, copies, title, the options the plot hook got. +static JOBS: Mutex> = Mutex::new(Vec::new()); + +fn echo_plot(_: &Drawing, _: &Space, opts: &Value) -> Result, String> { + Ok(opts.to_string().into_bytes()) +} + +fn printers() -> Vec { + vec![PlotterConfig { + name: "Office_T120".into(), + description: "HP DesignJet T120".into(), + default_paper: "Letter".into(), + papers: vec![ + DevicePaper { name: "Letter".into(), width: 215.9, height: 279.4, margins: [5.0; 4] }, + DevicePaper { name: "Roll 24 in".into(), width: 609.6, height: 914.4, margins: [5.0; 4] }, + ], + system: true, + ..PlotterConfig::default() + }] +} + +fn print(j: &PrintJob) -> Result { + let opts = serde_json::from_slice(j.pdf).map_err(|e| e.to_string())?; + JOBS.lock().unwrap().push((j.printer.into(), j.paper.into(), j.copies, j.title.into(), opts)); + Ok(format!("{}-7", j.printer)) +} + +fn session() -> Session { + set_plotter_store(PlotterStore::memory()); + set_system_printers(SystemPrinters { list: printers, print }); + set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Err("no writer in this test".into()), plot: Some(echo_plot) }); + let mut s = Session::new(); + s.cmdline("line 0,0 100,0").unwrap(); + s.cmdline("").unwrap(); + s +} + +#[test] +fn system_printers_are_devices_and_plot_prints_on_them() { + let mut s = session(); + let r = s.execute("plottermanager", &json!({})).unwrap(); + let names: Vec<&str> = r["devices"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["CADCraft PDF", "CADCraft PNG", "CADCraft SVG", "Office_T120"]); + + let r = s.execute("plot", &json!({ "layout": "Model", "device": "office_t120", "paper": "Roll 24 in", "copies": 2 })).unwrap(); + assert_eq!(r["job"], "Office_T120-7"); + assert_eq!(r["copies"], 2); + assert!(r.get("data").is_none()); + let (printer, paper, copies, title, opts) = JOBS.lock().unwrap().pop().unwrap(); + assert_eq!((printer.as_str(), paper.as_str(), copies), ("Office_T120", "Roll 24 in", 2)); + assert!(title.ends_with(" - Model"), "{title}"); + // The plotter wrote a PDF on the printer's paper. + assert_eq!(opts["output"], "pdf"); + assert_eq!(opts["width"], 609.6); + + // EXPORTPDF to the same device still returns the PDF. + let r = s.execute("exportpdf", &json!({ "layout": "Model", "device": "Office_T120" })).unwrap(); + assert!(r.get("data").is_some() && r.get("job").is_none()); + assert!(JOBS.lock().unwrap().is_empty()); + + // An unknown printer is refused, and copies are bounded. + assert!(s.execute("plot", &json!({ "layout": "Model", "printer": "Nope" })).is_err()); + let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "copies": 100000 })).unwrap(); + assert_eq!(r["copies"], 999); + assert_eq!(JOBS.lock().unwrap().pop().unwrap().2, 999); +} diff --git a/crates/io/src/cups.rs b/crates/io/src/cups.rs new file mode 100644 index 000000000..67774ce34 --- /dev/null +++ b/crates/io/src/cups.rs @@ -0,0 +1,287 @@ +//! System printers through CUPS (macOS and Linux): the destinations `lpstat` lists, each with +//! the papers and printable areas of its PPD, and printing a plot's PDF with `lp`. +//! +//! The PDF is the one the PDF plotter writes for the chosen paper, so it is sent unscaled: the +//! plot's scale is already applied. The parsers take text, so they are tested without a printer. + +use cadcraft_doc::{DevicePaper, Orientation, PlotOutput, PlotterConfig}; + +/// Most destinations listed. +const MAX_PRINTERS: usize = 64; +/// Largest PPD file read (bytes). +const MAX_PPD: u64 = 4 << 20; +/// Most copies of one job. +pub const MAX_COPIES: u32 = 999; +/// PostScript points per millimetre. +const PT_PER_MM: f64 = 72.0 / 25.4; + +/// A paper size of a PPD: its option keyword, the name shown, size and printable area (points). +#[derive(Clone, Debug, PartialEq)] +pub struct PpdPaper { + pub keyword: String, + pub name: String, + pub width: f64, + pub height: f64, + /// Printable area: lower-left x, y and upper-right x, y (points). + pub imageable: Option<[f64; 4]>, +} + +/// What a PPD says about a printer's papers. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Ppd { + pub nick_name: String, + /// The default paper's keyword. + pub default_size: String, + pub papers: Vec, +} + +/// A PPD main keyword line: `*Key Option/Label: Value` → (key, option, label, value). +fn ppd_line(line: &str) -> Option<(&str, &str, &str, &str)> { + let rest = line.strip_prefix('*')?; + let (head, value) = rest.split_once(':')?; + let (key, option) = head.split_once(' ').unwrap_or((head, "")); + let (option, label) = option.split_once('/').unwrap_or((option, "")); + Some((key.trim(), option.trim(), label.trim(), value.trim().trim_matches('"').trim())) +} + +fn numbers(s: &str) -> Option<[f64; N]> { + let v: Vec = s.split_whitespace().filter_map(|t| t.parse().ok()).filter(|x: &f64| x.is_finite()).collect(); + v.try_into().ok() +} + +/// The name a paper is shown with: its label, else its keyword; a borderless variant +/// (`Letter.Fullbleed`) says so. +fn paper_name(keyword: &str, label: &str) -> String { + let (base, borderless) = match keyword.strip_suffix(".Fullbleed") { + Some(b) => (b, true), + None => (keyword, false), + }; + let shown = if label.is_empty() { base } else { label.trim_end_matches(" (Borderless)").trim_end_matches(" Borderless") }; + if borderless { format!("{shown} (borderless)") } else { shown.to_string() } +} + +/// Parse a PPD's nickname, default page size and page sizes (with `PaperDimension` and +/// `ImageableArea`). Page sizes without dimensions are dropped. +pub fn parse_ppd(text: &str) -> Ppd { + let mut ppd = Ppd::default(); + let mut sizes: Vec<(String, String)> = Vec::new(); + let mut dims: Vec<(String, [f64; 2])> = Vec::new(); + let mut areas: Vec<(String, [f64; 4])> = Vec::new(); + for line in text.lines() { + let Some((key, option, label, value)) = ppd_line(line) else { continue }; + match key { + "NickName" => ppd.nick_name = value.to_string(), + "DefaultPageSize" => ppd.default_size = value.to_string(), + "PageSize" if !option.is_empty() && !sizes.iter().any(|(k, _)| k == option) => sizes.push((option.into(), label.into())), + "PaperDimension" => { + if let Some(d) = numbers::<2>(value) { + dims.push((option.into(), d)); + } + } + "ImageableArea" => { + if let Some(a) = numbers::<4>(value) { + areas.push((option.into(), a)); + } + } + _ => {} + } + } + for (keyword, label) in sizes { + let Some((_, [w, h])) = dims.iter().find(|(k, _)| *k == keyword) else { continue }; + if *w <= 0.0 || *h <= 0.0 { + continue; + } + let imageable = areas.iter().find(|(k, _)| *k == keyword).map(|(_, a)| *a); + ppd.papers.push(PpdPaper { name: paper_name(&keyword, &label), keyword, width: *w, height: *h, imageable }); + } + ppd +} + +/// The device a destination becomes: a system printer (PDF in, printed with `lp`) with the +/// PPD's papers. +pub fn printer_config(name: &str, ppd: &Ppd) -> PlotterConfig { + let papers: Vec = ppd + .papers + .iter() + .map(|p| { + let margins = p.imageable.map_or([0.0; 4], |[llx, lly, urx, ury]| { + [llx / PT_PER_MM, lly / PT_PER_MM, (p.width - urx) / PT_PER_MM, (p.height - ury) / PT_PER_MM] + }); + DevicePaper { name: p.name.clone(), width: p.width / PT_PER_MM, height: p.height / PT_PER_MM, margins } + }) + .collect(); + let default_paper = ppd.papers.iter().find(|p| p.keyword == ppd.default_size).map(|p| p.name.clone()).unwrap_or_default(); + let description = if ppd.nick_name.is_empty() { "System printer".to_string() } else { ppd.nick_name.clone() }; + PlotterConfig { + name: name.to_string(), + description, + output: PlotOutput::Pdf, + resolution: 300, + orientation: Orientation::Landscape, + default_paper, + papers, + system: true, + } + .sanitized() +} + +/// `lpstat -e`: one destination per line. +pub fn parse_destinations(text: &str) -> Vec { + let mut v: Vec = text.lines().map(str::trim).filter(|n| valid_name(n)).map(String::from).collect(); + v.dedup(); + v.truncate(MAX_PRINTERS); + v +} + +/// `lp`'s reply: the job id from `request id is NAME-12 (1 file(s))`. +pub fn parse_request_id(text: &str) -> Option { + let rest = text.split("request id is ").nth(1)?; + rest.split_whitespace().next().map(String::from) +} + +/// A destination name CUPS could have made (no path separators or control characters). +pub fn valid_name(n: &str) -> bool { + !n.is_empty() && n.len() <= 127 && !n.starts_with('.') && !n.contains(['/', '\\', '#']) && !n.chars().any(|c| c.is_control() || c.is_whitespace()) +} + +/// The `lp` arguments for a job (the PDF goes to standard input). +pub fn lp_args(printer: &str, page_size: Option<&str>, copies: u32, title: &str) -> Vec { + let mut a = vec!["-d".into(), printer.into(), "-n".into(), copies.clamp(1, MAX_COPIES).to_string()]; + let title: String = title.chars().filter(|c| !c.is_control()).take(100).collect(); + if !title.trim().is_empty() { + a.extend(["-t".into(), title]); + } + if let Some(k) = page_size { + a.extend(["-o".into(), format!("PageSize={k}")]); + } + // The plot is already at its scale: no fitting to the page. + a.extend(["-o".into(), "print-scaling=none".into(), "-o".into(), "fit-to-page=false".into(), "-".into()]); + a +} + +#[cfg(all(unix, not(target_arch = "wasm32")))] +mod system { + use super::*; + use std::io::Write; + use std::process::{Command, Stdio}; + + fn ppd(name: &str) -> Option { + let path = format!("/etc/cups/ppd/{name}.ppd"); + if std::fs::metadata(&path).ok()?.len() > MAX_PPD { + return None; + } + Some(parse_ppd(&std::fs::read_to_string(path).ok()?)) + } + + /// The CUPS destinations as devices (none when CUPS is missing). A destination without a + /// readable PPD (an IPP queue the system made on the fly) offers no papers of its own and is + /// left out. + pub fn printers() -> Vec { + let Ok(out) = Command::new("lpstat").arg("-e").stderr(Stdio::null()).output() else { return Vec::new() }; + parse_destinations(&String::from_utf8_lossy(&out.stdout)) + .into_iter() + .filter_map(|n| ppd(&n).filter(|p| !p.papers.is_empty()).map(|p| printer_config(&n, &p))) + .collect() + } + + /// Send `pdf` to `printer` on the paper called `paper` (a name [`printers`] gave). + /// Returns the job id. + pub fn print(printer: &str, paper: &str, copies: u32, title: &str, pdf: &[u8]) -> Result { + if !valid_name(printer) { + return Err(format!("`{printer}` is not a printer name")); + } + let keyword = ppd(printer).and_then(|p| p.papers.into_iter().find(|x| x.name.eq_ignore_ascii_case(paper)).map(|x| x.keyword)); + let mut child = Command::new("lp") + .args(lp_args(printer, keyword.as_deref(), copies, title)) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("lp: {e}"))?; + if let Some(mut stdin) = child.stdin.take() { + stdin.write_all(pdf).map_err(|e| format!("lp: {e}"))?; + } + let out = child.wait_with_output().map_err(|e| format!("lp: {e}"))?; + let said = String::from_utf8_lossy(&out.stdout).to_string(); + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr).trim().to_string(); + return Err(if err.is_empty() { format!("lp failed ({})", out.status) } else { err }); + } + Ok(parse_request_id(&said).unwrap_or_else(|| said.trim().to_string())) + } +} + +#[cfg(all(unix, not(target_arch = "wasm32")))] +pub use system::{print, printers}; + +#[cfg(test)] +mod tests { + use super::*; + + const PPD: &str = r#"*PPD-Adobe: "4.3" +*NickName: "EPSON Example Series-AirPrint" +*OpenUI *PageSize/Media Size: PickOne +*DefaultPageSize: Letter +*PageSize A4: "<>setpagedevice" +*PageSize Letter/US Letter: "<>setpagedevice" +*PageSize Letter.Fullbleed: "<>setpagedevice" +*PageSize Roll610/Roll 24 in: "<>setpagedevice" +*PageSize NoDims: "<>setpagedevice" +*CloseUI: *PageSize +*PageRegion A4: "<>setpagedevice" +*PaperDimension A4: "595.2756 841.8898" +*ImageableArea A4: "8.5039 8.5039 586.7717 833.3858" +*PaperDimension Letter/US Letter: "612.0000 792.0000" +*ImageableArea Letter/US Letter: "18 36 594 756" +*PaperDimension Letter.Fullbleed: "612 792" +*ImageableArea Letter.Fullbleed: "0 0 612 792" +*PaperDimension Roll610: "1728 2592" +"#; + + #[test] + fn ppd_papers_sizes_and_printable_areas() { + let p = parse_ppd(PPD); + assert_eq!(p.nick_name, "EPSON Example Series-AirPrint"); + assert_eq!(p.default_size, "Letter"); + let names: Vec<&str> = p.papers.iter().map(|x| x.name.as_str()).collect(); + assert_eq!(names, ["A4", "US Letter", "Letter (borderless)", "Roll 24 in"]); + let c = printer_config("EPSON_Example", &p); + assert!(c.system); + assert_eq!(c.output, PlotOutput::Pdf); + assert_eq!(c.default_paper, "US Letter"); + let letter = c.paper("US Letter").unwrap(); + assert!((letter.width - 215.9).abs() < 0.01 && (letter.height - 279.4).abs() < 0.01); + let [l, b, r, t] = letter.margins; + assert!((l - 6.35).abs() < 0.01 && (b - 12.7).abs() < 0.01 && (r - 6.35).abs() < 0.01 && (t - 12.7).abs() < 0.01); + assert_eq!(c.paper("Letter (borderless)").unwrap().margins, [0.0; 4]); + // No ImageableArea: the whole sheet. + assert_eq!(c.paper("Roll 24 in").unwrap().margins, [0.0; 4]); + } + + #[test] + fn lpstat_and_lp_replies() { + assert_eq!(parse_destinations("EPSON_A\nEPSON_B\n\nbad/name\n"), ["EPSON_A", "EPSON_B"]); + assert_eq!(parse_request_id("request id is EPSON_A-42 (1 file(s))\n").as_deref(), Some("EPSON_A-42")); + assert_eq!(parse_request_id("nothing"), None); + let a = lp_args("EPSON_A", Some("Letter"), 0, "Plan\u{7}.dwg - Model"); + assert_eq!( + a, + [ + "-d", + "EPSON_A", + "-n", + "1", + "-t", + "Plan.dwg - Model", + "-o", + "PageSize=Letter", + "-o", + "print-scaling=none", + "-o", + "fit-to-page=false", + "-" + ] + ); + assert_eq!(lp_args("P", None, 5000, "")[3], "999"); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index a7a2ed592..d2dc3ef8f 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -5,6 +5,7 @@ /// What a DXF file holds that CADCraft doesn't model, kept and written back (#528). mod dxf_raw; +pub mod cups; mod dxf_ext; mod dxf_image; mod dxf_mleader; diff --git a/crates/ui-egui/src/managers.rs b/crates/ui-egui/src/managers.rs index db64a9e24..0d902ad82 100644 --- a/crates/ui-egui/src/managers.rs +++ b/crates/ui-egui/src/managers.rs @@ -776,6 +776,8 @@ struct PlotState { page: cadcraft_doc::PageSetup, /// Plot area "window" corners in drawing units: [x1, y1, x2, y2]. window: [f64; 4], + /// Copies a system printer prints. + copies: u32, } /// The page setup a plot of `target` starts from: the layout's, or model-space defaults (fitted @@ -872,10 +874,12 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { if ext.is_empty() { ext = cadcraft_geom::Bounds2::new(cadcraft_geom::Vec2::ZERO, cadcraft_geom::Vec2::new(12.0, 9.0)); } - PlotState { generation, page: plot_page(d, &target), target, window: [ext.min.x, ext.min.y, ext.max.x, ext.max.y] } + PlotState { generation, page: plot_page(d, &target), target, window: [ext.min.x, ext.min.y, ext.max.x, ext.max.y], copies: 1 } }); let model = st.target == "Model"; let choices = PageChoices::new(ctx, d); + // A system printer prints the plot; other devices write a file. + let printer = choices.devices.iter().any(|dv| dv.system && dv.name.eq_ignore_ascii_case(&st.page.device)); // Print... in a preview opened from here plots with these settings. let mut ok = temp::(ctx, PLOT_NOW) == Some(true); set_temp(ctx, PLOT_NOW, false); @@ -904,6 +908,11 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { if let Some((k, v)) = page_rows(ui, egui::Id::new(("plot", st.target.as_str())), &st.page, &rows, &choices) { apply_page_change(&mut st.page, k, &v); } + if printer { + ui.label("Number of copies"); + ui.add(egui::DragValue::new(&mut st.copies).range(1..=999)); + ui.end_row(); + } if model && st.page.plot_area == "window" { for (i, label) in [(0, "First corner"), (2, "Opposite corner")] { ui.label(label); @@ -968,7 +977,11 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { } if ok { let mut params = plot_params(&st, None); - if let Some(pick) = app.services.pick_save.as_ref() { + if printer { + if let Some(o) = params.as_object_mut() { + o.insert("copies".into(), json!(st.copies.max(1))); + } + } else if let Some(pick) = app.services.pick_save.as_ref() { let title = app.session.state().map(|s| s.title.clone()).unwrap_or_default(); let stem = std::path::Path::new(&title).file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.is_empty()); let suggested = format!("{}-{}.{ext}", stem.unwrap_or_else(|| "Drawing".into()), st.target); @@ -982,6 +995,7 @@ fn plot(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { match app.run("plot", params) { Ok(r) => { let msg = match r.get("path").and_then(Value::as_str) { + _ if printer => format!("Sent {} to {} (job {})", st.target, st.page.device, r["job"].as_str().unwrap_or("?")), Some(path) => format!("Plotted {} to {path}", st.target), None => format!("Plotted {} ({} bytes of PDF; there is no file dialog here)", st.target, r["bytes"]), }; @@ -1085,7 +1099,7 @@ mod plot_dialog_tests { fn state(target: &str) -> PlotState { let d = cadcraft_doc::Drawing::new_metric(); - PlotState { generation: 0, page: plot_page(&d, target), target: target.into(), window: [0.0, 0.0, 10.0, 10.0] } + PlotState { generation: 0, page: plot_page(&d, target), target: target.into(), window: [0.0, 0.0, 10.0, 10.0], copies: 1 } } #[test]