diff --git a/Cargo.lock b/Cargo.lock index 0b55428494..03f5044eb7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6109,6 +6109,7 @@ dependencies = [ "webbrowser", "windows", "winit", + "winreg", "winresource", "winsafe", "x11rb", diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 47d26eb7b6..cc8bb1e5e9 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -40,6 +40,9 @@ craft-print = { workspace = true } [target.'cfg(windows)'.dependencies] craft-update = { workspace = true } clipboard-win = { workspace = true } +# Reads a print queue's Standard TCP/IP RAW port for the direct-PDF transport (src/direct_pdf.rs). +# MIT, already in the build through the update client. +winreg = "0.55" # Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the # GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over # Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter. diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 74e05e698f..f2ddb7fce8 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -3,6 +3,8 @@ use std::process::Command; use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; +mod direct_pdf; + pub struct SystemPrint; impl PrintService for SystemPrint { fn printers(&mut self) -> Vec { @@ -35,6 +37,9 @@ mod system { craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect() } pub fn print(job: &PrintJob) -> Result { + if job.direct_pdf { + return super::direct_pdf::print(job); + } // Copies, layout, marks and colour management are already in the PDF. Preserve its // physical sheet size and the queue's duplex default without printing copies twice. let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() }; diff --git a/apps/vectorcraft/src/printing/direct_pdf.rs b/apps/vectorcraft/src/printing/direct_pdf.rs new file mode 100644 index 0000000000..93e657cce9 --- /dev/null +++ b/apps/vectorcraft/src/printing/direct_pdf.rs @@ -0,0 +1,127 @@ +//! Send the print-ready PDF to the printer's own PDF interpreter over its RAW TCP port. +//! +//! This is the opt-in escape hatch for large-format PCL drivers that rewrite a custom page +//! (the HP DesignJet Z5200ps V4 driver emits a square PCL page for a 1067 x 480 mm sheet). The +//! PDF already carries the paper size, so the printer's interpreter prints it as laid out. + +#[cfg(windows)] +mod imp { + use std::io::Write; + use std::net::{Shutdown, TcpStream, ToSocketAddrs}; + use std::time::Duration; + + use vectorcraft_ui_egui::print::PrintJob; + use winreg::RegKey; + use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ}; + + /// Submit one composed PDF to the selected printer's Standard TCP/IP RAW port. + pub fn print(job: &PrintJob) -> Result { + let printer = job + .printer + .map(str::to_string) + .or_else(|| craft_print::printers().into_iter().find(|p| p.default).map(|p| p.name)) + .ok_or("direct PDF needs a selected printer")?; + let (host, port) = tcp_port(&printer)?; + send(&host, port, &pjl(job.title, job.pdf))?; + Ok(format!(" (direct PDF to {host}:{port})")) + } + + /// The `HostName` and port of a printer port registered as a Standard TCP/IP RAW port. + fn tcp_port(printer: &str) -> Result<(String, u16), String> { + let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); + let printer_key = hklm + .open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Printers\{printer}"), KEY_READ) + .map_err(|e| format!("direct PDF: cannot read the printer settings for {printer}: {e}"))?; + let port_name: String = printer_key.get_value("Port").map_err(|e| format!("direct PDF: {printer} has no port: {e}"))?; + let port_key = hklm + .open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\{port_name}"), KEY_READ) + .map_err(|e| format!("direct PDF: {printer} does not use a Standard TCP/IP port ({port_name}): {e}"))?; + let protocol: u32 = port_key.get_value("Protocol").unwrap_or(1); + if protocol != 1 { + return Err(format!("direct PDF: {printer}'s port ({port_name}) is not a RAW TCP/IP port")); + } + let host = port_key + .get_value::("HostName") + .ok() + .filter(|h| !h.trim().is_empty()) + .or_else(|| port_key.get_value::("IPAddress").ok().filter(|h| !h.trim().is_empty())) + .ok_or_else(|| format!("direct PDF: {printer}'s port ({port_name}) has no host address"))?; + let number = port_key.get_value::("PortNumber").unwrap_or(9100); + let port = u16::try_from(number).map_err(|_| format!("direct PDF: invalid port number {number}"))?; + Ok((host.trim().to_string(), port)) + } + + /// Frame the PDF for the printer's PJL interpreter. + fn pjl(title: &str, pdf: &[u8]) -> Vec { + let mut name: String = title.chars().map(|c| if (c.is_ascii_graphic() || c == ' ') && c != '"' { c } else { '_' }).take(80).collect(); + if name.is_empty() { + name.push_str("VectorCraft"); + } + let mut out = Vec::with_capacity(pdf.len() + 96); + out.extend_from_slice(b"\x1b%-12345X@PJL JOB NAME=\""); + out.extend_from_slice(name.as_bytes()); + out.extend_from_slice(b"\"\r\n@PJL ENTER LANGUAGE=PDF\r\n"); + out.extend_from_slice(pdf); + out.extend_from_slice(b"\r\n\x1b%-12345X@PJL EOJ\r\n"); + out + } + + /// Stream `data` to the first reachable address of `host:port`. + fn send(host: &str, port: u16, data: &[u8]) -> Result<(), String> { + let addrs = (host, port).to_socket_addrs().map_err(|e| format!("direct PDF: cannot resolve {host}: {e}"))?; + let mut last = None; + for addr in addrs { + match TcpStream::connect_timeout(&addr, Duration::from_secs(10)) { + Ok(mut stream) => { + stream.set_write_timeout(Some(Duration::from_secs(120))).map_err(|e| format!("direct PDF: {e}"))?; + stream.write_all(data).map_err(|e| format!("direct PDF: writing to {host}:{port} failed: {e}"))?; + stream.shutdown(Shutdown::Write).map_err(|e| format!("direct PDF: finishing {host}:{port} failed: {e}"))?; + return Ok(()); + } + Err(e) => last = Some(e), + } + } + Err(match last { + Some(e) => format!("direct PDF: cannot connect to {host}:{port}: {e}"), + None => format!("direct PDF: {host}:{port} has no addresses"), + }) + } + + #[cfg(test)] + mod tests { + use super::*; + use std::io::Read; + use std::net::TcpListener; + + #[test] + fn the_pjl_frames_the_pdf() { + let out = pjl("witch hat\"", b"%PDF-1.7"); + let text = String::from_utf8_lossy(&out); + assert!(text.starts_with("\u{1b}%-12345X@PJL JOB NAME=\"witch hat_\"\r\n@PJL ENTER LANGUAGE=PDF\r\n")); + assert!(text.contains("%PDF-1.7")); + assert!(text.ends_with("\r\n\u{1b}%-12345X@PJL EOJ\r\n")); + } + + #[test] + fn the_pdf_reaches_a_listening_port() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let t = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut got = Vec::new(); + stream.read_to_end(&mut got).unwrap(); + got + }); + send("127.0.0.1", port, b"%PDF-1.7 test").unwrap(); + assert_eq!(t.join().unwrap(), b"%PDF-1.7 test"); + } + } +} + +#[cfg(windows)] +pub use imp::print; + +#[cfg(not(windows))] +pub fn print(_: &vectorcraft_ui_egui::print::PrintJob) -> Result { + Err("direct PDF printing is only available on Windows".into()) +} diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 76650401c0..496cc7cb25 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -91,6 +91,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields.insert("printer".into(), json!(default)); fields.insert("toFile".into(), json!(!printers["service"].as_bool().unwrap_or(false))); fields.insert("__printers".into(), printers); + fields.insert("__directPdf".into(), json!(false)); fields.insert("__section".into(), json!(SECTIONS[0])); fields.insert("__sheet".into(), json!(0)); // The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ). @@ -205,7 +206,15 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { app.ui.dialog = None; return Ok(json!({ "settings": settings })); } - let r = crate::print::run(app, &json!({ "settings": settings, "printer": d.str("printer"), "toFile": d.bool("toFile") }))?; + let r = crate::print::run( + app, + &json!({ + "settings": settings, + "printer": d.str("printer"), + "toFile": d.bool("toFile"), + "directPdf": d.bool("__directPdf"), + }), + )?; app.ui.dialog = None; Ok(r) } @@ -358,6 +367,11 @@ fn printer_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { app.status(e); } }); + if service && cfg!(windows) { + let to_file = d.bool("toFile"); + flag(ui, d, "__directPdf", "Send PDF directly (bypass driver)", !to_file); + note(ui, "Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size."); + } } /// `print.preview` of `settings` (an error when they can't print), cached until they or the diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 499f6f2607..6c94e0cad8 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -26,6 +26,9 @@ pub struct PrintJob<'a> { /// The job's name in the print queue. pub title: &'a str, pub pdf: &'a [u8], + /// Send the PDF to the printer's own PDF interpreter over its RAW TCP port instead of + /// spooling it through the platform driver (Windows). + pub direct_pdf: bool, } /// Submission callable from the desktop background worker. @@ -105,6 +108,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { let pdf = data.as_ref().and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or("the print job has no data")?; let title = app.session.active().map(|d| d.title()).unwrap_or_default(); let printer = s("printer").filter(|n| !n.is_empty()); + let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false); let service = app.services.print.as_mut().ok_or("no print service")?; if let Some(submit) = service.shared_print() { let pending_printer = printer.clone(); @@ -114,7 +118,8 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { format!("Printing {title}"), None, move |_| { - submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf }).map(|note| json!({ "note": note, "printer": printer })) + submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf }) + .map(|note| json!({ "note": note, "printer": printer })) }, move |app, result| { let receipt = result?; @@ -135,7 +140,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result { } return Ok(v); } - let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf })?; + let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })?; app.status(done); v["printer"] = json!(printer); v["printed"] = json!(true); diff --git a/docs/gaps.md b/docs/gaps.md index d7276abeab..dccc4a5193 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -19,6 +19,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-03 | minor | Windows: opt-in direct PDF transport writes the print-ready PDF to a printer's Standard TCP/IP RAW port, for PCL-only drivers that rewrite custom pages (#5339, #4004); TCP framing and ticket-independent submission covered by app tests. No ranked entry closed; scores and estimates unchanged. | | 2026-10-24 | minor | G12: General › Corner Radius is the Rounded Rectangle tool's radius, a change while the tool is active reaches it, and the radius ↑/↓ set while drawing (or a Tool Options value) becomes the preference, within 0–1296 pt (#394, `crates/engine/src/tests/constrain_tools.rs`); no entry closed, estimate unchanged. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-3; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | | 2026-10-22 | minor | Reconcile upstream documentation after review F-2; preserve every dated revision and the original scaleArt runtime evidence without repeating completed jobs. | diff --git a/docs/print-tiling.md b/docs/print-tiling.md index 28d92a376e..00bf82c33e 100644 --- a/docs/print-tiling.md +++ b/docs/print-tiling.md @@ -49,6 +49,15 @@ pages before sending it to a printer. When printing that PDF, keep its page size than applying another fit-to-page reduction. For a sewing pattern, measure a known length on a printed sheet before printing the full job. +## Direct PDF on PCL-only printers + +Some Windows PCL drivers rewrite a custom page to a different physical size; the HP DesignJet +Z5200ps V4, for example, turns a 1067 x 480 mm page into a square PCL page. In **Print**, under +**Printer**, turn on **Send PDF directly (bypass driver)**. VectorCraft then writes the print-ready +PDF to the selected printer's Standard TCP/IP RAW port, so the printer's own PDF interpreter prints +the PDF's page size. It needs a printer with PDF support and a RAW TCP/IP port; it bypasses the +Windows driver's paper, colour and finishing settings. Leave it off for ordinary driver printing. + ## Choose a tiling mode | Scaling | How it divides the drawing | When to use it |