mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 02:03:02 +00:00
combo: #5341
This commit is contained in:
Generated
+1
@@ -6644,6 +6644,7 @@ dependencies = [
|
||||
"webbrowser",
|
||||
"windows",
|
||||
"winit",
|
||||
"winreg",
|
||||
"winresource",
|
||||
"winsafe",
|
||||
"wl-clipboard-rs",
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Printer> {
|
||||
@@ -43,6 +45,9 @@ mod system {
|
||||
craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect()
|
||||
}
|
||||
pub fn print(job: &PrintJob) -> Result<String, String> {
|
||||
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() };
|
||||
|
||||
@@ -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<String, String> {
|
||||
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::<String, _>("HostName")
|
||||
.ok()
|
||||
.filter(|h| !h.trim().is_empty())
|
||||
.or_else(|| port_key.get_value::<String, _>("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::<u32, _>("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<u8> {
|
||||
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<String, String> {
|
||||
Err("direct PDF printing is only available on Windows".into())
|
||||
}
|
||||
@@ -96,6 +96,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
fields.insert("printer".into(), json!(default));
|
||||
fields.insert("toFile".into(), json!(!printers["service"].as_bool().unwrap_or(false)));
|
||||
fields.insert("__printers".into(), printers);
|
||||
app.ui.print_direct_pdf = 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).
|
||||
@@ -217,7 +218,16 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
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 direct_pdf = app.ui.print_direct_pdf;
|
||||
let r = crate::print::run(
|
||||
app,
|
||||
&json!({
|
||||
"settings": settings,
|
||||
"printer": d.str("printer"),
|
||||
"toFile": d.bool("toFile"),
|
||||
"directPdf": direct_pdf,
|
||||
}),
|
||||
)?;
|
||||
app.ui.dialog = None;
|
||||
Ok(r)
|
||||
}
|
||||
@@ -372,6 +382,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");
|
||||
ui.add_enabled(!to_file, egui::Checkbox::new(&mut app.ui.print_direct_pdf, "Send PDF directly (bypass driver)"));
|
||||
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
|
||||
|
||||
@@ -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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -394,6 +394,10 @@ pub struct UiState {
|
||||
#[serde(rename = "language", skip_serializing)]
|
||||
pub legacy_language: Option<String>,
|
||||
pub brightness: Brightness,
|
||||
/// The Print dialog's opt-in direct-PDF transport. UI-only and not serialized: the control
|
||||
/// channel cannot enable a print that bypasses the printer driver.
|
||||
#[serde(skip)]
|
||||
pub print_direct_pdf: bool,
|
||||
pub dock_tab: DockTab,
|
||||
/// Tab order in the dock's tabbed group when it differs from [`DockTab::ALL`].
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
@@ -1181,6 +1185,7 @@ impl Default for UiState {
|
||||
Self {
|
||||
legacy_language: None,
|
||||
brightness: Brightness::MediumDark,
|
||||
print_direct_pdf: false,
|
||||
dock_tab: DockTab::Properties,
|
||||
dock_tab_order: Vec::new(),
|
||||
dock_collapsed: false,
|
||||
|
||||
@@ -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 |
|
||||
|
||||
Reference in New Issue
Block a user