From 628a54b5646ab92e70b1ddafd3000a2367d7bb94 Mon Sep 17 00:00:00 2001 From: Moiztermind Date: Sat, 10 Oct 2026 23:33:35 +0100 Subject: [PATCH 01/17] Print on Windows: printer list, driver Print Settings, GDI printing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - photocraft-winprint: an isolated unsafe crate (like photocraft-tablet) for Windows printing: printer list, the driver's Print Settings dialog, page geometry, and GDI printing with ICM off. - file.print prints on Windows (explicit "send": true only); new file.print.printers and file.print.page commands; printerSettings param. - Print dialog on Windows: Printer menu, Print Settings…, paper from the driver. - panic_hunt fuzzes print commands as dry runs. Closes #2697. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 9 + Cargo.toml | 1 + crates/engine/Cargo.toml | 1 + crates/engine/src/print_cmds.rs | 110 +++++++- crates/engine/src/print_cmds/tests.rs | 35 +++ crates/engine/tests/panic_hunt.rs | 9 + crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/file_ui.rs | 113 +++++++- crates/winprint/Cargo.toml | 26 ++ crates/winprint/src/lib.rs | 263 ++++++++++++++++++ crates/winprint/src/windows.rs | 378 ++++++++++++++++++++++++++ xtask/src/layers.rs | 2 + 12 files changed, 933 insertions(+), 15 deletions(-) create mode 100644 crates/winprint/Cargo.toml create mode 100644 crates/winprint/src/lib.rs create mode 100644 crates/winprint/src/windows.rs diff --git a/Cargo.lock b/Cargo.lock index fde4ac01b8..80cfe99225 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4368,6 +4368,7 @@ dependencies = [ "photocraft-raw", "photocraft-text", "photocraft-vector", + "photocraft-winprint", "rayon", "roxmltree", "serde", @@ -4592,6 +4593,7 @@ dependencies = [ "photocraft-testkit", "photocraft-text", "photocraft-vector", + "photocraft-winprint", "rayon", "serde", "serde_json", @@ -4632,6 +4634,13 @@ dependencies = [ "web-sys", ] +[[package]] +name = "photocraft-winprint" +version = "0.7.0" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "pico-args" version = "0.5.0" diff --git a/Cargo.toml b/Cargo.toml index 7502ff4fd5..ea82e615c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ photocraft-engine = { path = "crates/engine" } photocraft-ui-egui = { path = "crates/ui-egui" } photocraft-testkit = { path = "crates/testkit" } photocraft-tablet = { path = "crates/tablet" } +photocraft-winprint = { path = "crates/winprint" } # external thiserror = "2" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index fa15c30986..986ce8fc5c 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -19,6 +19,7 @@ photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } photocraft-compose = { workspace = true } +photocraft-winprint = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 59d6b3e1e8..e3e520ff9e 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -353,6 +353,20 @@ fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result { }; let copies = crate::commands::int(p, "copies").unwrap_or(1).clamp(1, 999); let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false); + // Windows has no `lp`: print through the driver (GDI, ICM off) instead of spooling a PDF. + // Only with an explicit `"send": true` (the dialog's Print button): a bare call, such as a + // fuzzer's or a script's `{}`, never puts paper through a printer. A dry run still renders + // the PDF and reports the `lp` line, as on every platform. + let explicit_send = p.get("send").and_then(Value::as_bool) == Some(true); + if cfg!(windows) && explicit_send && !dry && output.is_none() { + let printed = print_windows(&page, p, &doc.name, copies)?; + remember_print(s, p); + crate::automate_cmds::fire_event(s, "print"); + return Ok(json!({ + "pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, + "copies": copies, "command": Value::Null, "sent": true, "spooler": printed, "color": color, + })); + } let pdf = print_pdf(&page); write_file(&pdf_path, &pdf)?; let mut argv: Vec = vec!["lp".into()]; @@ -386,6 +400,80 @@ fn remember_print(s: &mut Session, p: &Value) { s.file_menu.last_print = Some(remembered); } +/// The `printer` parameter, or the system's default printer. +fn printer_name(p: &Value) -> Result { + if let Some(name) = p.get("printer").and_then(Value::as_str).filter(|v| !v.trim().is_empty()) { + return Ok(name.to_string()); + } + photocraft_winprint::default_printer().map_err(other)?.ok_or_else(|| other("no printer chosen and no default printer is set")) +} + +/// The driver settings chosen with Print Settings… (`printerSettings`, hex), when any. +fn printer_settings(p: &Value) -> Result> { + match p.get("printerSettings").and_then(Value::as_str).filter(|v| !v.is_empty()) { + Some(hex) => photocraft_winprint::DevMode::from_hex(hex).map(Some).map_err(|e| bad("file.print", e.to_string())), + None => Ok(None), + } +} + +/// The page's image as 8-bit RGB rows (gray expanded), mirrored for Emulsion Down. +pub fn page_rgb(page: &PrintPage) -> Result> { + let img = &page.image; + let (w, h) = (img.width as usize, img.height as usize); + let mut rgb = match img.channels { + 3 => img.data.clone(), + 1 => img.data.iter().flat_map(|g| [*g, *g, *g]).collect(), + _ => return Err(other("this printer profile is CMYK; Windows printers take RGB, so choose the printer's own (RGB) profile")), + }; + if rgb.len() != w * h * 3 { + return Err(other("nothing to print")); + } + if page.emulsion_down { + for row in rgb.chunks_exact_mut(w * 3) { + row.as_chunks_mut::<3>().0.reverse(); + } + } + Ok(rgb) +} + +/// The image box with its origin at the sheet's top-left (GDI's), mirrored for Emulsion Down. +pub fn page_rect_top_left(page: &PrintPage) -> (f64, f64, f64, f64) { + let (pw, ph) = page.paper; + let (x, y, w, h) = page.rect; + let x = if page.emulsion_down { pw - x - w } else { x }; + (x, ph - y - h, w, h) +} + +/// Prints `page` on a Windows printer. Printer marks, description and labels are PDF-only. +fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: i64) -> Result { + let printer = printer_name(p)?; + let settings = printer_settings(p)?; + let rgb = page_rgb(page)?; + let image = photocraft_winprint::RgbImage { width: page.image.width, height: page.image.height, data: &rgb }; + let job = photocraft_winprint::Job { printer: &printer, settings: settings.as_ref(), title, output_file: None, copies: copies.clamp(1, 999) as u32 }; + let done = photocraft_winprint::print(&job, &image, page_rect_top_left(page)).map_err(other)?; + let marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration || page.description.is_some() || page.label.is_some(); + Ok( + json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3], "marksSkipped": marks}), + ) +} + +fn printers(_: &mut Session, _: &Value) -> Result { + match photocraft_winprint::printers() { + Ok(list) => Ok(json!({"supported": true, "printers": list.iter().map(|p| json!({"name": p.name, "default": p.default})).collect::>()})), + Err(photocraft_winprint::PrintError::Unsupported) => Ok(json!({"supported": false, "printers": []})), + Err(e) => Err(other(e)), + } +} + +fn printer_page(_: &mut Session, p: &Value) -> Result { + let printer = printer_name(p)?; + let pg = photocraft_winprint::page(&printer, printer_settings(p)?.as_ref()).map_err(other)?; + Ok( + json!({"printer": printer, "paper": [pg.paper.0, pg.paper.1], "printable": [pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3], "dpi": [pg.dpi.0, pg.dpi.1]}), + ) +} + #[cfg(not(target_arch = "wasm32"))] fn spool_pdf(argv: &[String]) -> Result { let out = std::process::Command::new(&argv[0]).args(&argv[1..]).output().map_err(|e| other(format!("could not run `lp` (CUPS): {e}")))?; @@ -567,9 +655,29 @@ pub fn specs() -> Vec { CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run } }; } - const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the lp command, don't spool)} → {pdf, imageRect, command, sent}"##; + const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"printerSettings":hex? (the driver settings from Print Settings…, Windows),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool? (Windows prints to the printer only with an explicit true),"dryRun":bool=false (render the PDF, report the lp command, don't spool)} → {pdf, imageRect, command, sent}"##; vec![ spec!("file.print", "Print…", &["File"], Some("Cmd+P"), PRINT_PARAMS, native_doc, print), + CommandSpec { + id: "file.print.printers", + label: "Printers", + menu: &[], + shortcut: None, + params: r##"{} → {supported, printers: [{name, default}]} (supported: Windows; elsewhere Print spools with lp)"##, + enabled: |_| Ok(()), + journal: false, + run: printers, + }, + CommandSpec { + id: "file.print.page", + label: "Printer Page", + menu: &[], + shortcut: None, + params: r##"{"printer":name? (default printer),"printerSettings":hex?} → {printer, paper: [w,h] pt, printable: [x,y,w,h] pt from the top-left, dpi: [x,y]} (Windows)"##, + enabled: |_| Ok(()), + journal: false, + run: printer_page, + }, spec!( "file.printOneCopy", "Print One Copy", diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index 877fb945ff..04102eb78c 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -133,6 +133,41 @@ fn emulsion_down_mirrors_the_whole_page() { } } +fn page_of(channels: usize, data: Vec, emulsion_down: bool) -> PrintPage { + PrintPage { + paper: (600.0, 800.0), + image: PrintImage { width: 2, height: 1, channels, data, icc: None }, + rect: (100.0, 200.0, 144.0, 72.0), + marks: Marks::default(), + description: None, + label: None, + emulsion_down, + } +} + +#[test] +fn windows_print_image_is_rgb_mirrored_for_emulsion_down() { + assert_eq!(page_rgb(&page_of(3, vec![1, 2, 3, 4, 5, 6], false)).unwrap(), [1, 2, 3, 4, 5, 6]); + assert_eq!(page_rgb(&page_of(3, vec![1, 2, 3, 4, 5, 6], true)).unwrap(), [4, 5, 6, 1, 2, 3]); + assert_eq!(page_rgb(&page_of(1, vec![7, 9], true)).unwrap(), [9, 9, 9, 7, 7, 7]); + assert!(page_rgb(&page_of(4, vec![0; 8], false)).is_err(), "CMYK can't go to a GDI printer"); + assert!(page_rgb(&page_of(3, vec![0; 5], false)).is_err(), "short data"); + // GDI's origin is the sheet's top-left; Emulsion Down moves the box to the mirrored side. + assert_eq!(page_rect_top_left(&page_of(3, vec![0; 6], false)), (100.0, 528.0, 144.0, 72.0)); + assert_eq!(page_rect_top_left(&page_of(3, vec![0; 6], true)), (356.0, 528.0, 144.0, 72.0)); +} + +#[test] +fn printer_commands_answer_without_a_document_and_reject_bad_settings() { + let mut s = Session::new(); + let r = s.execute("file.print.printers", json!({})).unwrap(); + assert_eq!(r["supported"], cfg!(windows)); + assert!(r["printers"].is_array()); + assert!(s.execute("file.print.page", json!({"printer": "Anything", "printerSettings": "zz"})).is_err()); + let mut s = session("rgb", 8); + assert!(s.execute("file.print", json!({"printer": "Anything", "printerSettings": "0102", "send": true})).is_err()); +} + #[test] fn printer_profile_can_be_an_installed_icc_file() { let dir = tmp("icc"); diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index b301b95389..d3b396f2b8 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -61,6 +61,15 @@ fn no_command_panics_or_hangs_on_adversarial_params() { let mut bad: Vec = Vec::new(); for spec in command_specs() { for p in ¶ms { + // Print and Print One Copy reach real printers (lp, or the Windows driver): fuzz them + // as dry runs so the hunt never prints a page. + let mut p = p.clone(); + if spec.id.starts_with("file.print") + && let Some(o) = p.as_object_mut() + { + o.insert("dryRun".into(), json!(true)); + } + let p = &p; if let Err(why) = run_guarded(spec.id, p) { bad.push(format!("{} [{why}] <- {p}", spec.id)); break; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index a9af622286..1152a36680 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -12,6 +12,7 @@ craft-ui = { workspace = true } photocraft-geom = { workspace = true } photocraft-color = { workspace = true } photocraft-cms = { workspace = true } +photocraft-winprint = { workspace = true } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-compose = { workspace = true } diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 8b96a51a3d..323519c36b 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -593,9 +593,36 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { ] { f.entry(k.to_string()).or_insert(v); } + // Windows: the system's printers, and the paper from the chosen printer's driver settings. + if let Ok(list) = photocraft_winprint::printers() { + f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::>())); + let known = |n: &str| list.iter().any(|p| p.name == n); + if !known(&s(&f, "printer", "")) { + let fallback = list.iter().find(|p| p.default).or(list.first()).map(|p| p.name.clone()).unwrap_or_default(); + f.insert("printer".into(), json!(fallback)); + f.remove("printerSettings"); + } + driver_page(&mut f); + } app.ui.open_dialog(DialogKind::Command, f) } +/// Takes the paper from the printer's driver settings (Windows), as Photoshop does. +fn driver_page(f: &mut Map) { + let printer = s(f, "printer", ""); + let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| photocraft_winprint::DevMode::from_hex(h).ok()); + match photocraft_winprint::page(&printer, settings.as_ref()) { + Ok(pg) => { + f.insert("paper".into(), json!([pg.paper.0, pg.paper.1])); + f.insert("orientation".into(), json!("portrait")); + f.remove("__pageError"); + } + Err(e) => { + f.insert("__pageError".into(), json!(e.to_string())); + } + } +} + /// Points per unit for the Position and Size fields. fn unit_pt(units: &str) -> f64 { match units { @@ -702,19 +729,61 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map> = + f.get("__printers").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()); + if let Some(printers) = &printers { + // Windows: Photoshop's Printer menu and Print Settings… (the driver's own dialog). + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim)); + let before = s(f, "printer", ""); + let opts: Vec<(&str, &str)> = printers.iter().map(|n| (n.as_str(), n.as_str())).collect(); + dropdown_str(ui, "print-printer", f, "printer", &opts, 220.0); + if s(f, "printer", "") != before { + f.remove("printerSettings"); + driver_page(f); + } + }); + ui.horizontal(|ui| { + number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0); + if ui.button(tl!("Print Settings…")).clicked() { + let printer = s(f, "printer", ""); + let current = f.get("printerSettings").and_then(Value::as_str).and_then(|h| photocraft_winprint::DevMode::from_hex(h).ok()); + match photocraft_winprint::settings_dialog(&printer, current.as_ref(), None) { + Ok(Some(dm)) => { + f.insert("printerSettings".into(), json!(dm.to_hex())); + driver_page(f); + } + Ok(None) => {} + Err(e) => { + f.insert("__pageError".into(), json!(e.to_string())); + } + } + } + }); + let paper = p.get("paper").and_then(Value::as_array).map(|a| (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64))); + let text = match paper { + Some((Some(w), Some(h))) => format!("{:.0} × {:.0} mm · {}", w / 72.0 * 25.4, h / 72.0 * 25.4, tl!("set in Print Settings…")), + _ => String::new(), + }; + ui.label(egui::RichText::new(text).color(t.text_dim).size(11.0)); + if let Some(e) = f.get("__pageError").and_then(Value::as_str) { + ui.label(egui::RichText::new(e).color(t.warning).size(11.0)); } - }); - number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0); - ui.horizontal(|ui| { - let papers: Vec<(&str, &str)> = photocraft_engine::print_cmds::PAPERS.iter().map(|p| (p.0, p.0)).collect(); - dropdown_str(ui, "print-paper", f, "paper", &papers, 110.0); - dropdown_str(ui, "print-orient", f, "orientation", &[("portrait", tl!("Portrait")), ("landscape", tl!("Landscape"))], 110.0); - }); + } else { + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim)); + let mut pr = s(f, "printer", ""); + if ui.add(egui::TextEdit::singleline(&mut pr).hint_text(tl!("Default printer")).desired_width(180.0)).changed() { + f.insert("printer".into(), json!(pr)); + } + }); + number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0); + ui.horizontal(|ui| { + let papers: Vec<(&str, &str)> = photocraft_engine::print_cmds::PAPERS.iter().map(|p| (p.0, p.0)).collect(); + dropdown_str(ui, "print-paper", f, "paper", &papers, 110.0); + dropdown_str(ui, "print-orient", f, "orientation", &[("portrait", tl!("Portrait")), ("landscape", tl!("Landscape"))], 110.0); + }); + } head(ui, tl!("Color Management")); dropdown_str( ui, @@ -766,6 +835,11 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) -> Result { - let r = app.run("file.print", params(f))?; - app.ui.status = if r["sent"] == json!(true) { + let mut p = params(f); + // The Print button prints (an empty Save as PDF path means the printer). + if s(f, "output", "").is_empty() { + p["send"] = json!(true); + } + let r = app.run("file.print", p)?; + app.ui.status = if let Some(printer) = r["spooler"]["printer"].as_str() { + let skipped = if r["spooler"]["marksSkipped"] == json!(true) { " (printer marks and labels are only in Save as PDF)" } else { "" }; + format!("Sent to {printer}{skipped}") + } else if r["sent"] == json!(true) { let template = "Sent to the printer ({spooler})"; crate::i18n::fmt(tl!(template), &[("spooler", r["spooler"].as_str().unwrap_or(""))]) } else { diff --git a/crates/winprint/Cargo.toml b/crates/winprint/Cargo.toml new file mode 100644 index 0000000000..09504156d5 --- /dev/null +++ b/crates/winprint/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "photocraft-winprint" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Windows printing: printer list, the driver's Print Settings dialog, page geometry and GDI printing with ICM off" + +# An isolated `unsafe` helper crate like photocraft-tablet (craftrules never-crash, AGENTS.md): +# Windows printing needs Win32 calls. Only `src/windows.rs` allows `unsafe`; every block has a +# `SAFETY:` comment. Elsewhere every function returns `Unsupported`. +[lints.rust] +unsafe_code = "deny" + +[lints.clippy] +dbg_macro = "warn" +todo = "warn" + +# Already in Cargo.lock (winit/wgpu pull it in); pinned exactly: review the diff before bumping. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "=0.61.2", features = [ + "Win32_Foundation", + "Win32_Graphics_Gdi", + "Win32_Graphics_Printing", + "Win32_Storage_Xps", + "Win32_UI_ColorSystem", +] } diff --git a/crates/winprint/src/lib.rs b/crates/winprint/src/lib.rs new file mode 100644 index 0000000000..fac300a50f --- /dev/null +++ b/crates/winprint/src/lib.rs @@ -0,0 +1,263 @@ +//! Windows printing for File › Print: the system's printers, the driver's own Print Settings +//! dialog (paper, paper type, quality, the driver's colour correction and mirror), the page +//! geometry it implies, and printing an 8-bit RGB image through GDI with ICM off, so colours +//! converted with a printer profile ("PhotoCraft Manages Colors") reach the driver unchanged. +//! +//! The driver settings travel as an opaque DEVMODE blob ([`DevMode`]), validated before use. +//! Everything here is a safe API; the Win32 calls live in `windows.rs`. Other platforms get +//! [`PrintError::Unsupported`]. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +#[cfg(windows)] +#[allow(unsafe_code)] +mod windows; + +use std::fmt; + +/// Why a printing call failed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PrintError { + /// Not on Windows. + Unsupported, + /// Bad input (an unknown printer, a malformed DEVMODE, an empty image). + Invalid(String), + /// A Win32 call failed. + System(String), +} + +impl fmt::Display for PrintError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + PrintError::Unsupported => f.write_str("printing to a printer needs Windows here"), + PrintError::Invalid(m) | PrintError::System(m) => f.write_str(m), + } + } +} + +impl std::error::Error for PrintError {} + +pub type Result = std::result::Result; + +/// One installed printer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Printer { + pub name: String, + pub default: bool, +} + +/// A printer driver's settings (a Win32 DEVMODEW with the driver's private part), as bytes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DevMode(Vec); + +/// Offsets inside DEVMODEW: `dmSize` and `dmDriverExtra` follow the 32-wchar device name and +/// two version words. +const DM_SIZE_AT: usize = 68; +const DM_EXTRA_AT: usize = 70; +/// The smallest DEVMODEW a driver writes (Windows 95's, up to `dmICMIntent`). +const DM_MIN: usize = 156; +/// Larger blobs are not driver settings. +const DM_MAX: usize = 1 << 20; + +impl DevMode { + /// Validates driver settings bytes: the header's own sizes must add up to the length. + pub fn from_bytes(b: Vec) -> Result { + let word = |at: usize| b.get(at..at + 2).map(|w| usize::from(u16::from_le_bytes([w[0], w[1]]))); + let (Some(size), Some(extra)) = (word(DM_SIZE_AT), word(DM_EXTRA_AT)) else { + return Err(PrintError::Invalid("printer settings are too short".into())); + }; + if b.len() > DM_MAX || size < DM_MIN || size.checked_add(extra) != Some(b.len()) { + return Err(PrintError::Invalid("printer settings are damaged; choose Print Settings again".into())); + } + Ok(DevMode(b)) + } + + pub fn as_bytes(&self) -> &[u8] { + &self.0 + } + + /// Hex, for JSON parameters and remembered print settings. + pub fn to_hex(&self) -> String { + self.0.iter().map(|b| format!("{b:02x}")).collect() + } + + pub fn from_hex(s: &str) -> Result { + if !s.len().is_multiple_of(2) || s.len() > DM_MAX * 2 { + return Err(PrintError::Invalid("printer settings are damaged; choose Print Settings again".into())); + } + let bytes: Option> = (0..s.len()).step_by(2).map(|i| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok())).collect(); + Self::from_bytes(bytes.ok_or_else(|| PrintError::Invalid("printer settings are damaged; choose Print Settings again".into()))?) + } +} + +/// What a printer will print on with given settings. Points (1/72 in), origin top-left. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Page { + /// The whole sheet. + pub paper: (f64, f64), + /// The area the printer can reach: (x, y, width, height). + pub printable: (f64, f64, f64, f64), + /// Device resolution (dots per inch). + pub dpi: (u32, u32), +} + +/// An 8-bit RGB image, rows top to bottom, `width * 3` bytes each. +pub struct RgbImage<'a> { + pub width: u32, + pub height: u32, + pub data: &'a [u8], +} + +/// One print job. +pub struct Job<'a> { + pub printer: &'a str, + pub settings: Option<&'a DevMode>, + /// The name in the print queue. + pub title: &'a str, + /// Print to this file instead of the device (drivers that write files, and tests). + pub output_file: Option<&'a str>, + pub copies: u32, +} + +/// Where a job went: the image box in device pixels and the device resolution. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Printed { + pub device_rect: (i32, i32, i32, i32), + pub dpi: (u32, u32), +} + +/// Maps an image box in points (origin top-left of the sheet) to device pixels (origin at the +/// printable area's corner, as GDI draws). +pub fn device_rect(page: &Page, rect: (f64, f64, f64, f64)) -> (i32, i32, i32, i32) { + let (dx, dy) = (f64::from(page.dpi.0) / 72.0, f64::from(page.dpi.1) / 72.0); + let px = |v: f64| if v.is_finite() { v.round().clamp(-1e8, 1e8) as i32 } else { 0 }; + let (x, y, w, h) = rect; + (px((x - page.printable.0) * dx), px((y - page.printable.1) * dy), px(w * dx), px(h * dy)) +} + +/// The printers installed for this user, the default first. +pub fn printers() -> Result> { + #[cfg(windows)] + { + let mut v = windows::printers()?; + v.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))); + Ok(v) + } + #[cfg(not(windows))] + Err(PrintError::Unsupported) +} + +/// The default printer's name. +pub fn default_printer() -> Result> { + #[cfg(windows)] + { + windows::default_printer() + } + #[cfg(not(windows))] + Err(PrintError::Unsupported) +} + +/// A printer's settings as its driver starts them. +pub fn default_settings(printer: &str) -> Result { + #[cfg(windows)] + { + windows::properties(printer, None, None, false)?.ok_or_else(|| PrintError::System("the printer driver gave no settings".into())) + } + #[cfg(not(windows))] + { + let _ = printer; + Err(PrintError::Unsupported) + } +} + +/// Shows the driver's Print Settings dialog (modal; `parent` is a window handle). `None` when +/// the user cancels. +pub fn settings_dialog(printer: &str, current: Option<&DevMode>, parent: Option) -> Result> { + #[cfg(windows)] + { + windows::properties(printer, current, parent, true) + } + #[cfg(not(windows))] + { + let _ = (printer, current, parent); + Err(PrintError::Unsupported) + } +} + +/// The sheet and printable area for `printer` with `settings`. +pub fn page(printer: &str, settings: Option<&DevMode>) -> Result { + #[cfg(windows)] + { + windows::page(printer, settings) + } + #[cfg(not(windows))] + { + let _ = (printer, settings); + Err(PrintError::Unsupported) + } +} + +/// Prints `image` into `rect` (points, origin top-left of the sheet), `job.copies` pages. +pub fn print(job: &Job<'_>, image: &RgbImage<'_>, rect: (f64, f64, f64, f64)) -> Result { + let row = (image.width as usize).checked_mul(3).ok_or_else(|| PrintError::Invalid("image too large".into()))?; + if image.width == 0 || image.height == 0 || row.checked_mul(image.height as usize) != Some(image.data.len()) { + return Err(PrintError::Invalid("nothing to print".into())); + } + if !(rect.2 > 0.0 && rect.3 > 0.0) { + return Err(PrintError::Invalid("the print size is empty".into())); + } + #[cfg(windows)] + { + windows::print(job, image, rect) + } + #[cfg(not(windows))] + { + let _ = job; + Err(PrintError::Unsupported) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn devmode(size: u16, extra: u16) -> Vec { + let mut b = vec![0u8; usize::from(size) + usize::from(extra)]; + b[DM_SIZE_AT..DM_SIZE_AT + 2].copy_from_slice(&size.to_le_bytes()); + b[DM_EXTRA_AT..DM_EXTRA_AT + 2].copy_from_slice(&extra.to_le_bytes()); + b + } + + #[test] + fn devmode_checks_its_own_sizes_and_round_trips_hex() { + let d = DevMode::from_bytes(devmode(220, 1200)).unwrap(); + assert_eq!(DevMode::from_hex(&d.to_hex()).unwrap(), d); + for bad in [vec![], vec![0; 40], devmode(100, 0), { + let mut b = devmode(220, 10); + b.pop(); + b + }] { + assert!(DevMode::from_bytes(bad).is_err()); + } + for bad in ["", "abc", "zz", &"00".repeat(300)] { + assert!(DevMode::from_hex(bad).is_err(), "{bad}"); + } + } + + #[test] + fn device_rect_is_relative_to_the_printable_corner() { + // A3 at 360 dpi with a 3 mm (8.5 pt) unprintable margin. + let page = Page { paper: (841.89, 1190.55), printable: (8.5, 8.5, 824.89, 1173.55), dpi: (360, 360) }; + assert_eq!(device_rect(&page, (8.5, 8.5, 72.0, 36.0)), (0, 0, 360, 180)); + assert_eq!(device_rect(&page, (72.0, 144.0, 144.0, 72.0)), (318, 678, 720, 360)); + assert_eq!(device_rect(&page, (f64::NAN, f64::INFINITY, 1.0, 1.0)).0, 0); + } + + #[test] + fn print_rejects_empty_or_short_images_before_any_system_call() { + let job = Job { printer: "x", settings: None, title: "t", output_file: None, copies: 1 }; + let short = RgbImage { width: 2, height: 2, data: &[0; 11] }; + assert!(matches!(print(&job, &short, (0.0, 0.0, 10.0, 10.0)), Err(PrintError::Invalid(_)))); + let ok = RgbImage { width: 2, height: 2, data: &[0; 12] }; + assert!(matches!(print(&job, &ok, (0.0, 0.0, 0.0, 10.0)), Err(PrintError::Invalid(_)))); + } +} diff --git a/crates/winprint/src/windows.rs b/crates/winprint/src/windows.rs new file mode 100644 index 0000000000..104333cf03 --- /dev/null +++ b/crates/winprint/src/windows.rs @@ -0,0 +1,378 @@ +//! The Win32 side: winspool (printers, driver settings) and GDI (page geometry, printing). +//! Every `unsafe` block says why it is sound. Buffers the system writes into are `u64`-backed so +//! the structures read from them are aligned. + +use std::ptr::{null, null_mut}; + +use windows_sys::Win32::Foundation::HWND; +use windows_sys::Win32::Graphics::Gdi::{ + BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDCW, DEVMODEW, DIB_RGB_COLORS, DM_IN_BUFFER, DM_IN_PROMPT, DM_OUT_BUFFER, DeleteDC, GetDeviceCaps, HALFTONE, + HDC, HORZRES, LOGPIXELSX, LOGPIXELSY, PHYSICALHEIGHT, PHYSICALOFFSETX, PHYSICALOFFSETY, PHYSICALWIDTH, SRCCOPY, SetBrushOrgEx, SetStretchBltMode, + StretchDIBits, VERTRES, +}; +use windows_sys::Win32::Graphics::Printing::{ + ClosePrinter, DocumentPropertiesW, EnumPrintersW, GetDefaultPrinterW, OpenPrinterW, PRINTER_ENUM_CONNECTIONS, PRINTER_ENUM_LOCAL, PRINTER_HANDLE, + PRINTER_INFO_4W, +}; +use windows_sys::Win32::Storage::Xps::{AbortDoc, DOCINFOW, EndDoc, EndPage, StartDocW, StartPage}; +use windows_sys::Win32::UI::ColorSystem::{ICM_OFF, SetICMMode}; + +use crate::{DevMode, Job, Page, PrintError, Printed, Printer, Result, RgbImage}; + +const IDOK: i32 = 1; +const IDCANCEL: i32 = 2; +/// Wide strings read from the system stop here at the latest. +const MAX_WCHARS: usize = 32 * 1024; + +fn last_error(what: &str) -> PrintError { + PrintError::System(format!("{what} failed: {}", std::io::Error::last_os_error())) +} + +fn wide(s: &str) -> Result> { + if s.contains('\0') { + return Err(PrintError::Invalid("a name contains a NUL character".into())); + } + Ok(s.encode_utf16().chain(Some(0)).collect()) +} + +/// A zeroed, 8-byte aligned buffer of at least `bytes` bytes. +fn aligned(bytes: usize) -> Vec { + vec![0u64; bytes.div_ceil(8).max(1)] +} + +fn bytes_of(buf: &[u64], len: usize) -> Vec { + buf.iter().flat_map(|w| w.to_le_bytes()).take(len).collect() +} + +/// Reads a NUL-terminated wide string. +/// +/// # Safety +/// `p` is null or points to a NUL-terminated UTF-16 string that stays alive for the call. +unsafe fn read_wide(p: *const u16) -> String { + if p.is_null() { + return String::new(); + } + let mut n = 0; + // SAFETY: the caller guarantees a NUL-terminated string; we stop at the NUL (or the cap). + while n < MAX_WCHARS && unsafe { *p.add(n) } != 0 { + n += 1; + } + // SAFETY: the `n` units before the NUL were just read and are valid. + String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(p, n) }) +} + +pub fn printers() -> Result> { + let flags = PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS; + let (mut needed, mut count) = (0u32, 0u32); + // SAFETY: a size query: no buffer (null, 0 bytes); the out-params are valid locals. + unsafe { EnumPrintersW(flags, null(), 4, null_mut(), 0, &mut needed, &mut count) }; + if needed == 0 { + return Ok(Vec::new()); + } + let mut buf = aligned(needed as usize); + // SAFETY: `buf` holds at least `needed` writable bytes, aligned for PRINTER_INFO_4W. + let ok = unsafe { EnumPrintersW(flags, null(), 4, buf.as_mut_ptr().cast(), needed, &mut needed, &mut count) }; + if ok == 0 { + return Err(last_error("listing printers")); + } + let default = default_printer().ok().flatten(); + let infos = buf.as_ptr().cast::(); + let fits = (needed as usize) / std::mem::size_of::(); + let mut out = Vec::new(); + for i in 0..(count as usize).min(fits) { + // SAFETY: the system wrote `count` PRINTER_INFO_4W at the start of `buf` (bounded by + // the buffer size above); their name pointers point into `buf`, which is alive. + let name = unsafe { read_wide((*infos.add(i)).pPrinterName) }; + if !name.is_empty() { + out.push(Printer { default: default.as_deref() == Some(name.as_str()), name }); + } + } + Ok(out) +} + +pub fn default_printer() -> Result> { + let mut len = 0u32; + // SAFETY: a size query with a null buffer; `len` is a valid local. + unsafe { GetDefaultPrinterW(null_mut(), &mut len) }; + if len == 0 || len as usize > MAX_WCHARS { + return Ok(None); + } + let mut buf = vec![0u16; len as usize]; + // SAFETY: `buf` holds `len` writable wide chars. + if unsafe { GetDefaultPrinterW(buf.as_mut_ptr(), &mut len) } == 0 { + return Ok(None); + } + // SAFETY: on success the buffer holds a NUL-terminated name. + Ok(Some(unsafe { read_wide(buf.as_ptr()) })) +} + +/// An open printer handle, closed on drop. +struct OpenPrinter(PRINTER_HANDLE); + +impl OpenPrinter { + fn open(name: &[u16]) -> Result { + let mut h = PRINTER_HANDLE { Value: null_mut() }; + // SAFETY: `name` is NUL-terminated; `h` is a valid out-param; no defaults. + if unsafe { OpenPrinterW(name.as_ptr(), &mut h, null()) } == 0 || h.Value.is_null() { + return Err(last_error("opening the printer")); + } + Ok(OpenPrinter(h)) + } +} + +impl Drop for OpenPrinter { + fn drop(&mut self) { + // SAFETY: the handle came from OpenPrinterW and is closed once. + unsafe { ClosePrinter(self.0) }; + } +} + +/// Settings the driver can take as input: `current`, copied aligned, when it is this printer's. +fn input_settings(printer: &str, current: Option<&DevMode>) -> Option> { + let d = current?; + let b = d.as_bytes(); + // dmDeviceName: the first 32 wide chars (31 + NUL), so long names are truncated. + let device: Vec = b.get(..64)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|c| *c != 0).collect(); + let want: Vec = printer.encode_utf16().take(31).collect(); + if device != want { + return None; + } + let mut buf = aligned(b.len()); + for (i, chunk) in b.chunks(8).enumerate() { + let mut w = [0u8; 8]; + w[..chunk.len()].copy_from_slice(chunk); + if let Some(slot) = buf.get_mut(i) { + *slot = u64::from_le_bytes(w); + } + } + Some(buf) +} + +pub fn properties(printer: &str, current: Option<&DevMode>, parent: Option, prompt: bool) -> Result> { + let name = wide(printer)?; + let p = OpenPrinter::open(&name)?; + let hwnd: HWND = parent.map_or(null_mut(), |h| h as HWND); + // SAFETY: with fmode 0 DocumentPropertiesW only returns the size the settings need. + let needed = unsafe { DocumentPropertiesW(hwnd, p.0, name.as_ptr(), null_mut(), null(), 0) }; + if needed <= 0 || needed as usize > (1 << 20) { + return Err(last_error("reading the printer's settings")); + } + let mut out = aligned(needed as usize); + let input = input_settings(printer, current); + let mut mode = DM_OUT_BUFFER; + if input.is_some() { + mode |= DM_IN_BUFFER; + } + if prompt { + mode |= DM_IN_PROMPT; + } + let inp: *const DEVMODEW = input.as_ref().map_or(null(), |b| b.as_ptr().cast()); + // SAFETY: `out` holds `needed` aligned writable bytes as the size query asked for; `inp` is + // null or an aligned copy of settings written by this printer's driver. + let r = unsafe { DocumentPropertiesW(hwnd, p.0, name.as_ptr(), out.as_mut_ptr().cast(), inp, mode) }; + match r { + IDOK => { + let all = bytes_of(&out, needed as usize); + let word = |at: usize| all.get(at..at + 2).map_or(0, |w| usize::from(u16::from_le_bytes([w[0], w[1]]))); + let len = (word(68) + word(70)).min(all.len()); + DevMode::from_bytes(all.into_iter().take(len).collect()).map(Some) + } + IDCANCEL => Ok(None), + _ => Err(last_error("the printer's settings dialog")), + } +} + +/// A printer device context, deleted on drop. +struct Dc(HDC); + +impl Dc { + fn create(printer: &str, settings: Option<&DevMode>) -> Result { + let name = wide(printer)?; + let dm = input_settings(printer, settings); + let dmp: *const DEVMODEW = dm.as_ref().map_or(null(), |b| b.as_ptr().cast()); + // SAFETY: `name` is NUL-terminated; `dmp` is null or aligned settings from this + // printer's driver, alive for the call. + let hdc = unsafe { CreateDCW(null(), name.as_ptr(), null(), dmp) }; + if hdc.is_null() { + return Err(last_error(&format!("opening printer “{printer}”"))); + } + Ok(Dc(hdc)) + } + + fn cap(&self, index: u32) -> i32 { + // SAFETY: a valid printer DC and a documented capability index. + unsafe { GetDeviceCaps(self.0, index as i32) } + } + + fn page(&self) -> Result { + let (dx, dy) = (self.cap(LOGPIXELSX), self.cap(LOGPIXELSY)); + if dx <= 0 || dy <= 0 { + return Err(PrintError::System("the printer reported no resolution".into())); + } + let (fx, fy) = (72.0 / f64::from(dx), 72.0 / f64::from(dy)); + let (pw, ph) = (self.cap(PHYSICALWIDTH), self.cap(PHYSICALHEIGHT)); + let (ox, oy) = (self.cap(PHYSICALOFFSETX), self.cap(PHYSICALOFFSETY)); + let (hw, vh) = (self.cap(HORZRES), self.cap(VERTRES)); + let (pw, ph) = if pw > 0 && ph > 0 { (pw, ph) } else { (hw, vh) }; + Ok(Page { + paper: (f64::from(pw) * fx, f64::from(ph) * fy), + printable: (f64::from(ox) * fx, f64::from(oy) * fy, f64::from(hw) * fx, f64::from(vh) * fy), + dpi: (dx as u32, dy as u32), + }) + } +} + +impl Drop for Dc { + fn drop(&mut self) { + // SAFETY: the DC came from CreateDCW and is deleted once. + unsafe { DeleteDC(self.0) }; + } +} + +pub fn page(printer: &str, settings: Option<&DevMode>) -> Result { + Dc::create(printer, settings)?.page() +} + +/// RGB rows top-down → a bottom-up 24-bit DIB (BGR, rows padded to 4 bytes). +fn dib(image: &RgbImage<'_>) -> Result<(BITMAPINFO, Vec)> { + let (w, h) = (image.width as usize, image.height as usize); + let stride = (w.checked_mul(3).ok_or_else(|| PrintError::Invalid("image too large".into()))? + 3) & !3; + let total = stride.checked_mul(h).filter(|t| *t <= i32::MAX as usize).ok_or_else(|| PrintError::Invalid("image too large to print in one piece".into()))?; + let mut bits = vec![0u8; total]; + for (y, src) in image.data.chunks_exact(w * 3).enumerate() { + let start = (h - 1 - y) * stride; + let Some(dst) = bits.get_mut(start..start + w * 3) else { continue }; + for (d, s) in dst.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<3>().0) { + *d = [s[2], s[1], s[0]]; + } + } + let header = BITMAPINFOHEADER { + biSize: std::mem::size_of::() as u32, + biWidth: image.width as i32, + biHeight: image.height as i32, + biPlanes: 1, + biBitCount: 24, + biCompression: BI_RGB, + biSizeImage: total as u32, + ..Default::default() + }; + Ok((BITMAPINFO { bmiHeader: header, bmiColors: [Default::default()] }, bits)) +} + +pub fn print(job: &Job<'_>, image: &RgbImage<'_>, rect: (f64, f64, f64, f64)) -> Result { + if image.width > i32::MAX as u32 || image.height > i32::MAX as u32 { + return Err(PrintError::Invalid("image too large".into())); + } + let dc = Dc::create(job.printer, job.settings)?; + let page = dc.page()?; + let (x, y, w, h) = crate::device_rect(&page, rect); + let (bmi, bits) = dib(image)?; + let title = wide(job.title)?; + let output = job.output_file.map(wide).transpose()?; + let info = DOCINFOW { + cbSize: std::mem::size_of::() as i32, + lpszDocName: title.as_ptr(), + lpszOutput: output.as_ref().map_or(null(), |o| o.as_ptr()), + lpszDatatype: null(), + fwType: 0, + }; + // SAFETY: a valid printer DC. ICM off: the pixels are already in the printer's space + // (or deliberately unmanaged), so GDI must not convert them again. + unsafe { SetICMMode(dc.0, ICM_OFF) }; + // SAFETY: a valid DC; HALFTONE resampling needs the brush origin reset afterwards. + unsafe { + SetStretchBltMode(dc.0, HALFTONE); + SetBrushOrgEx(dc.0, 0, 0, null_mut()); + } + // SAFETY: `info` and the strings it points to live until EndDoc/AbortDoc below. + if unsafe { StartDocW(dc.0, &info) } <= 0 { + return Err(last_error("starting the print job")); + } + let fail = |what: &str| { + let e = last_error(what); + // SAFETY: the job was started on this DC. + unsafe { AbortDoc(dc.0) }; + e + }; + for _ in 0..job.copies.clamp(1, 999) { + // SAFETY: inside a started document on a valid DC. + if unsafe { StartPage(dc.0) } <= 0 { + return Err(fail("starting a page")); + } + // SAFETY: `bits` is a bottom-up DIB exactly as `bmi` describes (24-bit, padded rows, + // `biSizeImage` bytes); the source rectangle is the whole image. + let lines = + unsafe { StretchDIBits(dc.0, x, y, w, h, 0, 0, image.width as i32, image.height as i32, bits.as_ptr().cast(), &bmi, DIB_RGB_COLORS, SRCCOPY) }; + if lines <= 0 { + return Err(fail("sending the image to the printer")); + } + // SAFETY: closes the page started above. + if unsafe { EndPage(dc.0) } <= 0 { + return Err(fail("finishing a page")); + } + } + // SAFETY: closes the document started above. + if unsafe { EndDoc(dc.0) } <= 0 { + return Err(last_error("finishing the print job")); + } + Ok(Printed { device_rect: (x, y, w, h), dpi: page.dpi }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dib_is_bottom_up_bgr_with_padded_rows() { + // 2×2: red, green / blue, white. + let data = [255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255]; + let (bmi, bits) = dib(&RgbImage { width: 2, height: 2, data: &data }).unwrap(); + assert_eq!(bmi.bmiHeader.biHeight, 2); + assert_eq!(bits.len(), 16, "6 bytes per row padded to 8"); + // First stored row is the bottom one: blue, white. + assert_eq!(&bits[0..6], &[255, 0, 0, 255, 255, 255]); + assert_eq!(&bits[8..14], &[0, 0, 255, 0, 255, 0]); + } + + #[test] + fn settings_from_another_printer_are_not_passed_to_the_driver() { + let mut b = vec![0u8; 220]; + for (i, c) in "Printer A".encode_utf16().enumerate() { + b[i * 2..i * 2 + 2].copy_from_slice(&c.to_le_bytes()); + } + b[68..70].copy_from_slice(&220u16.to_le_bytes()); + let d = DevMode::from_bytes(b).unwrap(); + assert!(input_settings("Printer A", Some(&d)).is_some()); + assert!(input_settings("Printer B", Some(&d)).is_none()); + assert!(input_settings("Printer A", None).is_none()); + } + + /// A real job through Windows' "Microsoft Print to PDF" driver, written to a file (needs that + /// printer installed; run by hand). + #[test] + #[ignore] + fn prints_through_a_real_driver_to_a_file() { + let out = std::env::temp_dir().join(format!("pc-winprint-{}.pdf", std::process::id())); + let _ = std::fs::remove_file(&out); + let settings = crate::default_settings("Microsoft Print to PDF").unwrap(); + let (w, h) = (300u32, 200u32); + let data: Vec = (0..w * h).flat_map(|i| if (i % w) < w / 2 { [220, 30, 30] } else { [30, 30, 220] }).collect(); + let out_s = out.to_string_lossy().into_owned(); + let job = Job { printer: "Microsoft Print to PDF", settings: Some(&settings), title: "PhotoCraft test", output_file: Some(&out_s), copies: 2 }; + let done = crate::print(&job, &RgbImage { width: w, height: h, data: &data }, (72.0, 72.0, 216.0, 144.0)).unwrap(); + assert_eq!(done.device_rect.2, done.dpi.0 as i32 * 3, "3 inches wide"); + let pdf = std::fs::read(&out).unwrap(); + assert!(pdf.starts_with(b"%PDF"), "the driver wrote a PDF"); + assert!(pdf.len() > 1000, "the page has content"); + let _ = std::fs::remove_file(&out); + } + + /// Lists this machine's printers and their pages (needs real printers; run by hand). + #[test] + #[ignore] + fn lists_real_printers() { + for p in printers().unwrap() { + println!("{}{} {:?}", p.name, if p.default { " (default)" } else { "" }, page(&p.name, None)); + } + } +} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index 2128345148..dcb66f7120 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -46,6 +46,8 @@ pub const TABLE: &[(&str, Class)] = &[ ("adobe-assets", Class::Standalone), // Pen tablet input (the one isolated `unsafe` helper: AppKit interop on macOS). ("tablet", Class::Standalone), + // Windows printing (an isolated `unsafe` helper: winspool and GDI). + ("winprint", Class::Standalone), ("doc", Class::Layer(1)), ("ops", Class::Layer(2)), ("paint", Class::Layer(2)), From ce8d8d950bd1b2e7908af7e41d51c2949f377f3b Mon Sep 17 00:00:00 2001 From: Moiztermind Date: Sun, 11 Oct 2026 15:10:57 +0100 Subject: [PATCH 02/17] winprint: let the driver validate settings; never print on defaults silently The settings check compared the printer name stored in the DEVMODE with the queue name. Windows keeps only 31 characters of it, so a long queue name ("Sublimation - EPSON ET-18100 Series") failed the check and the chosen paper type and quality were silently dropped: the job printed on the driver defaults (plain paper). Settings now go through DocumentProperties(DM_IN_BUFFER | DM_OUT_BUFFER) before CreateDC, so the driver validates them itself, and a refusal is an error instead of a silent fallback. Co-Authored-By: Claude Opus 5.5 --- crates/winprint/src/windows.rs | 79 +++++++++++++++++++++++----------- 1 file changed, 53 insertions(+), 26 deletions(-) diff --git a/crates/winprint/src/windows.rs b/crates/winprint/src/windows.rs index 104333cf03..9b8f8ba16e 100644 --- a/crates/winprint/src/windows.rs +++ b/crates/winprint/src/windows.rs @@ -127,25 +127,21 @@ impl Drop for OpenPrinter { } } -/// Settings the driver can take as input: `current`, copied aligned, when it is this printer's. -fn input_settings(printer: &str, current: Option<&DevMode>) -> Option> { - let d = current?; - let b = d.as_bytes(); - // dmDeviceName: the first 32 wide chars (31 + NUL), so long names are truncated. - let device: Vec = b.get(..64)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|c| *c != 0).collect(); - let want: Vec = printer.encode_utf16().take(31).collect(); - if device != want { - return None; - } +/// `settings` copied into an aligned buffer the driver can read. +/// +/// There is deliberately no check of the printer name stored in the settings: Windows keeps only +/// 31 characters of it, and drivers fill it differently, so a long queue name ("Sublimation - +/// EPSON ET-18100 Series") failed such a check and the settings were silently dropped. The driver +/// itself validates them instead (see [`Dc::create`]). +fn aligned_copy(settings: &DevMode) -> Vec { + let b = settings.as_bytes(); let mut buf = aligned(b.len()); - for (i, chunk) in b.chunks(8).enumerate() { + for (slot, chunk) in buf.iter_mut().zip(b.chunks(8)) { let mut w = [0u8; 8]; w[..chunk.len()].copy_from_slice(chunk); - if let Some(slot) = buf.get_mut(i) { - *slot = u64::from_le_bytes(w); - } + *slot = u64::from_le_bytes(w); } - Some(buf) + buf } pub fn properties(printer: &str, current: Option<&DevMode>, parent: Option, prompt: bool) -> Result> { @@ -158,7 +154,7 @@ pub fn properties(printer: &str, current: Option<&DevMode>, parent: Option) -> Result { let name = wide(printer)?; - let dm = input_settings(printer, settings); + // The driver validates and completes the settings first (DM_IN_BUFFER | DM_OUT_BUFFER, no + // dialog). If it refuses them, that is an error: never print on the defaults instead. + let merged = match settings { + Some(s) => Some( + properties(printer, Some(s), None, false)? + .ok_or_else(|| PrintError::Invalid(format!("printer “{printer}” refused these settings; choose Print Settings… again")))?, + ), + None => None, + }; + let dm = merged.as_ref().map(aligned_copy); let dmp: *const DEVMODEW = dm.as_ref().map_or(null(), |b| b.as_ptr().cast()); // SAFETY: `name` is NUL-terminated; `dmp` is null or aligned settings from this // printer's driver, alive for the call. @@ -335,16 +340,38 @@ mod tests { } #[test] - fn settings_from_another_printer_are_not_passed_to_the_driver() { - let mut b = vec![0u8; 220]; - for (i, c) in "Printer A".encode_utf16().enumerate() { - b[i * 2..i * 2 + 2].copy_from_slice(&c.to_le_bytes()); - } + fn settings_are_copied_aligned_and_intact() { + let mut b: Vec = (0..230u32).map(|i| (i * 7) as u8).collect(); b[68..70].copy_from_slice(&220u16.to_le_bytes()); - let d = DevMode::from_bytes(b).unwrap(); - assert!(input_settings("Printer A", Some(&d)).is_some()); - assert!(input_settings("Printer B", Some(&d)).is_none()); - assert!(input_settings("Printer A", None).is_none()); + b[70..72].copy_from_slice(&10u16.to_le_bytes()); + let d = DevMode::from_bytes(b.clone()).unwrap(); + let buf = aligned_copy(&d); + assert_eq!(buf.as_ptr().align_offset(std::mem::align_of::()), 0); + assert_eq!(bytes_of(&buf, b.len()), b, "no name check, no truncation: the bytes go through as chosen"); + } + + /// Settings chosen for a printer are what the driver prints with: paper and resolution survive + /// the driver's own validation (needs "Microsoft Print to PDF"; run by hand). + #[test] + #[ignore] + fn chosen_settings_reach_the_device_context() { + let printer = "Microsoft Print to PDF"; + let d = crate::default_settings(printer).unwrap(); + let mut b = d.as_bytes().to_vec(); + // dmPaperSize = DMPAPER_A3 (8); dmFields |= DM_PAPERSIZE (2). + b[78..80].copy_from_slice(&8i16.to_le_bytes()); + let fields = u32::from_le_bytes([b[72], b[73], b[74], b[75]]) | 2; + b[72..76].copy_from_slice(&fields.to_le_bytes()); + let a3 = DevMode::from_bytes(b).unwrap(); + let pg = crate::page(printer, Some(&a3)).unwrap(); + assert!((pg.paper.0 - 841.9).abs() < 2.0 && (pg.paper.1 - 1190.6).abs() < 2.0, "A3, not the default: {:?}", pg.paper); + // Landscape (dmOrientation = 2, DM_ORIENTATION = 1): the page comes back wide. + let mut b = a3.as_bytes().to_vec(); + b[76..78].copy_from_slice(&2i16.to_le_bytes()); + let fields = u32::from_le_bytes([b[72], b[73], b[74], b[75]]) | 1; + b[72..76].copy_from_slice(&fields.to_le_bytes()); + let pg = crate::page(printer, Some(&DevMode::from_bytes(b).unwrap())).unwrap(); + assert!((pg.paper.0 - 1190.6).abs() < 2.0 && (pg.paper.1 - 841.9).abs() < 2.0, "landscape A3: {:?}", pg.paper); } /// A real job through Windows' "Microsoft Print to PDF" driver, written to a file (needs that From f9b3c6bd85cf92f266fb22df22354ab3eb0d83f2 Mon Sep 17 00:00:00 2001 From: moiztermind Date: Sun, 11 Oct 2026 19:23:18 +0100 Subject: [PATCH 03/17] winprint: draw crop and registration marks on GDI prints Printer marks (corner/centre crop, registration) were silently dropped on Windows GDI prints -- only the PDF export path drew them, as content-stream vector operators. A workshop test print surfaced the gap. Adds a Marks type to photocraft-winprint and draws the same geometry GDI's way (MoveToEx/LineTo for lines, Ellipse for registration circles) once per page between StretchDIBits and EndPage. The JSON field marksSkipped becomes textSkipped: description and label text are still PDF-only (no font layout in the GDI path yet). Co-Authored-By: Claude Sonnet 5 --- crates/engine/src/print_cmds.rs | 11 +++-- crates/ui-egui/src/file_ui.rs | 8 +++- crates/winprint/src/lib.rs | 23 +++++++++- crates/winprint/src/windows.rs | 79 ++++++++++++++++++++++++++++++--- 4 files changed, 109 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index e3e520ff9e..1b05a6511a 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -444,17 +444,20 @@ pub fn page_rect_top_left(page: &PrintPage) -> (f64, f64, f64, f64) { (x, ph - y - h, w, h) } -/// Prints `page` on a Windows printer. Printer marks, description and labels are PDF-only. +/// Prints `page` on a Windows printer. Corner/centre crop and registration marks are drawn with +/// GDI vector calls, matching the PDF path's geometry; description and label text are still +/// PDF-only (no font/text layout in the GDI path yet). fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: i64) -> Result { let printer = printer_name(p)?; let settings = printer_settings(p)?; let rgb = page_rgb(page)?; let image = photocraft_winprint::RgbImage { width: page.image.width, height: page.image.height, data: &rgb }; - let job = photocraft_winprint::Job { printer: &printer, settings: settings.as_ref(), title, output_file: None, copies: copies.clamp(1, 999) as u32 }; + let marks = photocraft_winprint::Marks { corner_crop: page.marks.corner_crop, center_crop: page.marks.center_crop, registration: page.marks.registration }; + let job = photocraft_winprint::Job { printer: &printer, settings: settings.as_ref(), title, output_file: None, copies: copies.clamp(1, 999) as u32, marks }; let done = photocraft_winprint::print(&job, &image, page_rect_top_left(page)).map_err(other)?; - let marks = page.marks.corner_crop || page.marks.center_crop || page.marks.registration || page.description.is_some() || page.label.is_some(); + let text_skipped = page.description.is_some() || page.label.is_some(); Ok( - json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3], "marksSkipped": marks}), + json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3], "textSkipped": text_skipped}), ) } diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 323519c36b..75592be6d8 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -923,8 +923,12 @@ fn print_confirm(app: &mut PhotocraftApp, f: &Map) -> Result { pub data: &'a [u8], } +/// Printer marks drawn around the image box: corner and centre crop marks, and registration +/// marks. Matches [`photocraft_engine`]'s PDF `Marks`, mirrored here so this crate stays +/// independent of the engine; GDI draws the same geometry with vector line/ellipse calls instead +/// of PDF content stream operators. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Marks { + pub corner_crop: bool, + pub center_crop: bool, + pub registration: bool, +} + +impl Marks { + pub(crate) fn any(self) -> bool { + self.corner_crop || self.center_crop || self.registration + } +} + /// One print job. pub struct Job<'a> { pub printer: &'a str, @@ -116,6 +136,7 @@ pub struct Job<'a> { /// Print to this file instead of the device (drivers that write files, and tests). pub output_file: Option<&'a str>, pub copies: u32, + pub marks: Marks, } /// Where a job went: the image box in device pixels and the device resolution. @@ -254,7 +275,7 @@ mod tests { #[test] fn print_rejects_empty_or_short_images_before_any_system_call() { - let job = Job { printer: "x", settings: None, title: "t", output_file: None, copies: 1 }; + let job = Job { printer: "x", settings: None, title: "t", output_file: None, copies: 1, marks: Marks::default() }; let short = RgbImage { width: 2, height: 2, data: &[0; 11] }; assert!(matches!(print(&job, &short, (0.0, 0.0, 10.0, 10.0)), Err(PrintError::Invalid(_)))); let ok = RgbImage { width: 2, height: 2, data: &[0; 12] }; diff --git a/crates/winprint/src/windows.rs b/crates/winprint/src/windows.rs index 9b8f8ba16e..1ff5de984a 100644 --- a/crates/winprint/src/windows.rs +++ b/crates/winprint/src/windows.rs @@ -6,9 +6,9 @@ use std::ptr::{null, null_mut}; use windows_sys::Win32::Foundation::HWND; use windows_sys::Win32::Graphics::Gdi::{ - BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDCW, DEVMODEW, DIB_RGB_COLORS, DM_IN_BUFFER, DM_IN_PROMPT, DM_OUT_BUFFER, DeleteDC, GetDeviceCaps, HALFTONE, - HDC, HORZRES, LOGPIXELSX, LOGPIXELSY, PHYSICALHEIGHT, PHYSICALOFFSETX, PHYSICALOFFSETY, PHYSICALWIDTH, SRCCOPY, SetBrushOrgEx, SetStretchBltMode, - StretchDIBits, VERTRES, + BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDCW, CreatePen, DEVMODEW, DIB_RGB_COLORS, DM_IN_BUFFER, DM_IN_PROMPT, DM_OUT_BUFFER, DeleteDC, DeleteObject, + Ellipse, GetDeviceCaps, GetStockObject, HALFTONE, HDC, HOLLOW_BRUSH, HORZRES, LOGPIXELSX, LOGPIXELSY, LineTo, MoveToEx, PHYSICALHEIGHT, PHYSICALOFFSETX, + PHYSICALOFFSETY, PHYSICALWIDTH, PS_SOLID, SRCCOPY, SelectObject, SetBrushOrgEx, SetStretchBltMode, StretchDIBits, VERTRES, }; use windows_sys::Win32::Graphics::Printing::{ ClosePrinter, DocumentPropertiesW, EnumPrintersW, GetDefaultPrinterW, OpenPrinterW, PRINTER_ENUM_CONNECTIONS, PRINTER_ENUM_LOCAL, PRINTER_HANDLE, @@ -17,7 +17,7 @@ use windows_sys::Win32::Graphics::Printing::{ use windows_sys::Win32::Storage::Xps::{AbortDoc, DOCINFOW, EndDoc, EndPage, StartDocW, StartPage}; use windows_sys::Win32::UI::ColorSystem::{ICM_OFF, SetICMMode}; -use crate::{DevMode, Job, Page, PrintError, Printed, Printer, Result, RgbImage}; +use crate::{DevMode, Job, Marks, Page, PrintError, Printed, Printer, Result, RgbImage}; const IDOK: i32 = 1; const IDCANCEL: i32 = 2; @@ -264,6 +264,61 @@ fn dib(image: &RgbImage<'_>) -> Result<(BITMAPINFO, Vec)> { Ok((BITMAPINFO { bmiHeader: header, bmiColors: [Default::default()] }, bits)) } +/// Vector marks around the image box `(x, y, w, h)` (device pixels, origin top-left, as GDI +/// draws). Same geometry as `photocraft_engine::print_cmds::marks_ops`'s PDF content stream, with +/// the vertical sense flipped (PDF's origin is bottom-left; GDI's is top-left), scaled from points +/// to device pixels with `dpi` instead of PDF's user-space points. +/// +/// # Safety +/// `dc` is a valid, selected device context for the current page. +unsafe fn draw_marks(dc: HDC, marks: Marks, (x, y, w, h): (i32, i32, i32, i32), dpi: (u32, u32)) -> Result<()> { + let (sx, sy) = (f64::from(dpi.0) / 72.0, f64::from(dpi.1) / 72.0); + let px = |v: f64| v.round() as i32; + let (gap_x, gap_y) = (px(6.0 * sx), px(6.0 * sy)); + let (len_x, len_y) = (px(18.0 * sx), px(18.0 * sy)); + let pen_width = px(0.3 * sx).max(1); + // SAFETY: `dc` is valid; the pen and brush are deleted/restored before returning. + let pen = unsafe { CreatePen(PS_SOLID, pen_width, 0x0000_0000) }; + let hollow = unsafe { GetStockObject(HOLLOW_BRUSH) }; + let old_pen = unsafe { SelectObject(dc, pen) }; + let old_brush = unsafe { SelectObject(dc, hollow) }; + let ok = std::cell::Cell::new(true); + let line = |x0: i32, y0: i32, x1: i32, y1: i32| { + // SAFETY: `dc` is valid for the duration of this call. + ok.set(ok.get() && unsafe { MoveToEx(dc, x0, y0, null_mut()) != 0 && LineTo(dc, x1, y1) != 0 }); + }; + if marks.corner_crop { + for (cx, cy, dx, dy) in [(x, y, -1, -1), (x + w, y, 1, -1), (x, y + h, -1, 1), (x + w, y + h, 1, 1)] { + line(cx + dx * gap_x, cy, cx + dx * (gap_x + len_x), cy); + line(cx, cy + dy * gap_y, cx, cy + dy * (gap_y + len_y)); + } + } + if marks.center_crop { + let (mx, my) = (x + w / 2, y + h / 2); + line(mx, y - gap_y, mx, y - gap_y - len_y); + line(mx, y + h + gap_y, mx, y + h + gap_y + len_y); + line(x - gap_x, my, x - gap_x - len_x, my); + line(x + w + gap_x, my, x + w + gap_x + len_x, my); + } + if marks.registration { + let (rx, ry) = (px(5.0 * sx), px(5.0 * sy)); + let (off_x, off_y) = (gap_x + len_x / 2, gap_y + len_y / 2); + for (cx, cy) in [(x + w / 2, y - off_y), (x + w / 2, y + h + off_y), (x - off_x, y + h / 2), (x + w + off_x, y + h / 2)] { + // SAFETY: `dc` is valid for the duration of this call. + ok.set(ok.get() && unsafe { Ellipse(dc, cx - rx, cy - ry, cx + rx, cy + ry) != 0 }); + line(cx - (rx as f64 * 1.6) as i32, cy, cx + (rx as f64 * 1.6) as i32, cy); + line(cx, cy - (ry as f64 * 1.6) as i32, cx, cy + (ry as f64 * 1.6) as i32); + } + } + // SAFETY: restores the DC's previous pen/brush, then frees the ones created above. + unsafe { + SelectObject(dc, old_pen); + SelectObject(dc, old_brush); + DeleteObject(pen); + } + if ok.get() { Ok(()) } else { Err(last_error("drawing printer marks")) } +} + pub fn print(job: &Job<'_>, image: &RgbImage<'_>, rect: (f64, f64, f64, f64)) -> Result { if image.width > i32::MAX as u32 || image.height > i32::MAX as u32 { return Err(PrintError::Invalid("image too large".into())); @@ -311,6 +366,12 @@ pub fn print(job: &Job<'_>, image: &RgbImage<'_>, rect: (f64, f64, f64, f64)) -> if lines <= 0 { return Err(fail("sending the image to the printer")); } + if job.marks.any() { + // SAFETY: `dc.0` is the valid, started page's device context. + if let Err(e) = unsafe { draw_marks(dc.0, job.marks, (x, y, w, h), page.dpi) } { + return Err(fail(&e.to_string())); + } + } // SAFETY: closes the page started above. if unsafe { EndPage(dc.0) } <= 0 { return Err(fail("finishing a page")); @@ -385,12 +446,20 @@ mod tests { let (w, h) = (300u32, 200u32); let data: Vec = (0..w * h).flat_map(|i| if (i % w) < w / 2 { [220, 30, 30] } else { [30, 30, 220] }).collect(); let out_s = out.to_string_lossy().into_owned(); - let job = Job { printer: "Microsoft Print to PDF", settings: Some(&settings), title: "PhotoCraft test", output_file: Some(&out_s), copies: 2 }; + let marks = crate::Marks { corner_crop: true, center_crop: true, registration: true }; + let job = Job { printer: "Microsoft Print to PDF", settings: Some(&settings), title: "PhotoCraft test", output_file: Some(&out_s), copies: 2, marks }; let done = crate::print(&job, &RgbImage { width: w, height: h, data: &data }, (72.0, 72.0, 216.0, 144.0)).unwrap(); assert_eq!(done.device_rect.2, done.dpi.0 as i32 * 3, "3 inches wide"); let pdf = std::fs::read(&out).unwrap(); assert!(pdf.starts_with(b"%PDF"), "the driver wrote a PDF"); assert!(pdf.len() > 1000, "the page has content"); + // The driver vectorises our GDI line/ellipse calls as real PDF content: a job with every + // mark on is meaningfully bigger than the same image with marks off. + let no_marks_job = Job { marks: crate::Marks::default(), ..job }; + let done2 = crate::print(&no_marks_job, &RgbImage { width: w, height: h, data: &data }, (72.0, 72.0, 216.0, 144.0)).unwrap(); + let _ = done2; + let pdf_no_marks = std::fs::read(&out).unwrap(); + assert!(pdf.len() > pdf_no_marks.len() + 100, "marks add vector content: {} vs {}", pdf.len(), pdf_no_marks.len()); let _ = std::fs::remove_file(&out); } From 9f7f8b7a7b9ece8ab024d6f0194d11805d1b6bfa Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 13 Oct 2026 01:51:12 +0200 Subject: [PATCH 04/17] Check that driver copy fields remain active after validation --- crates/winprint/src/lib.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/winprint/src/lib.rs b/crates/winprint/src/lib.rs index e263926e73..e0c5729881 100644 --- a/crates/winprint/src/lib.rs +++ b/crates/winprint/src/lib.rs @@ -94,7 +94,10 @@ impl DevMode { #[cfg(any(windows, test))] pub(crate) fn has_manual_copies(&self) -> bool { - self.0.get(86..88) == Some(1i16.to_le_bytes().as_slice()) && self.0.get(100..102) == Some(0i16.to_le_bytes().as_slice()) + let fields = self.0.get(72..76).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_le_bytes); + fields.is_some_and(|f| f & 0x100 != 0) + && self.0.get(86..88) == Some(1i16.to_le_bytes().as_slice()) + && self.0.get(100..102) == Some(0i16.to_le_bytes().as_slice()) } /// Hex, for JSON parameters and remembered print settings. @@ -296,6 +299,9 @@ mod tests { assert!(!original.has_manual_copies()); assert_eq!(&normalized.as_bytes()[220..], &original.as_bytes()[220..]); assert_eq!(normalized.for_manual_copies().unwrap(), normalized); + let mut ignored = normalized.as_bytes().to_vec(); + ignored[72..76].copy_from_slice(&0u32.to_le_bytes()); + assert!(!DevMode::from_bytes(ignored).unwrap().has_manual_copies(), "a driver must advertise that it accepts dmCopies"); } #[test] @@ -314,5 +320,8 @@ mod tests { assert!(matches!(print(&job, &short, (0.0, 0.0, 10.0, 10.0)), Err(PrintError::Invalid(_)))); let ok = RgbImage { width: 2, height: 2, data: &[0; 12] }; assert!(matches!(print(&job, &ok, (0.0, 0.0, 0.0, 10.0)), Err(PrintError::Invalid(_)))); + for rect in [(f64::NAN, 0.0, 10.0, 10.0), (0.0, 0.0, f64::INFINITY, 10.0)] { + assert!(matches!(print(&job, &ok, rect), Err(PrintError::Invalid(_)))); + } } } From 4a730912c0dd3868b3c4933f8734ca03e9698cae Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 13 Oct 2026 01:53:16 +0200 Subject: [PATCH 05/17] Preserve PDF text and CMYK paths and reject native layout mismatches --- crates/engine/src/print_cmds.rs | 20 +++++++++++++++++--- crates/engine/src/print_cmds/tests.rs | 15 +++++++++++++++ crates/winprint/src/windows.rs | 11 +++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index dd7f85971c..4093c8dd35 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -391,13 +391,16 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { // Windows has no `lp`: print through the driver (GDI, ICM off) instead of spooling a PDF. // Sending follows the shared command contract; fuzz tests explicitly request dryRun. // The worker returns its result before repeat settings and hooks are applied once. - if cfg!(windows) && send && !dry && output.is_none() { + if cfg!(windows) && send && !dry && output.is_none() && native_rgb_compatible(&page) { let printed = print_windows(&page, p, &doc.name, copies)?; return Ok(json!({ "pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, "copies": copies, "command": Value::Null, "sent": true, "spooler": printed, "color": color, })); } + if cfg!(windows) && send && !dry && output.is_none() && printer_settings(p)?.is_some() { + return Err(other("CMYK profiles and description/label text use PDF composition; these native driver settings cannot be applied. Save as PDF, or clear the driver settings to use PDF printing.")); + } let pdf = print_pdf(&page); let job = craft_print::Job { printer: p.get("printer").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string), @@ -427,6 +430,14 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { ) } +/// Keep CMYK output profiles and page text on the existing PDF composition path. GDI currently +/// draws RGB/gray and vector marks only; it must never silently omit requested page content. +fn native_rgb_compatible(page: &PrintPage) -> bool { + matches!(page.image.channels, 1 | 3) + && page.description.as_deref().is_none_or(str::is_empty) + && page.label.as_deref().is_none_or(str::is_empty) +} + /// Print One Copy repeats these. fn remember_print(s: &mut Session, p: &Value) { let mut remembered = p.clone(); @@ -490,14 +501,17 @@ pub fn page_rect_top_left(page: &PrintPage) -> (f64, f64, f64, f64) { fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: u32) -> Result { let printer = printer_name(p)?; let settings = printer_settings(p)?; + let device_page = photocraft_winprint::page(&printer, settings.as_ref()).map_err(other)?; + if (device_page.paper.0 - page.paper.0).abs() > 2.0 || (device_page.paper.1 - page.paper.1).abs() > 2.0 { + return Err(other("the driver paper or orientation differs from the print layout; choose the matching paper in Print Settings before printing")); + } let rgb = page_rgb(page)?; let image = photocraft_winprint::RgbImage { width: page.image.width, height: page.image.height, data: &rgb }; let marks = photocraft_winprint::Marks { corner_crop: page.marks.corner_crop, center_crop: page.marks.center_crop, registration: page.marks.registration }; let job = photocraft_winprint::Job { printer: &printer, settings: settings.as_ref(), title, output_file: None, copies: copies.clamp(1, 999), marks }; let done = photocraft_winprint::print(&job, &image, page_rect_top_left(page)).map_err(other)?; - let text_skipped = page.description.is_some() || page.label.is_some(); Ok( - json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3], "textSkipped": text_skipped}), + json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3]}), ) } diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index c15b7c6562..b240efb48a 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -175,6 +175,21 @@ fn windows_print_image_is_rgb_mirrored_for_emulsion_down() { assert_eq!(page_rect_top_left(&page_of(3, vec![0; 6], true)), (356.0, 528.0, 144.0, 72.0)); } +#[test] +fn native_rgb_route_preserves_pdf_only_color_and_page_content() { + let mut page = page_of(3, vec![0; 6], false); + assert!(native_rgb_compatible(&page)); + page.label = Some("Print Me".into()); + assert!(!native_rgb_compatible(&page)); + page.label = None; + page.description = Some("Proof description".into()); + assert!(!native_rgb_compatible(&page)); + page.description = Some(String::new()); + assert!(native_rgb_compatible(&page)); + assert!(!native_rgb_compatible(&page_of(4, vec![0; 8], false))); + assert!(native_rgb_compatible(&page_of(1, vec![0; 2], false))); +} + #[test] fn printer_commands_answer_without_a_document_and_reject_bad_settings() { let mut s = Session::new(); diff --git a/crates/winprint/src/windows.rs b/crates/winprint/src/windows.rs index ec9bd784fb..0e00338668 100644 --- a/crates/winprint/src/windows.rs +++ b/crates/winprint/src/windows.rs @@ -458,6 +458,11 @@ mod tests { let out = std::env::temp_dir().join(format!("pc-winprint-{}.pdf", std::process::id())); let _ = std::fs::remove_file(&out); let settings = crate::default_settings("Microsoft Print to PDF").unwrap(); + let mut bytes = settings.as_bytes().to_vec(); + bytes[86..88].copy_from_slice(&5i16.to_le_bytes()); + let fields = u32::from_le_bytes(bytes[72..76].try_into().unwrap()) | 0x100; + bytes[72..76].copy_from_slice(&fields.to_le_bytes()); + let settings = DevMode::from_bytes(bytes).unwrap(); let (w, h) = (300u32, 200u32); let data: Vec = (0..w * h).flat_map(|i| if (i % w) < w / 2 { [220, 30, 30] } else { [30, 30, 220] }).collect(); let out_s = out.to_string_lossy().into_owned(); @@ -475,6 +480,12 @@ mod tests { let _ = done2; let pdf_no_marks = std::fs::read(&out).unwrap(); assert!(pdf.len() > pdf_no_marks.len() + 100, "marks add vector content: {} vs {}", pdf.len(), pdf_no_marks.len()); + if let Ok(evidence) = std::env::var("PHOTOCRAFT_WINPRINT_TEST_EVIDENCE") { + let evidence = std::path::Path::new(&evidence); + std::fs::create_dir_all(evidence).unwrap(); + std::fs::write(evidence.join("copies2-driver5-marks.pdf"), &pdf).unwrap(); + std::fs::write(evidence.join("copies2-driver5-no-marks.pdf"), &pdf_no_marks).unwrap(); + } let _ = std::fs::remove_file(&out); } From 3702555aa9ded0393aa70cb1e81ae92a679d65b6 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 13 Oct 2026 02:02:13 +0200 Subject: [PATCH 06/17] Make native RGB color policy explicit and preserve embedded profiles --- crates/engine/src/print_cmds.rs | 23 ++++++++++++++--- crates/engine/src/print_cmds/tests.rs | 16 +++++++----- crates/winprint/src/lib.rs | 14 ++++++++++- crates/winprint/src/windows.rs | 36 +++++++++++++++++++++------ 4 files changed, 70 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 4093c8dd35..aa8f7d2a8a 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -391,7 +391,8 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { // Windows has no `lp`: print through the driver (GDI, ICM off) instead of spooling a PDF. // Sending follows the shared command contract; fuzz tests explicitly request dryRun. // The worker returns its result before repeat settings and hooks are applied once. - if cfg!(windows) && send && !dry && output.is_none() && native_rgb_compatible(&page) { + let handling = p.get("colorHandling").and_then(Value::as_str).unwrap_or("printerManages"); + if cfg!(windows) && send && !dry && output.is_none() && native_rgb_compatible(&page, handling) { let printed = print_windows(&page, p, &doc.name, copies)?; return Ok(json!({ "pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, @@ -399,7 +400,7 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { })); } if cfg!(windows) && send && !dry && output.is_none() && printer_settings(p)?.is_some() { - return Err(other("CMYK profiles and description/label text use PDF composition; these native driver settings cannot be applied. Save as PDF, or clear the driver settings to use PDF printing.")); + return Err(other("the selected color profile or page text requires PDF printing. Save as PDF, or clear Print Settings to use PDF printing.")); } let pdf = print_pdf(&page); let job = craft_print::Job { @@ -432,8 +433,9 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { /// Keep CMYK output profiles and page text on the existing PDF composition path. GDI currently /// draws RGB/gray and vector marks only; it must never silently omit requested page content. -fn native_rgb_compatible(page: &PrintPage) -> bool { +fn native_rgb_compatible(page: &PrintPage, handling: &str) -> bool { matches!(page.image.channels, 1 | 3) + && (page.image.icc.is_none() || matches!(handling, "photocraftManages" | "photoshopManages" | "noColorManagement")) && page.description.as_deref().is_none_or(str::is_empty) && page.label.as_deref().is_none_or(str::is_empty) } @@ -508,7 +510,20 @@ fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: u32) -> Resul let rgb = page_rgb(page)?; let image = photocraft_winprint::RgbImage { width: page.image.width, height: page.image.height, data: &rgb }; let marks = photocraft_winprint::Marks { corner_crop: page.marks.corner_crop, center_crop: page.marks.center_crop, registration: page.marks.registration }; - let job = photocraft_winprint::Job { printer: &printer, settings: settings.as_ref(), title, output_file: None, copies: copies.clamp(1, 999), marks }; + let color_policy = match p.get("colorHandling").and_then(Value::as_str) { + Some("photocraftManages" | "photoshopManages") => photocraft_winprint::ColorPolicy::ApplicationManaged, + Some("noColorManagement") => photocraft_winprint::ColorPolicy::Unmanaged, + _ => photocraft_winprint::ColorPolicy::DriverManaged, + }; + let job = photocraft_winprint::Job { + printer: &printer, + settings: settings.as_ref(), + title, + output_file: None, + copies: copies.clamp(1, 999), + color_policy, + marks, + }; let done = photocraft_winprint::print(&job, &image, page_rect_top_left(page)).map_err(other)?; Ok( json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3]}), diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index b240efb48a..023829d72d 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -178,16 +178,20 @@ fn windows_print_image_is_rgb_mirrored_for_emulsion_down() { #[test] fn native_rgb_route_preserves_pdf_only_color_and_page_content() { let mut page = page_of(3, vec![0; 6], false); - assert!(native_rgb_compatible(&page)); + assert!(native_rgb_compatible(&page, "printerManages")); page.label = Some("Print Me".into()); - assert!(!native_rgb_compatible(&page)); + assert!(!native_rgb_compatible(&page, "printerManages")); page.label = None; page.description = Some("Proof description".into()); - assert!(!native_rgb_compatible(&page)); + assert!(!native_rgb_compatible(&page, "printerManages")); page.description = Some(String::new()); - assert!(native_rgb_compatible(&page)); - assert!(!native_rgb_compatible(&page_of(4, vec![0; 8], false))); - assert!(native_rgb_compatible(&page_of(1, vec![0; 2], false))); + assert!(native_rgb_compatible(&page, "printerManages")); + page.image.icc = Some(vec![1, 2, 3]); + assert!(!native_rgb_compatible(&page, "printerManages"), "preserve embedded source ICC in the PDF route"); + assert!(native_rgb_compatible(&page, "photocraftManages")); + assert!(native_rgb_compatible(&page, "photoshopManages")); + assert!(!native_rgb_compatible(&page_of(4, vec![0; 8], false), "photocraftManages")); + assert!(native_rgb_compatible(&page_of(1, vec![0; 2], false), "noColorManagement")); } #[test] diff --git a/crates/winprint/src/lib.rs b/crates/winprint/src/lib.rs index e0c5729881..ef20e28ce1 100644 --- a/crates/winprint/src/lib.rs +++ b/crates/winprint/src/lib.rs @@ -150,6 +150,17 @@ impl Marks { } } +/// One print job. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ColorPolicy { + /// The driver applies its color settings to the RGB image. + DriverManaged, + /// The caller has converted the pixels into the printer's RGB space. + ApplicationManaged, + /// The caller deliberately requests no DC color correction. + Unmanaged, +} + /// One print job. pub struct Job<'a> { pub printer: &'a str, @@ -159,6 +170,7 @@ pub struct Job<'a> { /// Print to this file instead of the device (drivers that write files, and tests). pub output_file: Option<&'a str>, pub copies: u32, + pub color_policy: ColorPolicy, pub marks: Marks, } @@ -315,7 +327,7 @@ mod tests { #[test] fn print_rejects_empty_or_short_images_before_any_system_call() { - let job = Job { printer: "x", settings: None, title: "t", output_file: None, copies: 1, marks: Marks::default() }; + let job = Job { printer: "x", settings: None, title: "t", output_file: None, copies: 1, color_policy: ColorPolicy::Unmanaged, marks: Marks::default() }; let short = RgbImage { width: 2, height: 2, data: &[0; 11] }; assert!(matches!(print(&job, &short, (0.0, 0.0, 10.0, 10.0)), Err(PrintError::Invalid(_)))); let ok = RgbImage { width: 2, height: 2, data: &[0; 12] }; diff --git a/crates/winprint/src/windows.rs b/crates/winprint/src/windows.rs index 0e00338668..103309dcd0 100644 --- a/crates/winprint/src/windows.rs +++ b/crates/winprint/src/windows.rs @@ -15,9 +15,9 @@ use windows_sys::Win32::Graphics::Printing::{ PRINTER_INFO_4W, }; use windows_sys::Win32::Storage::Xps::{AbortDoc, DOCINFOW, EndDoc, EndPage, StartDocW, StartPage}; -use windows_sys::Win32::UI::ColorSystem::{ICM_OFF, SetICMMode}; +use windows_sys::Win32::UI::ColorSystem::{ICM_DONE_OUTSIDEDC, ICM_OFF, SetICMMode}; -use crate::{DevMode, Job, Marks, Page, PrintError, Printed, Printer, Result, RgbImage}; +use crate::{ColorPolicy, DevMode, Job, Marks, Page, PrintError, Printed, Printer, Result, RgbImage}; const IDOK: i32 = 1; const IDCANCEL: i32 = 2; @@ -349,11 +349,17 @@ pub fn print(job: &Job<'_>, image: &RgbImage<'_>, rect: (f64, f64, f64, f64)) -> lpszDatatype: null(), fwType: 0, }; - // SAFETY: a valid printer DC. ICM off: the pixels are already in the printer's space - // (or deliberately unmanaged), so GDI must not convert them again. - if unsafe { SetICMMode(dc.0, ICM_OFF) } == 0 { - return Err(last_error("disabling GDI color management")); - } + let color_mode = match job.color_policy { + ColorPolicy::DriverManaged => ICM_OFF, + // ICM_OFF enables old-style halftone correction. Pixels converted by the caller + // need both DC conversion and that correction off (Microsoft SetICMMode contract). + ColorPolicy::ApplicationManaged | ColorPolicy::Unmanaged => ICM_DONE_OUTSIDEDC, + }; + let set_color_mode = || { + // SAFETY: a valid printer DC and a documented SetICMMode value. + if unsafe { SetICMMode(dc.0, color_mode) } == 0 { Err(last_error("setting GDI color policy")) } else { Ok(()) } + }; + set_color_mode()?; // SAFETY: a valid DC; HALFTONE resampling needs the brush origin reset afterwards. unsafe { SetStretchBltMode(dc.0, HALFTONE); @@ -374,6 +380,12 @@ pub fn print(job: &Job<'_>, image: &RgbImage<'_>, rect: (f64, f64, f64, f64)) -> if unsafe { StartPage(dc.0) } <= 0 { return Err(fail("starting a page")); } + // StartPage saves/restores DC state. Reapply the policy for each page, before pixels. + if let Err(error) = set_color_mode() { + // SAFETY: this DC owns the document started above. + unsafe { AbortDoc(dc.0) }; + return Err(error); + } // SAFETY: `bits` is a bottom-up DIB exactly as `bmi` describes (24-bit, padded rows, // `biSizeImage` bytes); the source rectangle is the whole image. let lines = @@ -467,7 +479,15 @@ mod tests { let data: Vec = (0..w * h).flat_map(|i| if (i % w) < w / 2 { [220, 30, 30] } else { [30, 30, 220] }).collect(); let out_s = out.to_string_lossy().into_owned(); let marks = crate::Marks { corner_crop: true, center_crop: true, registration: true }; - let job = Job { printer: "Microsoft Print to PDF", settings: Some(&settings), title: "PhotoCraft test", output_file: Some(&out_s), copies: 2, marks }; + let job = Job { + printer: "Microsoft Print to PDF", + settings: Some(&settings), + title: "PhotoCraft test", + output_file: Some(&out_s), + copies: 2, + color_policy: ColorPolicy::ApplicationManaged, + marks, + }; let done = crate::print(&job, &RgbImage { width: w, height: h, data: &data }, (72.0, 72.0, 216.0, 144.0)).unwrap(); assert_eq!(done.device_rect.2, done.dpi.0 as i32 * 3, "3 inches wide"); let pdf = std::fs::read(&out).unwrap(); From d9bc5a8cd51bf967aede79d41a96e2e15328c00d Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 13 Oct 2026 02:56:11 +0200 Subject: [PATCH 07/17] Use shared native print transport and keep page composition in PhotoCraft --- Cargo.lock | 1229 ++++++++++++++++- Cargo.toml | 3 +- crates/engine/Cargo.toml | 1 - crates/engine/src/print_cmds.rs | 33 +- crates/engine/src/print_cmds/tests.rs | 4 +- crates/engine/src/print_cmds/windows_marks.rs | 47 + crates/ui-egui/Cargo.toml | 2 +- crates/ui-egui/src/file_ui.rs | 10 +- crates/winprint/Cargo.toml | 26 - crates/winprint/src/lib.rs | 339 ----- crates/winprint/src/windows.rs | 520 ------- xtask/src/layers.rs | 1 - 12 files changed, 1288 insertions(+), 927 deletions(-) create mode 100644 crates/engine/src/print_cmds/windows_marks.rs delete mode 100644 crates/winprint/Cargo.toml delete mode 100644 crates/winprint/src/lib.rs delete mode 100644 crates/winprint/src/windows.rs diff --git a/Cargo.lock b/Cargo.lock index 08d317ce94..9ba37f36a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -550,12 +550,48 @@ dependencies = [ "arrayvec", ] +[[package]] +name = "aws-lc-rs" +version = "1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +dependencies = [ + "aws-lc-sys", + "untrusted 0.7.1", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bindgen" version = "0.72.1" @@ -645,7 +681,7 @@ dependencies = [ "cc", "cfg-if", "constant_time_eq", - "cpufeatures", + "cpufeatures 0.3.1", ] [[package]] @@ -654,6 +690,15 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -885,7 +930,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.3.1", "rand_core 0.10.1", ] @@ -896,8 +941,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", "serde", + "wasm-bindgen", "windows-link", ] @@ -973,6 +1020,39 @@ dependencies = [ "error-code", ] +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmpv2" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "961b955a666e25ee5a1091d219128d6e6401e3dab84efb1a2bf6b4035d797b39" +dependencies = [ + "crmf", + "der", + "spki", + "x509-cert", +] + +[[package]] +name = "cms" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" +dependencies = [ + "const-oid", + "der", + "spki", + "x509-cert", +] + [[package]] name = "codespan-reporting" version = "0.13.1" @@ -1028,6 +1108,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "constant_time_eq" version = "0.4.2" @@ -1103,6 +1189,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "core_maths" version = "0.1.1" @@ -1112,6 +1204,15 @@ dependencies = [ "libm", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -1124,9 +1225,14 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d991bf6792f8ade99c51358bf3c1d902c8cd96b5#d991bf6792f8ade99c51358bf3c1d902c8cd96b5" +source = "git+https://github.com/storytold/craft-libs?rev=ee70afc29a41bc50f2a55affa9aa2c62e0d28e3a#ee70afc29a41bc50f2a55affa9aa2c62e0d28e3a" dependencies = [ + "craft-winprint-gdi", + "miniz_oxide 0.8.9", + "roxmltree", "tempfile", + "winprint", + "winsafe", ] [[package]] @@ -1138,6 +1244,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-winprint-gdi" +version = "0.1.0" +source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1181,6 +1295,18 @@ dependencies = [ "itertools 0.10.5", ] +[[package]] +name = "crmf" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36fe21b96d5b87f5de4b5b7202ec41c00110ac817ce6728fe75fb2fe5962ed92" +dependencies = [ + "cms", + "der", + "spki", + "x509-cert", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -1221,6 +1347,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1267,6 +1403,30 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "dify" version = "0.8.0" @@ -1280,6 +1440,16 @@ dependencies = [ "rayon", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1394,6 +1564,12 @@ dependencies = [ "linux-raw-sys 0.9.4", ] +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "dyn-clone" version = "1.0.20" @@ -1578,6 +1754,20 @@ dependencies = [ "serde", ] +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "endi" version = "1.1.1" @@ -1797,6 +1987,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -1809,6 +2009,12 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.10" @@ -1826,6 +2032,28 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" +[[package]] +name = "fmt-derive" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cb4a4b45c26455885f8b462db12978e51f60cc914337bccb9a36faf93410169" +dependencies = [ + "fmt-derive-proc", +] + +[[package]] +name = "fmt-derive-proc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7704da0760734344ce8753f15b21e97c6be85dc5a8f2c3a963fbd042b3380d23" +dependencies = [ + "proc-macro-crate", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "fmv-macos-events" version = "0.1.0" @@ -1948,6 +2176,12 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "futures" version = "0.3.34" @@ -2073,6 +2307,16 @@ dependencies = [ "libc", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -2092,6 +2336,19 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -2111,9 +2368,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -2279,6 +2538,25 @@ dependencies = [ "euclid", ] +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -2359,6 +2637,107 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -3188,6 +3567,12 @@ dependencies = [ "imgref", ] +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "maybe-owned" version = "0.3.4" @@ -3237,6 +3622,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3302,6 +3693,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "naga" version = "30.0.1" @@ -3997,6 +4394,12 @@ dependencies = [ "libc", ] +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + [[package]] name = "orbclient" version = "0.3.55" @@ -4116,6 +4519,25 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "peniko" version = "0.6.1" @@ -4258,7 +4680,7 @@ dependencies = [ name = "photocraft-automation" version = "0.8.2" dependencies = [ - "base64", + "base64 0.22.1", "cap-std", "getrandom 0.3.4", "photocraft-codecs", @@ -4379,7 +4801,6 @@ dependencies = [ "photocraft-raw", "photocraft-text", "photocraft-vector", - "photocraft-winprint", "rayon", "roxmltree", "serde", @@ -4579,7 +5000,8 @@ dependencies = [ name = "photocraft-ui-egui" version = "0.8.2" dependencies = [ - "base64", + "base64 0.22.1", + "craft-print", "craft-ui", "eframe", "egui", @@ -4607,7 +5029,6 @@ dependencies = [ "photocraft-testkit", "photocraft-text", "photocraft-vector", - "photocraft-winprint", "rayon", "serde", "serde_json", @@ -4649,13 +5070,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "photocraft-winprint" -version = "0.8.2" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "pico-args" version = "0.5.0" @@ -4856,6 +5270,30 @@ dependencies = [ "toml_edit", ] +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -4962,6 +5400,63 @@ dependencies = [ "memchr", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.52.0", +] + [[package]] name = "quote" version = "1.0.47" @@ -5014,6 +5509,12 @@ dependencies = [ "rand_core 0.9.5", ] +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + [[package]] name = "rand_core" version = "0.9.5" @@ -5029,6 +5530,15 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "rand_xorshift" version = "0.4.0" @@ -5239,6 +5749,49 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "resvg" version = "0.45.1" @@ -5292,6 +5845,20 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted 0.9.0", + "windows-sys 0.52.0", +] + [[package]] name = "rmcp" version = "3.5.0" @@ -5419,6 +5986,81 @@ dependencies = [ "rustix 1.1.5", ] +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted 0.9.0", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -5464,6 +6106,18 @@ dependencies = [ "twox-hash", ] +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "ryu-js" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" + [[package]] name = "same-file" version = "1.0.6" @@ -5473,6 +6127,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "schemars" version = "1.2.2" @@ -5511,6 +6174,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -5577,6 +6263,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_json_canonicalizer" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe52319a927259afbfa5180c5157cd8167edfd3e8c254f9558c7fef44c5649f2" +dependencies = [ + "ryu-js", + "serde", + "serde_json", +] + [[package]] name = "serde_repr" version = "0.1.21" @@ -5597,6 +6294,40 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + [[package]] name = "shlex" version = "1.3.0" @@ -5619,6 +6350,175 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "sigstore-bundle" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7dc53c8a941858d01479622dbb7650aaa2ee0ca1fb58fb6cdddbfc3064abbb" +dependencies = [ + "base64 0.22.1", + "hex", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-rekor", + "sigstore-tsa", + "sigstore-types", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-crypto" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "const-oid", + "der", + "digest", + "pem", + "rand_core 0.10.1", + "sha2", + "signature", + "sigstore-types", + "spki", + "thiserror 2.0.21", + "tracing", + "x509-cert", +] + +[[package]] +name = "sigstore-merkle" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c0d53558825c77716855c13794306fff766854c1bf92948e77d7890da3f2455" +dependencies = [ + "base64 0.22.1", + "hex", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-rekor" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "641fdaaa40d0cd6e249cf1671c2240beff1a3ece578062cf43e750779e8db2b3" +dependencies = [ + "base64 0.22.1", + "hex", + "reqwest", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-types", + "thiserror 2.0.21", + "url", +] + +[[package]] +name = "sigstore-trust-root" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6b0d2550f05c096400066e858db13d91f9de3b750a7541fb1291c1dc80ca290" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "rustls-pki-types", + "serde", + "serde_json", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", + "x509-cert", +] + +[[package]] +name = "sigstore-tsa" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bc86c8abc1ece6832236e7e34e9baebb5d4d40490c0332b814a0d8624ca7255" +dependencies = [ + "aws-lc-rs", + "base64 0.22.1", + "chrono", + "cmpv2", + "cms", + "const-oid", + "der", + "hex", + "rand 0.10.3", + "reqwest", + "rustls-pki-types", + "rustls-webpki", + "sigstore-crypto", + "sigstore-types", + "thiserror 2.0.21", + "tracing", + "x509-cert", + "x509-tsp", +] + +[[package]] +name = "sigstore-types" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8d870c9bcfdf83396ac2bd2d6a23c5d09ec02cc9fda50fa1cbb3dd71a9bee53" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "pem", + "serde", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "sigstore-verify" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d30aff69036e4579b416956e9ba68cec45b793116f78f10842d04c7f8b924bab" +dependencies = [ + "base64 0.22.1", + "chrono", + "cms", + "const-oid", + "hex", + "pem", + "rustls-pki-types", + "rustls-webpki", + "serde", + "serde_json", + "serde_json_canonicalizer", + "sigstore-bundle", + "sigstore-crypto", + "sigstore-merkle", + "sigstore-rekor", + "sigstore-trust-root", + "sigstore-tsa", + "sigstore-types", + "thiserror 2.0.21", + "tls_codec", + "tracing", + "x509-cert", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -5796,6 +6696,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -5839,6 +6749,33 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "svgtypes" version = "0.15.3" @@ -5849,6 +6786,16 @@ dependencies = [ "siphasher", ] +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + [[package]] name = "syn" version = "2.0.119" @@ -5871,6 +6818,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synstructure" version = "0.14.0" @@ -5891,6 +6847,27 @@ dependencies = [ "libc", ] +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "system-deps" version = "7.0.8" @@ -5904,6 +6881,17 @@ dependencies = [ "version-compare", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "target-lexicon" version = "0.13.5" @@ -6039,6 +7027,27 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tokio" version = "1.53.1" @@ -6065,6 +7074,16 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.19" @@ -6141,6 +7160,51 @@ version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + [[package]] name = "tracing" version = "0.1.44" @@ -6194,6 +7258,12 @@ dependencies = [ "petgraph", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "ttf-parser" version = "0.25.1" @@ -6224,6 +7294,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "uds_windows" version = "1.2.1" @@ -6301,6 +7377,18 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -6319,7 +7407,7 @@ version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" dependencies = [ - "base64", + "base64 0.22.1", "data-url", "flate2", "fontdb", @@ -6427,6 +7515,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -6761,6 +7858,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" @@ -7048,6 +8154,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -7300,6 +8417,27 @@ dependencies = [ "memchr", ] +[[package]] +name = "winprint" +version = "0.2.1" +source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49" +dependencies = [ + "flate2", + "fmt-derive", + "reqwest", + "scopeguard", + "sigstore-trust-root", + "sigstore-types", + "sigstore-verify", + "strum", + "tar", + "thiserror 2.0.21", + "windows", + "windows-core", + "windows-implement", + "xml", +] + [[package]] name = "winresource" version = "0.1.31" @@ -7388,6 +8526,41 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid", + "der", + "sha1", + "signature", + "spki", + "tls_codec", +] + +[[package]] +name = "x509-tsp" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5ceece934a21607055b7ac5c25adb56a2ff559804b10705dc674d1d838c15e1" +dependencies = [ + "cmpv2", + "cms", + "der", +] + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.5", +] + [[package]] name = "xcap" version = "0.9.8" @@ -7455,6 +8628,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" +[[package]] +name = "xml" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f45bb2c13fec6a6cb4c0f76a7e94839e110a14ec803ec2940777a94c347bc52" + [[package]] name = "xml-rs" version = "0.8.29" @@ -7652,6 +8831,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 408997d343..54bd1a3a05 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,10 +36,9 @@ photocraft-engine = { path = "crates/engine" } photocraft-ui-egui = { path = "crates/ui-egui" } photocraft-testkit = { path = "crates/testkit" } photocraft-tablet = { path = "crates/tablet" } -photocraft-winprint = { path = "crates/winprint" } # external -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "ee70afc29a41bc50f2a55affa9aa2c62e0d28e3a" } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 2f144ce57e..741d927a3f 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -19,7 +19,6 @@ photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } photocraft-compose = { workspace = true } -photocraft-winprint = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index aa8f7d2a8a..419ffd55aa 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -14,6 +14,8 @@ use std::io::Write as _; +mod windows_marks; + use photocraft_color::ColorMode; use photocraft_doc::{Document, LayerContent, SmartSource}; use serde_json::{Value, json}; @@ -457,13 +459,13 @@ fn printer_name(p: &Value) -> Result { if let Some(name) = p.get("printer").and_then(Value::as_str).filter(|v| !v.trim().is_empty()) { return Ok(name.to_string()); } - photocraft_winprint::default_printer().map_err(other)?.ok_or_else(|| other("no printer chosen and no default printer is set")) + craft_print::rgb::default_printer().map_err(other)?.ok_or_else(|| other("no printer chosen and no default printer is set")) } /// The driver settings chosen with Print Settings… (`printerSettings`, hex), when any. -fn printer_settings(p: &Value) -> Result> { +fn printer_settings(p: &Value) -> Result> { match p.get("printerSettings").and_then(Value::as_str).filter(|v| !v.is_empty()) { - Some(hex) => photocraft_winprint::DevMode::from_hex(hex).map(Some).map_err(|e| bad("file.print", e.to_string())), + Some(hex) => craft_print::rgb::DevMode::from_hex(hex).map(Some).map_err(|e| bad("file.print", e.to_string())), None => Ok(None), } } @@ -503,44 +505,45 @@ pub fn page_rect_top_left(page: &PrintPage) -> (f64, f64, f64, f64) { fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: u32) -> Result { let printer = printer_name(p)?; let settings = printer_settings(p)?; - let device_page = photocraft_winprint::page(&printer, settings.as_ref()).map_err(other)?; + let device_page = craft_print::rgb::page(&printer, settings.as_ref()).map_err(other)?; if (device_page.paper.0 - page.paper.0).abs() > 2.0 || (device_page.paper.1 - page.paper.1).abs() > 2.0 { return Err(other("the driver paper or orientation differs from the print layout; choose the matching paper in Print Settings before printing")); } let rgb = page_rgb(page)?; - let image = photocraft_winprint::RgbImage { width: page.image.width, height: page.image.height, data: &rgb }; - let marks = photocraft_winprint::Marks { corner_crop: page.marks.corner_crop, center_crop: page.marks.center_crop, registration: page.marks.registration }; + let image = craft_print::rgb::RgbImage { width: page.image.width, height: page.image.height, data: &rgb }; + let rect = page_rect_top_left(page); + let primitives = windows_marks::primitives(page.marks, rect); let color_policy = match p.get("colorHandling").and_then(Value::as_str) { - Some("photocraftManages" | "photoshopManages") => photocraft_winprint::ColorPolicy::ApplicationManaged, - Some("noColorManagement") => photocraft_winprint::ColorPolicy::Unmanaged, - _ => photocraft_winprint::ColorPolicy::DriverManaged, + Some("photocraftManages" | "photoshopManages") => craft_print::rgb::ColorPolicy::ApplicationManaged, + Some("noColorManagement") => craft_print::rgb::ColorPolicy::Unmanaged, + _ => craft_print::rgb::ColorPolicy::DriverManaged, }; - let job = photocraft_winprint::Job { + let job = craft_print::rgb::Job { printer: &printer, settings: settings.as_ref(), title, output_file: None, copies: copies.clamp(1, 999), color_policy, - marks, + primitives: &primitives, }; - let done = photocraft_winprint::print(&job, &image, page_rect_top_left(page)).map_err(other)?; + let done = craft_print::rgb::print(&job, &image, rect).map_err(other)?; Ok( json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3]}), ) } fn printers(_: &mut Session, _: &Value) -> Result { - match photocraft_winprint::printers() { + match craft_print::rgb::printers() { Ok(list) => Ok(json!({"supported": true, "printers": list.iter().map(|p| json!({"name": p.name, "default": p.default})).collect::>()})), - Err(photocraft_winprint::PrintError::Unsupported) => Ok(json!({"supported": false, "printers": []})), + Err(craft_print::rgb::PrintError::Unsupported) => Ok(json!({"supported": false, "printers": []})), Err(e) => Err(other(e)), } } fn printer_page(_: &mut Session, p: &Value) -> Result { let printer = printer_name(p)?; - let pg = photocraft_winprint::page(&printer, printer_settings(p)?.as_ref()).map_err(other)?; + let pg = craft_print::rgb::page(&printer, printer_settings(p)?.as_ref()).map_err(other)?; Ok( json!({"printer": printer, "paper": [pg.paper.0, pg.paper.1], "printable": [pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3], "dpi": [pg.dpi.0, pg.dpi.1]}), ) diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs index 023829d72d..6181097532 100644 --- a/crates/engine/src/print_cmds/tests.rs +++ b/crates/engine/src/print_cmds/tests.rs @@ -52,7 +52,7 @@ fn print_dry_run_renders_a_pdf_and_reports_the_platform_backend() { assert!(!cmd.contains(&out), "PDF bytes are streamed instead of passing a path"); } #[cfg(windows)] - assert!(cmd.last().unwrap().contains("craft-print PDF spooler")); + assert_eq!(cmd.first().map(String::as_str), Some("xps-print")); assert_eq!(r["sent"], false); assert_eq!(r["pdf"], out); let pdf = std::fs::read(&out).unwrap(); @@ -237,7 +237,7 @@ fn print_one_copy_repeats_the_last_settings() { #[cfg(unix)] assert_eq!(&cmd[..3], &["lp", "-n", "1"]); #[cfg(windows)] - assert!(cmd.last().unwrap().contains("craft-print PDF spooler")); + assert_eq!(cmd.first().map(String::as_str), Some("xps-print")); assert!(r["pdf"].is_null()); } diff --git a/crates/engine/src/print_cmds/windows_marks.rs b/crates/engine/src/print_cmds/windows_marks.rs new file mode 100644 index 0000000000..857e6335a9 --- /dev/null +++ b/crates/engine/src/print_cmds/windows_marks.rs @@ -0,0 +1,47 @@ +//! App-owned print-mark composition in points from the sheet's top-left. +use super::Marks; +use craft_print::rgb::{Primitive, Shape}; + +pub(super) fn primitives(marks: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> Vec { + let mut out = Vec::with_capacity(24); + let line = |out: &mut Vec, x0, y0, x1, y1| { + out.push(Primitive { shape: Shape::Line { from: (x0, y0), to: (x1, y1) }, width: 0.3, color: [0; 3] }); + }; + let (gap, len) = (6.0, 18.0); + if marks.corner_crop { + for (cx, cy, dx, dy) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)] { + line(&mut out, cx + dx * gap, cy, cx + dx * (gap + len), cy); + line(&mut out, cx, cy + dy * gap, cx, cy + dy * (gap + len)); + } + } + if marks.center_crop { + let (mx, my) = (x + w / 2.0, y + h / 2.0); + line(&mut out, mx, y - gap, mx, y - gap - len); + line(&mut out, mx, y + h + gap, mx, y + h + gap + len); + line(&mut out, x - gap, my, x - gap - len, my); + line(&mut out, x + w + gap, my, x + w + gap + len, my); + } + if marks.registration { + let (r, off) = (5.0, gap + len / 2.0); + for (cx, cy) in [(x + w / 2.0, y - off), (x + w / 2.0, y + h + off), (x - off, y + h / 2.0), (x + w + off, y + h / 2.0)] { + out.push(Primitive { shape: Shape::Ellipse { bounds: (cx - r, cy - r, 2.0 * r, 2.0 * r) }, width: 0.3, color: [0; 3] }); + line(&mut out, cx - r * 1.6, cy, cx + r * 1.6, cy); + line(&mut out, cx, cy - r * 1.6, cx, cy + r * 1.6); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn marks_surround_the_final_image_box_in_physical_points() { + let out = primitives(Marks { corner_crop: true, center_crop: true, registration: true }, (100.0, 200.0, 144.0, 72.0)); + assert_eq!(out.len(), 24); + assert_eq!(out[0].shape, Shape::Line { from: (94.0, 200.0), to: (76.0, 200.0) }); + assert_eq!(out[12].shape, Shape::Ellipse { bounds: (167.0, 180.0, 10.0, 10.0) }); + assert!(out.iter().all(|p| p.width == 0.3 && p.color == [0; 3])); + assert!(primitives(Marks::default(), (0.0, 0.0, 10.0, 10.0)).is_empty()); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9925af20a9..aeefacaf2f 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -8,11 +8,11 @@ license.workspace = true workspace = true [dependencies] +craft-print = { workspace = true } craft-ui = { workspace = true } photocraft-geom = { workspace = true } photocraft-color = { workspace = true } photocraft-cms = { workspace = true } -photocraft-winprint = { workspace = true } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-compose = { workspace = true } diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 9805db14c3..d57a450e05 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -594,7 +594,7 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { f.entry(k.to_string()).or_insert(v); } // Windows: the system's printers, and the paper from the chosen printer's driver settings. - if let Ok(list) = photocraft_winprint::printers() { + if let Ok(list) = craft_print::rgb::printers() { f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::>())); let known = |n: &str| list.iter().any(|p| p.name == n); if !known(&s(&f, "printer", "")) { @@ -610,8 +610,8 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { /// Takes the paper from the printer's driver settings (Windows), as Photoshop does. fn driver_page(f: &mut Map) { let printer = s(f, "printer", ""); - let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| photocraft_winprint::DevMode::from_hex(h).ok()); - match photocraft_winprint::page(&printer, settings.as_ref()) { + let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok()); + match craft_print::rgb::page(&printer, settings.as_ref()) { Ok(pg) => { f.insert("paper".into(), json!([pg.paper.0, pg.paper.1])); f.insert("orientation".into(), json!("portrait")); @@ -747,8 +747,8 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map { f.insert("printerSettings".into(), json!(dm.to_hex())); driver_page(f); diff --git a/crates/winprint/Cargo.toml b/crates/winprint/Cargo.toml deleted file mode 100644 index 09504156d5..0000000000 --- a/crates/winprint/Cargo.toml +++ /dev/null @@ -1,26 +0,0 @@ -[package] -name = "photocraft-winprint" -version.workspace = true -edition.workspace = true -license.workspace = true -description = "Windows printing: printer list, the driver's Print Settings dialog, page geometry and GDI printing with ICM off" - -# An isolated `unsafe` helper crate like photocraft-tablet (craftrules never-crash, AGENTS.md): -# Windows printing needs Win32 calls. Only `src/windows.rs` allows `unsafe`; every block has a -# `SAFETY:` comment. Elsewhere every function returns `Unsupported`. -[lints.rust] -unsafe_code = "deny" - -[lints.clippy] -dbg_macro = "warn" -todo = "warn" - -# Already in Cargo.lock (winit/wgpu pull it in); pinned exactly: review the diff before bumping. -[target.'cfg(windows)'.dependencies] -windows-sys = { version = "=0.61.2", features = [ - "Win32_Foundation", - "Win32_Graphics_Gdi", - "Win32_Graphics_Printing", - "Win32_Storage_Xps", - "Win32_UI_ColorSystem", -] } diff --git a/crates/winprint/src/lib.rs b/crates/winprint/src/lib.rs deleted file mode 100644 index ef20e28ce1..0000000000 --- a/crates/winprint/src/lib.rs +++ /dev/null @@ -1,339 +0,0 @@ -//! Windows printing for File › Print: the system's printers, the driver's own Print Settings -//! dialog (paper, paper type, quality, the driver's colour correction and mirror), the page -//! geometry it implies, and printing an 8-bit RGB image through GDI with ICM off, so colours -//! converted with a printer profile ("PhotoCraft Manages Colors") reach the driver unchanged. -//! Corner/centre crop marks and registration marks are drawn around the image with GDI vector -//! calls (`MoveToEx`/`LineTo`/`Ellipse`), the same geometry as the PDF path's content stream. -//! Description and label text stay PDF-only (no font/text layout here yet). -//! -//! The driver settings travel as an opaque DEVMODE blob ([`DevMode`]), validated before use. -//! Everything here is a safe API; the Win32 calls live in `windows.rs`. Other platforms get -//! [`PrintError::Unsupported`]. -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -#[cfg(windows)] -#[allow(unsafe_code)] -mod windows; - -use std::fmt; - -/// Why a printing call failed. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum PrintError { - /// Not on Windows. - Unsupported, - /// Bad input (an unknown printer, a malformed DEVMODE, an empty image). - Invalid(String), - /// A Win32 call failed. - System(String), -} - -impl fmt::Display for PrintError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - PrintError::Unsupported => f.write_str("printing to a printer needs Windows here"), - PrintError::Invalid(m) | PrintError::System(m) => f.write_str(m), - } - } -} - -impl std::error::Error for PrintError {} - -pub type Result = std::result::Result; - -/// One installed printer. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Printer { - pub name: String, - pub default: bool, -} - -/// A printer driver's settings (a Win32 DEVMODEW with the driver's private part), as bytes. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct DevMode(Vec); - -/// Offsets inside DEVMODEW: `dmSize` and `dmDriverExtra` follow the 32-wchar device name and -/// two version words. -const DM_SIZE_AT: usize = 68; -const DM_EXTRA_AT: usize = 70; -/// The smallest DEVMODEW a driver writes (Windows 95's, up to `dmICMIntent`). -const DM_MIN: usize = 156; -/// Larger blobs are not driver settings. -const DM_MAX: usize = 1 << 20; - -impl DevMode { - /// Validates driver settings bytes: the header's own sizes must add up to the length. - pub fn from_bytes(b: Vec) -> Result { - let word = |at: usize| b.get(at..at + 2).map(|w| usize::from(u16::from_le_bytes([w[0], w[1]]))); - let (Some(size), Some(extra)) = (word(DM_SIZE_AT), word(DM_EXTRA_AT)) else { - return Err(PrintError::Invalid("printer settings are too short".into())); - }; - if b.len() > DM_MAX || size < DM_MIN || size.checked_add(extra) != Some(b.len()) { - return Err(PrintError::Invalid("printer settings are damaged; choose Print Settings again".into())); - } - Ok(DevMode(b)) - } - - pub fn as_bytes(&self) -> &[u8] { - &self.0 - } - - /// The application emits every copy as a page. Disable driver copies/collation too, - /// preserving the driver's private settings and all other public fields. - #[cfg(any(windows, test))] - pub(crate) fn for_manual_copies(&self) -> Result { - let mut bytes = self.0.clone(); - let invalid = || PrintError::Invalid("printer settings are too short".into()); - let fields: [u8; 4] = bytes.get(72..76).and_then(|b| b.try_into().ok()).ok_or_else(invalid)?; - let fields = u32::from_le_bytes(fields) | 0x100 | 0x8000; // DM_COPIES | DM_COLLATE - bytes.get_mut(72..76).ok_or_else(invalid)?.copy_from_slice(&fields.to_le_bytes()); - bytes.get_mut(86..88).ok_or_else(invalid)?.copy_from_slice(&1i16.to_le_bytes()); - bytes.get_mut(100..102).ok_or_else(invalid)?.copy_from_slice(&0i16.to_le_bytes()); - Ok(Self(bytes)) - } - - #[cfg(any(windows, test))] - pub(crate) fn has_manual_copies(&self) -> bool { - let fields = self.0.get(72..76).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_le_bytes); - fields.is_some_and(|f| f & 0x100 != 0) - && self.0.get(86..88) == Some(1i16.to_le_bytes().as_slice()) - && self.0.get(100..102) == Some(0i16.to_le_bytes().as_slice()) - } - - /// Hex, for JSON parameters and remembered print settings. - pub fn to_hex(&self) -> String { - self.0.iter().map(|b| format!("{b:02x}")).collect() - } - - pub fn from_hex(s: &str) -> Result { - if !s.len().is_multiple_of(2) || s.len() > DM_MAX * 2 { - return Err(PrintError::Invalid("printer settings are damaged; choose Print Settings again".into())); - } - let bytes: Option> = (0..s.len()).step_by(2).map(|i| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok())).collect(); - Self::from_bytes(bytes.ok_or_else(|| PrintError::Invalid("printer settings are damaged; choose Print Settings again".into()))?) - } -} - -/// What a printer will print on with given settings. Points (1/72 in), origin top-left. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Page { - /// The whole sheet. - pub paper: (f64, f64), - /// The area the printer can reach: (x, y, width, height). - pub printable: (f64, f64, f64, f64), - /// Device resolution (dots per inch). - pub dpi: (u32, u32), -} - -/// An 8-bit RGB image, rows top to bottom, `width * 3` bytes each. -pub struct RgbImage<'a> { - pub width: u32, - pub height: u32, - pub data: &'a [u8], -} - -/// Printer marks drawn around the image box: corner and centre crop marks, and registration -/// marks. Matches [`photocraft_engine`]'s PDF `Marks`, mirrored here so this crate stays -/// independent of the engine; GDI draws the same geometry with vector line/ellipse calls instead -/// of PDF content stream operators. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Marks { - pub corner_crop: bool, - pub center_crop: bool, - pub registration: bool, -} - -impl Marks { - #[cfg(windows)] - pub(crate) fn any(self) -> bool { - self.corner_crop || self.center_crop || self.registration - } -} - -/// One print job. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum ColorPolicy { - /// The driver applies its color settings to the RGB image. - DriverManaged, - /// The caller has converted the pixels into the printer's RGB space. - ApplicationManaged, - /// The caller deliberately requests no DC color correction. - Unmanaged, -} - -/// One print job. -pub struct Job<'a> { - pub printer: &'a str, - pub settings: Option<&'a DevMode>, - /// The name in the print queue. - pub title: &'a str, - /// Print to this file instead of the device (drivers that write files, and tests). - pub output_file: Option<&'a str>, - pub copies: u32, - pub color_policy: ColorPolicy, - pub marks: Marks, -} - -/// Where a job went: the image box in device pixels and the device resolution. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Printed { - pub device_rect: (i32, i32, i32, i32), - pub dpi: (u32, u32), -} - -/// Maps an image box in points (origin top-left of the sheet) to device pixels (origin at the -/// printable area's corner, as GDI draws). -pub fn device_rect(page: &Page, rect: (f64, f64, f64, f64)) -> (i32, i32, i32, i32) { - let (dx, dy) = (f64::from(page.dpi.0) / 72.0, f64::from(page.dpi.1) / 72.0); - let px = |v: f64| if v.is_finite() { v.round().clamp(-1e8, 1e8) as i32 } else { 0 }; - let (x, y, w, h) = rect; - (px((x - page.printable.0) * dx), px((y - page.printable.1) * dy), px(w * dx), px(h * dy)) -} - -/// The printers installed for this user, the default first. -pub fn printers() -> Result> { - #[cfg(windows)] - { - let mut v = windows::printers()?; - v.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))); - Ok(v) - } - #[cfg(not(windows))] - Err(PrintError::Unsupported) -} - -/// The default printer's name. -pub fn default_printer() -> Result> { - #[cfg(windows)] - { - windows::default_printer() - } - #[cfg(not(windows))] - Err(PrintError::Unsupported) -} - -/// A printer's settings as its driver starts them. -pub fn default_settings(printer: &str) -> Result { - #[cfg(windows)] - { - windows::properties(printer, None, None, false)?.ok_or_else(|| PrintError::System("the printer driver gave no settings".into())) - } - #[cfg(not(windows))] - { - let _ = printer; - Err(PrintError::Unsupported) - } -} - -/// Shows the driver's Print Settings dialog (modal; `parent` is a window handle). `None` when -/// the user cancels. -pub fn settings_dialog(printer: &str, current: Option<&DevMode>, parent: Option) -> Result> { - #[cfg(windows)] - { - windows::properties(printer, current, parent, true) - } - #[cfg(not(windows))] - { - let _ = (printer, current, parent); - Err(PrintError::Unsupported) - } -} - -/// The sheet and printable area for `printer` with `settings`. -pub fn page(printer: &str, settings: Option<&DevMode>) -> Result { - #[cfg(windows)] - { - windows::page(printer, settings) - } - #[cfg(not(windows))] - { - let _ = (printer, settings); - Err(PrintError::Unsupported) - } -} - -/// Prints `image` into `rect` (points, origin top-left of the sheet), `job.copies` pages. -pub fn print(job: &Job<'_>, image: &RgbImage<'_>, rect: (f64, f64, f64, f64)) -> Result { - let row = (image.width as usize).checked_mul(3).ok_or_else(|| PrintError::Invalid("image too large".into()))?; - if image.width == 0 || image.height == 0 || row.checked_mul(image.height as usize) != Some(image.data.len()) { - return Err(PrintError::Invalid("nothing to print".into())); - } - if ![rect.0, rect.1, rect.2, rect.3].iter().all(|v| v.is_finite()) || !(rect.2 > 0.0 && rect.3 > 0.0) { - return Err(PrintError::Invalid("the print size is empty".into())); - } - #[cfg(windows)] - { - windows::print(job, image, rect) - } - #[cfg(not(windows))] - { - let _ = job; - Err(PrintError::Unsupported) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn devmode(size: u16, extra: u16) -> Vec { - let mut b = vec![0u8; usize::from(size) + usize::from(extra)]; - b[DM_SIZE_AT..DM_SIZE_AT + 2].copy_from_slice(&size.to_le_bytes()); - b[DM_EXTRA_AT..DM_EXTRA_AT + 2].copy_from_slice(&extra.to_le_bytes()); - b - } - - #[test] - fn devmode_checks_its_own_sizes_and_round_trips_hex() { - let d = DevMode::from_bytes(devmode(220, 1200)).unwrap(); - assert_eq!(DevMode::from_hex(&d.to_hex()).unwrap(), d); - for bad in [vec![], vec![0; 40], devmode(100, 0), { - let mut b = devmode(220, 10); - b.pop(); - b - }] { - assert!(DevMode::from_bytes(bad).is_err()); - } - for bad in ["", "abc", "zz", &"00".repeat(300)] { - assert!(DevMode::from_hex(bad).is_err(), "{bad}"); - } - } - - #[test] - fn manual_copies_disable_driver_multiplication_without_losing_private_settings() { - let mut bytes = devmode(220, 32); - bytes[86..88].copy_from_slice(&7i16.to_le_bytes()); - bytes[100..102].copy_from_slice(&1i16.to_le_bytes()); - bytes[220..].fill(0x5a); - let original = DevMode::from_bytes(bytes).unwrap(); - let normalized = original.for_manual_copies().unwrap(); - assert!(normalized.has_manual_copies()); - assert!(!original.has_manual_copies()); - assert_eq!(&normalized.as_bytes()[220..], &original.as_bytes()[220..]); - assert_eq!(normalized.for_manual_copies().unwrap(), normalized); - let mut ignored = normalized.as_bytes().to_vec(); - ignored[72..76].copy_from_slice(&0u32.to_le_bytes()); - assert!(!DevMode::from_bytes(ignored).unwrap().has_manual_copies(), "a driver must advertise that it accepts dmCopies"); - } - - #[test] - fn device_rect_is_relative_to_the_printable_corner() { - // A3 at 360 dpi with a 3 mm (8.5 pt) unprintable margin. - let page = Page { paper: (841.89, 1190.55), printable: (8.5, 8.5, 824.89, 1173.55), dpi: (360, 360) }; - assert_eq!(device_rect(&page, (8.5, 8.5, 72.0, 36.0)), (0, 0, 360, 180)); - assert_eq!(device_rect(&page, (72.0, 144.0, 144.0, 72.0)), (318, 678, 720, 360)); - assert_eq!(device_rect(&page, (f64::NAN, f64::INFINITY, 1.0, 1.0)).0, 0); - } - - #[test] - fn print_rejects_empty_or_short_images_before_any_system_call() { - let job = Job { printer: "x", settings: None, title: "t", output_file: None, copies: 1, color_policy: ColorPolicy::Unmanaged, marks: Marks::default() }; - let short = RgbImage { width: 2, height: 2, data: &[0; 11] }; - assert!(matches!(print(&job, &short, (0.0, 0.0, 10.0, 10.0)), Err(PrintError::Invalid(_)))); - let ok = RgbImage { width: 2, height: 2, data: &[0; 12] }; - assert!(matches!(print(&job, &ok, (0.0, 0.0, 0.0, 10.0)), Err(PrintError::Invalid(_)))); - for rect in [(f64::NAN, 0.0, 10.0, 10.0), (0.0, 0.0, f64::INFINITY, 10.0)] { - assert!(matches!(print(&job, &ok, rect), Err(PrintError::Invalid(_)))); - } - } -} diff --git a/crates/winprint/src/windows.rs b/crates/winprint/src/windows.rs deleted file mode 100644 index 103309dcd0..0000000000 --- a/crates/winprint/src/windows.rs +++ /dev/null @@ -1,520 +0,0 @@ -//! The Win32 side: winspool (printers, driver settings) and GDI (page geometry, printing). -//! Every `unsafe` block says why it is sound. Buffers the system writes into are `u64`-backed so -//! the structures read from them are aligned. - -use std::ptr::{null, null_mut}; - -use windows_sys::Win32::Foundation::HWND; -use windows_sys::Win32::Graphics::Gdi::{ - BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDCW, CreatePen, DEVMODEW, DIB_RGB_COLORS, DM_IN_BUFFER, DM_IN_PROMPT, DM_OUT_BUFFER, DeleteDC, DeleteObject, - Ellipse, GetDeviceCaps, GetStockObject, HALFTONE, HDC, HOLLOW_BRUSH, HORZRES, LOGPIXELSX, LOGPIXELSY, LineTo, MoveToEx, PHYSICALHEIGHT, PHYSICALOFFSETX, - PHYSICALOFFSETY, PHYSICALWIDTH, PS_SOLID, SRCCOPY, SelectObject, SetBrushOrgEx, SetStretchBltMode, StretchDIBits, VERTRES, -}; -use windows_sys::Win32::Graphics::Printing::{ - ClosePrinter, DocumentPropertiesW, EnumPrintersW, GetDefaultPrinterW, OpenPrinterW, PRINTER_ENUM_CONNECTIONS, PRINTER_ENUM_LOCAL, PRINTER_HANDLE, - PRINTER_INFO_4W, -}; -use windows_sys::Win32::Storage::Xps::{AbortDoc, DOCINFOW, EndDoc, EndPage, StartDocW, StartPage}; -use windows_sys::Win32::UI::ColorSystem::{ICM_DONE_OUTSIDEDC, ICM_OFF, SetICMMode}; - -use crate::{ColorPolicy, DevMode, Job, Marks, Page, PrintError, Printed, Printer, Result, RgbImage}; - -const IDOK: i32 = 1; -const IDCANCEL: i32 = 2; -/// Wide strings read from the system stop here at the latest. -const MAX_WCHARS: usize = 32 * 1024; - -fn last_error(what: &str) -> PrintError { - PrintError::System(format!("{what} failed: {}", std::io::Error::last_os_error())) -} - -fn wide(s: &str) -> Result> { - if s.contains('\0') { - return Err(PrintError::Invalid("a name contains a NUL character".into())); - } - Ok(s.encode_utf16().chain(Some(0)).collect()) -} - -/// A zeroed, 8-byte aligned buffer of at least `bytes` bytes. -fn aligned(bytes: usize) -> Vec { - vec![0u64; bytes.div_ceil(8).max(1)] -} - -fn bytes_of(buf: &[u64], len: usize) -> Vec { - buf.iter().flat_map(|w| w.to_le_bytes()).take(len).collect() -} - -/// Reads a NUL-terminated wide string. -/// -/// # Safety -/// `p` is null or points to a NUL-terminated UTF-16 string that stays alive for the call. -unsafe fn read_wide(p: *const u16) -> String { - if p.is_null() { - return String::new(); - } - let mut n = 0; - // SAFETY: the caller guarantees a NUL-terminated string; we stop at the NUL (or the cap). - while n < MAX_WCHARS && unsafe { *p.add(n) } != 0 { - n += 1; - } - // SAFETY: the `n` units before the NUL were just read and are valid. - String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(p, n) }) -} - -pub fn printers() -> Result> { - let flags = PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS; - let (mut needed, mut count) = (0u32, 0u32); - // SAFETY: a size query: no buffer (null, 0 bytes); the out-params are valid locals. - unsafe { EnumPrintersW(flags, null(), 4, null_mut(), 0, &mut needed, &mut count) }; - if needed == 0 { - return Ok(Vec::new()); - } - let mut buf = aligned(needed as usize); - // SAFETY: `buf` holds at least `needed` writable bytes, aligned for PRINTER_INFO_4W. - let ok = unsafe { EnumPrintersW(flags, null(), 4, buf.as_mut_ptr().cast(), needed, &mut needed, &mut count) }; - if ok == 0 { - return Err(last_error("listing printers")); - } - let default = default_printer().ok().flatten(); - let infos = buf.as_ptr().cast::(); - let fits = (needed as usize) / std::mem::size_of::(); - let mut out = Vec::new(); - for i in 0..(count as usize).min(fits) { - // SAFETY: the system wrote `count` PRINTER_INFO_4W at the start of `buf` (bounded by - // the buffer size above); their name pointers point into `buf`, which is alive. - let name = unsafe { read_wide((*infos.add(i)).pPrinterName) }; - if !name.is_empty() { - out.push(Printer { default: default.as_deref() == Some(name.as_str()), name }); - } - } - Ok(out) -} - -pub fn default_printer() -> Result> { - let mut len = 0u32; - // SAFETY: a size query with a null buffer; `len` is a valid local. - unsafe { GetDefaultPrinterW(null_mut(), &mut len) }; - if len == 0 || len as usize > MAX_WCHARS { - return Ok(None); - } - let mut buf = vec![0u16; len as usize]; - // SAFETY: `buf` holds `len` writable wide chars. - if unsafe { GetDefaultPrinterW(buf.as_mut_ptr(), &mut len) } == 0 { - return Ok(None); - } - // SAFETY: on success the buffer holds a NUL-terminated name. - Ok(Some(unsafe { read_wide(buf.as_ptr()) })) -} - -/// An open printer handle, closed on drop. -struct OpenPrinter(PRINTER_HANDLE); - -impl OpenPrinter { - fn open(name: &[u16]) -> Result { - let mut h = PRINTER_HANDLE { Value: null_mut() }; - // SAFETY: `name` is NUL-terminated; `h` is a valid out-param; no defaults. - if unsafe { OpenPrinterW(name.as_ptr(), &mut h, null()) } == 0 || h.Value.is_null() { - return Err(last_error("opening the printer")); - } - Ok(OpenPrinter(h)) - } -} - -impl Drop for OpenPrinter { - fn drop(&mut self) { - // SAFETY: the handle came from OpenPrinterW and is closed once. - unsafe { ClosePrinter(self.0) }; - } -} - -/// `settings` copied into an aligned buffer the driver can read. -/// -/// There is deliberately no check of the printer name stored in the settings: Windows keeps only -/// 31 characters of it, and drivers fill it differently, so a long queue name ("Sublimation - -/// EPSON ET-18100 Series") failed such a check and the settings were silently dropped. The driver -/// itself validates them instead (see [`Dc::create`]). -fn aligned_copy(settings: &DevMode) -> Vec { - let b = settings.as_bytes(); - let mut buf = aligned(b.len()); - for (slot, chunk) in buf.iter_mut().zip(b.chunks(8)) { - let mut w = [0u8; 8]; - w[..chunk.len()].copy_from_slice(chunk); - *slot = u64::from_le_bytes(w); - } - buf -} - -pub fn properties(printer: &str, current: Option<&DevMode>, parent: Option, prompt: bool) -> Result> { - let name = wide(printer)?; - let p = OpenPrinter::open(&name)?; - let hwnd: HWND = parent.map_or(null_mut(), |h| h as HWND); - // SAFETY: with fmode 0 DocumentPropertiesW only returns the size the settings need. - let needed = unsafe { DocumentPropertiesW(hwnd, p.0, name.as_ptr(), null_mut(), null(), 0) }; - if needed <= 0 || needed as usize > (1 << 20) { - return Err(last_error("reading the printer's settings")); - } - let mut out = aligned(needed as usize); - let input = current.map(aligned_copy); - let mut mode = DM_OUT_BUFFER; - if input.is_some() { - mode |= DM_IN_BUFFER; - } - if prompt { - mode |= DM_IN_PROMPT; - } - let inp: *const DEVMODEW = input.as_ref().map_or(null(), |b| b.as_ptr().cast()); - // SAFETY: `out` holds `needed` aligned writable bytes as the size query asked for; `inp` is - // null or an aligned copy of settings written by this printer's driver. - let r = unsafe { DocumentPropertiesW(hwnd, p.0, name.as_ptr(), out.as_mut_ptr().cast(), inp, mode) }; - match r { - IDOK => { - let all = bytes_of(&out, needed as usize); - let word = |at: usize| all.get(at..at + 2).map_or(0, |w| usize::from(u16::from_le_bytes([w[0], w[1]]))); - let len = (word(68) + word(70)).min(all.len()); - DevMode::from_bytes(all.into_iter().take(len).collect()).map(Some) - } - IDCANCEL => Ok(None), - _ => Err(last_error("the printer's settings dialog")), - } -} - -/// A printer device context, deleted on drop. -struct Dc(HDC); - -impl Dc { - fn create(printer: &str, settings: Option<&DevMode>, manual_copies: bool) -> Result { - let name = wide(printer)?; - let normalized = if manual_copies { - let defaults = match settings { - Some(s) => s.clone(), - None => properties(printer, None, None, false)?.ok_or_else(|| PrintError::Invalid("the printer refused its default settings".into()))?, - }; - Some(defaults.for_manual_copies()?) - } else { - None - }; - let settings = normalized.as_ref().or(settings); - // The driver validates and completes the settings first (DM_IN_BUFFER | DM_OUT_BUFFER, no - // dialog). If it refuses them, that is an error: never print on the defaults instead. - let merged = match settings { - Some(s) => Some( - properties(printer, Some(s), None, false)? - .ok_or_else(|| PrintError::Invalid(format!("printer “{printer}” refused these settings; choose Print Settings… again")))?, - ), - None => None, - }; - if manual_copies && !merged.as_ref().is_some_and(DevMode::has_manual_copies) { - return Err(PrintError::Invalid("the driver refused single-copy settings; no print job was sent".into())); - } - let dm = merged.as_ref().map(aligned_copy); - let dmp: *const DEVMODEW = dm.as_ref().map_or(null(), |b| b.as_ptr().cast()); - // SAFETY: `name` is NUL-terminated; `dmp` is null or aligned settings from this - // printer's driver, alive for the call. - let hdc = unsafe { CreateDCW(null(), name.as_ptr(), null(), dmp) }; - if hdc.is_null() { - return Err(last_error(&format!("opening printer “{printer}”"))); - } - Ok(Dc(hdc)) - } - - fn cap(&self, index: u32) -> i32 { - // SAFETY: a valid printer DC and a documented capability index. - unsafe { GetDeviceCaps(self.0, index as i32) } - } - - fn page(&self) -> Result { - let (dx, dy) = (self.cap(LOGPIXELSX), self.cap(LOGPIXELSY)); - if dx <= 0 || dy <= 0 { - return Err(PrintError::System("the printer reported no resolution".into())); - } - let (fx, fy) = (72.0 / f64::from(dx), 72.0 / f64::from(dy)); - let (pw, ph) = (self.cap(PHYSICALWIDTH), self.cap(PHYSICALHEIGHT)); - let (ox, oy) = (self.cap(PHYSICALOFFSETX), self.cap(PHYSICALOFFSETY)); - let (hw, vh) = (self.cap(HORZRES), self.cap(VERTRES)); - let (pw, ph) = if pw > 0 && ph > 0 { (pw, ph) } else { (hw, vh) }; - Ok(Page { - paper: (f64::from(pw) * fx, f64::from(ph) * fy), - printable: (f64::from(ox) * fx, f64::from(oy) * fy, f64::from(hw) * fx, f64::from(vh) * fy), - dpi: (dx as u32, dy as u32), - }) - } -} - -impl Drop for Dc { - fn drop(&mut self) { - // SAFETY: the DC came from CreateDCW and is deleted once. - unsafe { DeleteDC(self.0) }; - } -} - -pub fn page(printer: &str, settings: Option<&DevMode>) -> Result { - Dc::create(printer, settings, false)?.page() -} - -/// RGB rows top-down → a bottom-up 24-bit DIB (BGR, rows padded to 4 bytes). -fn dib(image: &RgbImage<'_>) -> Result<(BITMAPINFO, Vec)> { - let (w, h) = (image.width as usize, image.height as usize); - let stride = (w.checked_mul(3).ok_or_else(|| PrintError::Invalid("image too large".into()))? + 3) & !3; - let total = stride.checked_mul(h).filter(|t| *t <= i32::MAX as usize).ok_or_else(|| PrintError::Invalid("image too large to print in one piece".into()))?; - let mut bits = vec![0u8; total]; - for (y, src) in image.data.chunks_exact(w * 3).enumerate() { - let start = (h - 1 - y) * stride; - let Some(dst) = bits.get_mut(start..start + w * 3) else { continue }; - for (d, s) in dst.as_chunks_mut::<3>().0.iter_mut().zip(src.as_chunks::<3>().0) { - *d = [s[2], s[1], s[0]]; - } - } - let header = BITMAPINFOHEADER { - biSize: std::mem::size_of::() as u32, - biWidth: image.width as i32, - biHeight: image.height as i32, - biPlanes: 1, - biBitCount: 24, - biCompression: BI_RGB, - biSizeImage: total as u32, - ..Default::default() - }; - Ok((BITMAPINFO { bmiHeader: header, bmiColors: [Default::default()] }, bits)) -} - -/// Vector marks around the image box `(x, y, w, h)` (device pixels, origin top-left, as GDI -/// draws). Same geometry as `photocraft_engine::print_cmds::marks_ops`'s PDF content stream, with -/// the vertical sense flipped (PDF's origin is bottom-left; GDI's is top-left), scaled from points -/// to device pixels with `dpi` instead of PDF's user-space points. -/// -/// # Safety -/// `dc` is a valid, selected device context for the current page. -unsafe fn draw_marks(dc: HDC, marks: Marks, (x, y, w, h): (i32, i32, i32, i32), dpi: (u32, u32)) -> Result<()> { - let (sx, sy) = (f64::from(dpi.0) / 72.0, f64::from(dpi.1) / 72.0); - let px = |v: f64| v.round() as i32; - let (gap_x, gap_y) = (px(6.0 * sx), px(6.0 * sy)); - let (len_x, len_y) = (px(18.0 * sx), px(18.0 * sy)); - let pen_width = px(0.3 * sx).max(1); - // SAFETY: `dc` is valid; the pen and brush are deleted/restored before returning. - let pen = unsafe { CreatePen(PS_SOLID, pen_width, 0x0000_0000) }; - let hollow = unsafe { GetStockObject(HOLLOW_BRUSH) }; - let old_pen = unsafe { SelectObject(dc, pen) }; - let old_brush = unsafe { SelectObject(dc, hollow) }; - let ok = std::cell::Cell::new(true); - let line = |x0: i32, y0: i32, x1: i32, y1: i32| { - // SAFETY: `dc` is valid for the duration of this call. - ok.set(ok.get() && unsafe { MoveToEx(dc, x0, y0, null_mut()) != 0 && LineTo(dc, x1, y1) != 0 }); - }; - if marks.corner_crop { - for (cx, cy, dx, dy) in [(x, y, -1, -1), (x + w, y, 1, -1), (x, y + h, -1, 1), (x + w, y + h, 1, 1)] { - line(cx + dx * gap_x, cy, cx + dx * (gap_x + len_x), cy); - line(cx, cy + dy * gap_y, cx, cy + dy * (gap_y + len_y)); - } - } - if marks.center_crop { - let (mx, my) = (x + w / 2, y + h / 2); - line(mx, y - gap_y, mx, y - gap_y - len_y); - line(mx, y + h + gap_y, mx, y + h + gap_y + len_y); - line(x - gap_x, my, x - gap_x - len_x, my); - line(x + w + gap_x, my, x + w + gap_x + len_x, my); - } - if marks.registration { - let (rx, ry) = (px(5.0 * sx), px(5.0 * sy)); - let (off_x, off_y) = (gap_x + len_x / 2, gap_y + len_y / 2); - for (cx, cy) in [(x + w / 2, y - off_y), (x + w / 2, y + h + off_y), (x - off_x, y + h / 2), (x + w + off_x, y + h / 2)] { - // SAFETY: `dc` is valid for the duration of this call. - ok.set(ok.get() && unsafe { Ellipse(dc, cx - rx, cy - ry, cx + rx, cy + ry) != 0 }); - line(cx - (rx as f64 * 1.6) as i32, cy, cx + (rx as f64 * 1.6) as i32, cy); - line(cx, cy - (ry as f64 * 1.6) as i32, cx, cy + (ry as f64 * 1.6) as i32); - } - } - // SAFETY: restores the DC's previous pen/brush, then frees the ones created above. - unsafe { - SelectObject(dc, old_pen); - SelectObject(dc, old_brush); - DeleteObject(pen); - } - if ok.get() { Ok(()) } else { Err(last_error("drawing printer marks")) } -} - -pub fn print(job: &Job<'_>, image: &RgbImage<'_>, rect: (f64, f64, f64, f64)) -> Result { - if image.width > i32::MAX as u32 || image.height > i32::MAX as u32 { - return Err(PrintError::Invalid("image too large".into())); - } - let dc = Dc::create(job.printer, job.settings, true)?; - let page = dc.page()?; - let (x, y, w, h) = crate::device_rect(&page, rect); - let (bmi, bits) = dib(image)?; - let title = wide(job.title)?; - let output = job.output_file.map(wide).transpose()?; - let info = DOCINFOW { - cbSize: std::mem::size_of::() as i32, - lpszDocName: title.as_ptr(), - lpszOutput: output.as_ref().map_or(null(), |o| o.as_ptr()), - lpszDatatype: null(), - fwType: 0, - }; - let color_mode = match job.color_policy { - ColorPolicy::DriverManaged => ICM_OFF, - // ICM_OFF enables old-style halftone correction. Pixels converted by the caller - // need both DC conversion and that correction off (Microsoft SetICMMode contract). - ColorPolicy::ApplicationManaged | ColorPolicy::Unmanaged => ICM_DONE_OUTSIDEDC, - }; - let set_color_mode = || { - // SAFETY: a valid printer DC and a documented SetICMMode value. - if unsafe { SetICMMode(dc.0, color_mode) } == 0 { Err(last_error("setting GDI color policy")) } else { Ok(()) } - }; - set_color_mode()?; - // SAFETY: a valid DC; HALFTONE resampling needs the brush origin reset afterwards. - unsafe { - SetStretchBltMode(dc.0, HALFTONE); - SetBrushOrgEx(dc.0, 0, 0, null_mut()); - } - // SAFETY: `info` and the strings it points to live until EndDoc/AbortDoc below. - if unsafe { StartDocW(dc.0, &info) } <= 0 { - return Err(last_error("starting the print job")); - } - let fail = |what: &str| { - let e = last_error(what); - // SAFETY: the job was started on this DC. - unsafe { AbortDoc(dc.0) }; - e - }; - for _ in 0..job.copies.clamp(1, 999) { - // SAFETY: inside a started document on a valid DC. - if unsafe { StartPage(dc.0) } <= 0 { - return Err(fail("starting a page")); - } - // StartPage saves/restores DC state. Reapply the policy for each page, before pixels. - if let Err(error) = set_color_mode() { - // SAFETY: this DC owns the document started above. - unsafe { AbortDoc(dc.0) }; - return Err(error); - } - // SAFETY: `bits` is a bottom-up DIB exactly as `bmi` describes (24-bit, padded rows, - // `biSizeImage` bytes); the source rectangle is the whole image. - let lines = - unsafe { StretchDIBits(dc.0, x, y, w, h, 0, 0, image.width as i32, image.height as i32, bits.as_ptr().cast(), &bmi, DIB_RGB_COLORS, SRCCOPY) }; - if lines <= 0 { - return Err(fail("sending the image to the printer")); - } - if job.marks.any() { - // SAFETY: `dc.0` is the valid, started page's device context. - if let Err(e) = unsafe { draw_marks(dc.0, job.marks, (x, y, w, h), page.dpi) } { - return Err(fail(&e.to_string())); - } - } - // SAFETY: closes the page started above. - if unsafe { EndPage(dc.0) } <= 0 { - return Err(fail("finishing a page")); - } - } - // SAFETY: closes the document started above. - if unsafe { EndDoc(dc.0) } <= 0 { - return Err(last_error("finishing the print job")); - } - Ok(Printed { device_rect: (x, y, w, h), dpi: page.dpi }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn dib_is_bottom_up_bgr_with_padded_rows() { - // 2×2: red, green / blue, white. - let data = [255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255]; - let (bmi, bits) = dib(&RgbImage { width: 2, height: 2, data: &data }).unwrap(); - assert_eq!(bmi.bmiHeader.biHeight, 2); - assert_eq!(bits.len(), 16, "6 bytes per row padded to 8"); - // First stored row is the bottom one: blue, white. - assert_eq!(&bits[0..6], &[255, 0, 0, 255, 255, 255]); - assert_eq!(&bits[8..14], &[0, 0, 255, 0, 255, 0]); - } - - #[test] - fn settings_are_copied_aligned_and_intact() { - let mut b: Vec = (0..230u32).map(|i| (i * 7) as u8).collect(); - b[68..70].copy_from_slice(&220u16.to_le_bytes()); - b[70..72].copy_from_slice(&10u16.to_le_bytes()); - let d = DevMode::from_bytes(b.clone()).unwrap(); - let buf = aligned_copy(&d); - assert_eq!(buf.as_ptr().align_offset(std::mem::align_of::()), 0); - assert_eq!(bytes_of(&buf, b.len()), b, "no name check, no truncation: the bytes go through as chosen"); - } - - /// Settings chosen for a printer are what the driver prints with: paper and resolution survive - /// the driver's own validation (needs "Microsoft Print to PDF"; run by hand). - #[test] - #[ignore] - fn chosen_settings_reach_the_device_context() { - let printer = "Microsoft Print to PDF"; - let d = crate::default_settings(printer).unwrap(); - let mut b = d.as_bytes().to_vec(); - // dmPaperSize = DMPAPER_A3 (8); dmFields |= DM_PAPERSIZE (2). - b[78..80].copy_from_slice(&8i16.to_le_bytes()); - let fields = u32::from_le_bytes([b[72], b[73], b[74], b[75]]) | 2; - b[72..76].copy_from_slice(&fields.to_le_bytes()); - let a3 = DevMode::from_bytes(b).unwrap(); - let pg = crate::page(printer, Some(&a3)).unwrap(); - assert!((pg.paper.0 - 841.9).abs() < 2.0 && (pg.paper.1 - 1190.6).abs() < 2.0, "A3, not the default: {:?}", pg.paper); - // Landscape (dmOrientation = 2, DM_ORIENTATION = 1): the page comes back wide. - let mut b = a3.as_bytes().to_vec(); - b[76..78].copy_from_slice(&2i16.to_le_bytes()); - let fields = u32::from_le_bytes([b[72], b[73], b[74], b[75]]) | 1; - b[72..76].copy_from_slice(&fields.to_le_bytes()); - let pg = crate::page(printer, Some(&DevMode::from_bytes(b).unwrap())).unwrap(); - assert!((pg.paper.0 - 1190.6).abs() < 2.0 && (pg.paper.1 - 841.9).abs() < 2.0, "landscape A3: {:?}", pg.paper); - } - - /// A real job through Windows' "Microsoft Print to PDF" driver, written to a file (needs that - /// printer installed; run by hand). - #[test] - #[ignore] - fn prints_through_a_real_driver_to_a_file() { - let out = std::env::temp_dir().join(format!("pc-winprint-{}.pdf", std::process::id())); - let _ = std::fs::remove_file(&out); - let settings = crate::default_settings("Microsoft Print to PDF").unwrap(); - let mut bytes = settings.as_bytes().to_vec(); - bytes[86..88].copy_from_slice(&5i16.to_le_bytes()); - let fields = u32::from_le_bytes(bytes[72..76].try_into().unwrap()) | 0x100; - bytes[72..76].copy_from_slice(&fields.to_le_bytes()); - let settings = DevMode::from_bytes(bytes).unwrap(); - let (w, h) = (300u32, 200u32); - let data: Vec = (0..w * h).flat_map(|i| if (i % w) < w / 2 { [220, 30, 30] } else { [30, 30, 220] }).collect(); - let out_s = out.to_string_lossy().into_owned(); - let marks = crate::Marks { corner_crop: true, center_crop: true, registration: true }; - let job = Job { - printer: "Microsoft Print to PDF", - settings: Some(&settings), - title: "PhotoCraft test", - output_file: Some(&out_s), - copies: 2, - color_policy: ColorPolicy::ApplicationManaged, - marks, - }; - let done = crate::print(&job, &RgbImage { width: w, height: h, data: &data }, (72.0, 72.0, 216.0, 144.0)).unwrap(); - assert_eq!(done.device_rect.2, done.dpi.0 as i32 * 3, "3 inches wide"); - let pdf = std::fs::read(&out).unwrap(); - assert!(pdf.starts_with(b"%PDF"), "the driver wrote a PDF"); - assert!(pdf.len() > 1000, "the page has content"); - // The driver vectorises our GDI line/ellipse calls as real PDF content: a job with every - // mark on is meaningfully bigger than the same image with marks off. - let no_marks_job = Job { marks: crate::Marks::default(), ..job }; - let done2 = crate::print(&no_marks_job, &RgbImage { width: w, height: h, data: &data }, (72.0, 72.0, 216.0, 144.0)).unwrap(); - let _ = done2; - let pdf_no_marks = std::fs::read(&out).unwrap(); - assert!(pdf.len() > pdf_no_marks.len() + 100, "marks add vector content: {} vs {}", pdf.len(), pdf_no_marks.len()); - if let Ok(evidence) = std::env::var("PHOTOCRAFT_WINPRINT_TEST_EVIDENCE") { - let evidence = std::path::Path::new(&evidence); - std::fs::create_dir_all(evidence).unwrap(); - std::fs::write(evidence.join("copies2-driver5-marks.pdf"), &pdf).unwrap(); - std::fs::write(evidence.join("copies2-driver5-no-marks.pdf"), &pdf_no_marks).unwrap(); - } - let _ = std::fs::remove_file(&out); - } - - /// Lists this machine's printers and their pages (needs real printers; run by hand). - #[test] - #[ignore] - fn lists_real_printers() { - for p in printers().unwrap() { - println!("{}{} {:?}", p.name, if p.default { " (default)" } else { "" }, page(&p.name, None)); - } - } -} diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index dcb66f7120..e78613f37a 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -47,7 +47,6 @@ pub const TABLE: &[(&str, Class)] = &[ // Pen tablet input (the one isolated `unsafe` helper: AppKit interop on macOS). ("tablet", Class::Standalone), // Windows printing (an isolated `unsafe` helper: winspool and GDI). - ("winprint", Class::Standalone), ("doc", Class::Layer(1)), ("ops", Class::Layer(2)), ("paint", Class::Layer(2)), From 4de93daa912cdfe803984b0686c989a5b0490bad Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Tue, 13 Oct 2026 04:25:32 +0200 Subject: [PATCH 08/17] Pin pre-submission annotation visibility guard --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9ba37f36a7..9b052103d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -849,7 +849,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.5", "rustix-linux-procfs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "winx", ] @@ -1225,7 +1225,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=ee70afc29a41bc50f2a55affa9aa2c62e0d28e3a#ee70afc29a41bc50f2a55affa9aa2c62e0d28e3a" +source = "git+https://github.com/storytold/craft-libs?rev=6ba4d0b97ad09767c588d82ff9c988eea53f0546#6ba4d0b97ad09767c588d82ff9c988eea53f0546" dependencies = [ "craft-winprint-gdi", "miniz_oxide 0.8.9", @@ -1891,7 +1891,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3028,7 +3028,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3690,7 +3690,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png 0.18.1", "thiserror 2.0.21", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4436,7 +4436,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5454,7 +5454,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -5973,7 +5973,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6040,7 +6040,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -6678,7 +6678,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -6905,10 +6905,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.5", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7308,7 +7308,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -8068,7 +8068,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 54bd1a3a05..9d289b3438 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ photocraft-testkit = { path = "crates/testkit" } photocraft-tablet = { path = "crates/tablet" } # external -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "ee70afc29a41bc50f2a55affa9aa2c62e0d28e3a" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "6ba4d0b97ad09767c588d82ff9c988eea53f0546" } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" From 70059ac1b43e4679c462f77efc1d0a2ef63de0ae Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Tue, 13 Oct 2026 04:56:32 +0200 Subject: [PATCH 09/17] Pin driver option retention qualification fixes --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9b052103d1..5c5b43b827 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1225,7 +1225,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=6ba4d0b97ad09767c588d82ff9c988eea53f0546#6ba4d0b97ad09767c588d82ff9c988eea53f0546" +source = "git+https://github.com/storytold/craft-libs?rev=d873514e8a773f02f54c34ba890e57c02c3a36f6#d873514e8a773f02f54c34ba890e57c02c3a36f6" dependencies = [ "craft-winprint-gdi", "miniz_oxide 0.8.9", diff --git a/Cargo.toml b/Cargo.toml index 9d289b3438..cd5017ba68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ photocraft-testkit = { path = "crates/testkit" } photocraft-tablet = { path = "crates/tablet" } # external -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "6ba4d0b97ad09767c588d82ff9c988eea53f0546" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d873514e8a773f02f54c34ba890e57c02c3a36f6" } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" From d6fbac1720941a477333c20c70948efd9365fd04 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Tue, 13 Oct 2026 05:04:13 +0200 Subject: [PATCH 10/17] Pin qualification fixes integrated with current print progress --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5c5b43b827..362a874cbb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1225,7 +1225,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d873514e8a773f02f54c34ba890e57c02c3a36f6#d873514e8a773f02f54c34ba890e57c02c3a36f6" +source = "git+https://github.com/storytold/craft-libs?rev=3d37da389a3618ab9b76109da11416e9ca4ea719#3d37da389a3618ab9b76109da11416e9ca4ea719" dependencies = [ "craft-winprint-gdi", "miniz_oxide 0.8.9", diff --git a/Cargo.toml b/Cargo.toml index cd5017ba68..2c329d980d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ photocraft-testkit = { path = "crates/testkit" } photocraft-tablet = { path = "crates/tablet" } # external -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d873514e8a773f02f54c34ba890e57c02c3a36f6" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "3d37da389a3618ab9b76109da11416e9ca4ea719" } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" From 8f56cd5be5a8b3a384da888b6c769b0b8353dfc4 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Tue, 13 Oct 2026 05:54:57 +0200 Subject: [PATCH 11/17] Preserve explicit PDF export before disabled submission refusal --- crates/engine/src/print_cmds.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 0235d3af11..9361f7d2b4 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -390,17 +390,12 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { let send = p.get("send").and_then(Value::as_bool).unwrap_or(output.is_none()); let copies = crate::commands::int(p, "copies").unwrap_or(1).clamp(1, 999) as u32; let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false); - // Apply the process-wide test/fuzz guard before either native transport can reach a driver. - if send && !dry && printing_disabled() { - return Err(other( - "printing is disabled in this process (photocraft_engine::print_cmds::disable_printing or PHOTOCRAFT_NO_PRINT); use dryRun: true", - )); - } // Shared RGB transport handles compatible Windows pages; PDF-only content retains its route. // Sending follows the shared command contract; fuzz tests explicitly request dryRun. // The worker returns its result before repeat settings and hooks are applied once. let handling = p.get("colorHandling").and_then(Value::as_str).unwrap_or("printerManages"); if cfg!(windows) && send && !dry && output.is_none() && native_rgb_compatible(&page, handling) { + require_printing_enabled()?; let printed = print_windows(&page, p, &doc.name, copies)?; return Ok(json!({ "pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, @@ -431,6 +426,7 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result { let mut sent = false; let mut spool = Value::Null; if send && !dry { + require_printing_enabled()?; spool = json!(craft_print::submit(&pdf, &job).map_err(other)?); sent = true; } @@ -569,6 +565,14 @@ pub fn printing_disabled() -> bool { PRINTING_DISABLED.load(std::sync::atomic::Ordering::Relaxed) || std::env::var_os("PHOTOCRAFT_NO_PRINT").is_some_and(|v| !v.is_empty() && v != "0") } +fn require_printing_enabled() -> Result<()> { + if printing_disabled() { + Err(other("printing is disabled in this process (photocraft_engine::print_cmds::disable_printing or PHOTOCRAFT_NO_PRINT); use dryRun: true")) + } else { + Ok(()) + } +} + fn print(s: &mut Session, p: &Value) -> Result { do_print(s, p, "file.print") } From 3454620f8933241ba3575a26c48c6e9a54f0e75f Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Tue, 13 Oct 2026 06:04:03 +0200 Subject: [PATCH 12/17] Format shared print-disable error --- crates/engine/src/print_cmds.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 9361f7d2b4..87862b65f6 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -567,7 +567,9 @@ pub fn printing_disabled() -> bool { fn require_printing_enabled() -> Result<()> { if printing_disabled() { - Err(other("printing is disabled in this process (photocraft_engine::print_cmds::disable_printing or PHOTOCRAFT_NO_PRINT); use dryRun: true")) + Err(other( + "printing is disabled in this process (photocraft_engine::print_cmds::disable_printing or PHOTOCRAFT_NO_PRINT); use dryRun: true", + )) } else { Ok(()) } From 06387a955c960b3ced7c4267b35e39814c9ae411 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Tue, 13 Oct 2026 06:36:33 +0200 Subject: [PATCH 13/17] Apply CI formatter output for print guard --- crates/engine/src/print_cmds.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs index 87862b65f6..9361f7d2b4 100644 --- a/crates/engine/src/print_cmds.rs +++ b/crates/engine/src/print_cmds.rs @@ -567,9 +567,7 @@ pub fn printing_disabled() -> bool { fn require_printing_enabled() -> Result<()> { if printing_disabled() { - Err(other( - "printing is disabled in this process (photocraft_engine::print_cmds::disable_printing or PHOTOCRAFT_NO_PRINT); use dryRun: true", - )) + Err(other("printing is disabled in this process (photocraft_engine::print_cmds::disable_printing or PHOTOCRAFT_NO_PRINT); use dryRun: true")) } else { Ok(()) } From f85eddf3cc8f1d1934822c4343f42cc2dc8c9075 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Tue, 13 Oct 2026 07:20:25 +0200 Subject: [PATCH 14/17] Complete native printing translations and Serbian theme labels --- crates/ui-egui/src/i18n/cs.tsv | 7 +++++++ crates/ui-egui/src/i18n/de.tsv | 7 +++++++ crates/ui-egui/src/i18n/el.tsv | 7 +++++++ crates/ui-egui/src/i18n/es.tsv | 7 +++++++ crates/ui-egui/src/i18n/fr.tsv | 7 +++++++ crates/ui-egui/src/i18n/hu.tsv | 7 +++++++ crates/ui-egui/src/i18n/id.tsv | 7 +++++++ crates/ui-egui/src/i18n/it.tsv | 7 +++++++ crates/ui-egui/src/i18n/ja.tsv | 7 +++++++ crates/ui-egui/src/i18n/ko.tsv | 7 +++++++ crates/ui-egui/src/i18n/nl.tsv | 7 +++++++ crates/ui-egui/src/i18n/pl.tsv | 7 +++++++ crates/ui-egui/src/i18n/pt-br.tsv | 7 +++++++ crates/ui-egui/src/i18n/ru.tsv | 7 +++++++ crates/ui-egui/src/i18n/sr.tsv | 11 +++++++++++ crates/ui-egui/src/i18n/tr.tsv | 7 +++++++ crates/ui-egui/src/i18n/uk.tsv | 7 +++++++ crates/ui-egui/src/i18n/vi.tsv | 7 +++++++ crates/ui-egui/src/i18n/zh-hans.tsv | 7 +++++++ crates/ui-egui/src/i18n/zh-hant.tsv | 7 +++++++ 20 files changed, 144 insertions(+) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4fdabb4406..312fca6fba 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3703,3 +3703,10 @@ navigator Zoom Zvětšení Step {step} is waiting for its dialog Krok {step} čeká na svůj dialog @plural {n} action|{n} actions {n} akce|{n} akce|{n} akcí Auto Add/Delete Automaticky přidat/odstranit + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nezapínejte současně zrcadlení v nastavení tisku: obě převrácení se navzájem zruší. + Print Settings… Nastavení tisku… + Remember to turn off the printer's own colour management in Print Settings… Nezapomeňte v nastavení tisku vypnout vlastní správu barev tiskárny… + Sent to {printer} Odesláno do {printer} + set in Print Settings… nastavuje se v nastavení tisku… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index be910dda32..86dbf56351 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2735,3 +2735,10 @@ curves Smooth Glätten Step {step} is waiting for its dialog Schritt {step} wartet auf seinen Dialog @plural {n} action|{n} actions {n} Aktion|{n} Aktionen Auto Add/Delete Autom. hinzuf./löschen + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Aktiviere nicht zusätzlich das Spiegelbild in den Druckeinstellungen: Die beiden Spiegelungen heben sich auf. + Print Settings… Druckeinstellungen… + Remember to turn off the printer's own colour management in Print Settings… Denke daran, die eigene Farbverwaltung des Druckers in den Druckeinstellungen auszuschalten… + Sent to {printer} An {printer} gesendet + set in Print Settings… in den Druckeinstellungen festlegen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d02c1318aa..94ebb84f0e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3793,3 +3793,10 @@ curves Smooth Εξομάλυνση Step {step} is waiting for its dialog Το βήμα {step} περιμένει το παράθυρο διαλόγου του @plural {n} action|{n} actions {n} ενέργεια|{n} ενέργειες Auto Add/Delete Αυτόματη προσθήκη/διαγραφή + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Μην ενεργοποιείτε επίσης τον κατοπτρισμό στις ρυθμίσεις εκτύπωσης: οι δύο αναστροφές αλληλοαναιρούνται. + Print Settings… Ρυθμίσεις εκτύπωσης… + Remember to turn off the printer's own colour management in Print Settings… Θυμηθείτε να απενεργοποιήσετε τη διαχείριση χρωμάτων του εκτυπωτή στις ρυθμίσεις εκτύπωσης… + Sent to {printer} Στάλθηκε στον {printer} + set in Print Settings… ορίζεται στις ρυθμίσεις εκτύπωσης… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index cdee7d44b9..f3f9893f2a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2776,3 +2776,10 @@ curves Smooth Suavizar Step {step} is waiting for its dialog El paso {step} está esperando su cuadro de diálogo @plural {n} action|{n} actions {n} acción|{n} acciones Auto Add/Delete Añadir/eliminar automáticamente + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. No actives también Imagen especular en Ajustes de impresión: las dos inversiones se anulan. + Print Settings… Ajustes de impresión… + Remember to turn off the printer's own colour management in Print Settings… Recuerda desactivar la gestión de color de la impresora en Ajustes de impresión… + Sent to {printer} Enviado a {printer} + set in Print Settings… se establece en Ajustes de impresión… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index daf5447d76..b0a4aedb6c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3096,3 +3096,10 @@ curves Smooth Lisser Step {step} is waiting for its dialog L’étape {step} attend sa boîte de dialogue @plural {n} action|{n} actions {n} action|{n} actions Auto Add/Delete Ajout/suppr. auto + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Ne cochez pas aussi Image miroir dans les paramètres d’impression : les deux inversions s’annulent. + Print Settings… Paramètres d’impression… + Remember to turn off the printer's own colour management in Print Settings… Pensez à désactiver la gestion des couleurs de l’imprimante dans les paramètres d’impression… + Sent to {printer} Envoyé à {printer} + set in Print Settings… défini dans les paramètres d’impression… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index ef7905b881..d0da3a93c7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4016,3 +4016,10 @@ cameraRaw Yellow Sárga Loaded Camera Raw settings from {file} Camera Raw-beállítások betöltve innen: {file} Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw-beállítások betöltve innen: {file} ({n} nem támogatott) Auto Add/Delete Automatikus hozzáadás/törlés + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. A nyomtatási beállításokban ne jelöld be a tükrözést is: a két tükrözés kioltja egymást. + Print Settings… Nyomtatási beállítások… + Remember to turn off the printer's own colour management in Print Settings… Ne felejtsd el kikapcsolni a nyomtató saját színkezelését a nyomtatási beállításokban… + Sent to {printer} Elküldve ide: {printer} + set in Print Settings… a nyomtatási beállításokban adható meg… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index db948970fe..10876b8572 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3083,3 +3083,10 @@ curves Smooth Haluskan Step {step} is waiting for its dialog Langkah {step} menunggu dialognya @plural {n} action|{n} actions {n} tindakan Auto Add/Delete Tambah/Hapus Otomatis + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Jangan aktifkan juga Gambar Cermin di Pengaturan Cetak: kedua pembalikan saling meniadakan. + Print Settings… Pengaturan Cetak… + Remember to turn off the printer's own colour management in Print Settings… Ingat untuk menonaktifkan pengelolaan warna milik printer di Pengaturan Cetak… + Sent to {printer} Dikirim ke {printer} + set in Print Settings… diatur di Pengaturan Cetak… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index cf4c8962cf..3de380dcde 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4059,3 +4059,10 @@ navigator Zoom Zoom Step {step} is waiting for its dialog Il passaggio {step} attende la sua finestra di dialogo @plural {n} action|{n} actions {n} azione|{n} azioni Auto Add/Delete Aggiungi/elimina automaticamente + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Non attivare anche Immagine speculare nelle impostazioni di stampa: le due inversioni si annullano. + Print Settings… Impostazioni di stampa… + Remember to turn off the printer's own colour management in Print Settings… Ricorda di disattivare la gestione del colore della stampante nelle impostazioni di stampa… + Sent to {printer} Inviato a {printer} + set in Print Settings… impostato nelle impostazioni di stampa… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 19c36d54ab..7620e9ad57 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3705,3 +3705,10 @@ curves Smooth スムーズ Step {step} is waiting for its dialog ステップ {step} はダイアログを待っています @plural {n} action|{n} actions アクション {n} 個 Auto Add/Delete 自動追加・削除 + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 印刷設定の「鏡像」も有効にしないでください。2回反転すると元に戻ります。 + Print Settings… 印刷設定… + Remember to turn off the printer's own colour management in Print Settings… 印刷設定でプリンター独自のカラーマネジメントを無効にしてください… + Sent to {printer} {printer} に送信しました + set in Print Settings… 印刷設定で指定… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7857b418b7..fa32cf82d0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3265,3 +3265,10 @@ curves Smooth 매끄럽게 Step {step} is waiting for its dialog {step}단계가 대화 상자를 기다리고 있습니다 @plural {n} action|{n} actions 액션 {n}개 Auto Add/Delete 자동 추가/삭제 + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 인쇄 설정에서도 이미지 반전을 켜지 마세요. 두 번 반전하면 원래대로 돌아갑니다. + Print Settings… 인쇄 설정… + Remember to turn off the printer's own colour management in Print Settings… 인쇄 설정에서 프린터 자체의 색상 관리를 끄세요… + Sent to {printer} {printer}(으)로 전송됨 + set in Print Settings… 인쇄 설정에서 지정… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a7f7c2ae13..9412f08f4a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3855,3 +3855,10 @@ curves Smooth Vloeiend maken Step {step} is waiting for its dialog Stap {step} wacht op zijn dialoogvenster @plural {n} action|{n} actions {n} handeling|{n} handelingen Auto Add/Delete Automatisch toevoegen/verwijderen + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Schakel niet ook Spiegelbeeld in bij de afdrukinstellingen: de twee spiegelingen heffen elkaar op. + Print Settings… Afdrukinstellingen… + Remember to turn off the printer's own colour management in Print Settings… Vergeet niet het eigen kleurbeheer van de printer uit te schakelen in de afdrukinstellingen… + Sent to {printer} Verzonden naar {printer} + set in Print Settings… instellen in de afdrukinstellingen… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0c82ac3b9b..24749182ea 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3692,3 +3692,10 @@ curves Smooth Wygładź Step {step} is waiting for its dialog Krok {step} czeka na swoje okno dialogowe @plural {n} action|{n} actions {n} operacja|{n} operacje|{n} operacji Auto Add/Delete Automatyczne dodawanie/usuwanie + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nie włączaj też odbicia lustrzanego w ustawieniach druku: oba odbicia wzajemnie się znoszą. + Print Settings… Ustawienia druku… + Remember to turn off the printer's own colour management in Print Settings… Pamiętaj o wyłączeniu zarządzania kolorami drukarki w ustawieniach druku… + Sent to {printer} Wysłano do {printer} + set in Print Settings… ustawiane w ustawieniach druku… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 199fa97345..9fe2601cf6 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3885,3 +3885,10 @@ layerLabel No Color Sem cor Step {step} is waiting for its dialog A etapa {step} está aguardando sua caixa de diálogo @plural {n} action|{n} actions {n} ação|{n} ações Auto Add/Delete Adicionar/excluir automaticamente + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Não ative também a imagem espelhada nas configurações de impressão: as duas inversões se anulam. + Print Settings… Configurações de impressão… + Remember to turn off the printer's own colour management in Print Settings… Lembre-se de desativar o gerenciamento de cores da própria impressora nas configurações de impressão… + Sent to {printer} Enviado para {printer} + set in Print Settings… definido nas configurações de impressão… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index dd7001bc1f..00ce3f12d0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3040,3 +3040,10 @@ curves Smooth Сгладить Step {step} is waiting for its dialog Шаг {step} ожидает своего диалога @plural {n} action|{n} actions {n} операция|{n} операции|{n} операций Auto Add/Delete Автодобавление/удаление + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Не включайте также зеркальное отражение в параметрах печати: два отражения отменяют друг друга. + Print Settings… Параметры печати… + Remember to turn off the printer's own colour management in Print Settings… Не забудьте отключить управление цветом самого принтера в параметрах печати… + Sent to {printer} Отправлено на {printer} + set in Print Settings… задаётся в параметрах печати… diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 9d8aebef63..76a8a421a0 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4167,3 +4167,14 @@ shape Appearance Izgled Import .GRD Uvezi .GRD Choose a gradient file (.grd). Izaberite datoteku gradijenta (.grd). Auto Add/Delete Automatsko dodavanje/brisanje + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nemojte uključiti i ogledalsku sliku u podešavanjima štampanja: dva preslikavanja se poništavaju. + Print Settings… Podešavanja štampanja… + Remember to turn off the printer's own colour management in Print Settings… Ne zaboravite da isključite upravljanje bojama samog štampača u podešavanjima štampanja… + Sent to {printer} Poslato na {printer} + set in Print Settings… podešava se u podešavanjima štampanja… + Soft dark Blaga tamna + Soft light Blaga svetla + Soft Dark Theme Blaga tamna tema + Soft Light Theme Blaga svetla tema diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 605ffd26f9..fb7ce8f663 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3828,3 +3828,10 @@ cameraData Lens Lens Loaded Camera Raw settings from {file} Camera Raw ayarları {file} dosyasından yüklendi Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw ayarları {file} dosyasından yüklendi ({n} desteklenmiyor) Auto Add/Delete Otomatik Ekle/Sil + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Yazdırma Ayarlarında ayrıca Ayna Görüntüsünü açmayın: iki yansıtma birbirini iptal eder. + Print Settings… Yazdırma Ayarları… + Remember to turn off the printer's own colour management in Print Settings… Yazdırma Ayarlarında yazıcının kendi renk yönetimini kapatmayı unutmayın… + Sent to {printer} {printer} yazıcısına gönderildi + set in Print Settings… Yazdırma Ayarlarında belirlenir… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 712766a793..85418d216f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3793,3 +3793,10 @@ curves Smooth Згладити Step {step} is waiting for its dialog Крок {step} очікує на свій діалог @plural {n} action|{n} actions {n} операція|{n} операції|{n} операцій Auto Add/Delete Автододавання/видалення + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Не вмикайте також дзеркальне відображення в параметрах друку: два відображення скасовують одне одного. + Print Settings… Параметри друку… + Remember to turn off the printer's own colour management in Print Settings… Не забудьте вимкнути керування кольором самого принтера в параметрах друку… + Sent to {printer} Надіслано на {printer} + set in Print Settings… задається в параметрах друку… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7ef6f16dd6..eb66747a1a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3580,3 +3580,10 @@ curves Smooth Làm mượt Import .GRD Nhập .GRD Choose a gradient file (.grd). Chọn tệp chuyển sắc (.grd). Auto Add/Delete Tự động thêm/xóa + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Đừng bật thêm Ảnh phản chiếu trong thiết lập in: hai lần lật sẽ triệt tiêu nhau. + Print Settings… Thiết lập in… + Remember to turn off the printer's own colour management in Print Settings… Nhớ tắt quản lý màu riêng của máy in trong thiết lập in… + Sent to {printer} Đã gửi tới {printer} + set in Print Settings… đặt trong thiết lập in… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 142718f393..e46fd61904 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2700,3 +2700,10 @@ curves Smooth 平滑 Step {step} is waiting for its dialog 步骤 {step} 正在等待其对话框 @plural {n} action|{n} actions {n} 个动作 Auto Add/Delete 自动添加/删除 + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 不要同时勾选打印设置中的镜像:两次翻转会相互抵消。 + Print Settings… 打印设置… + Remember to turn off the printer's own colour management in Print Settings… 请记得在打印设置中关闭打印机自身的色彩管理… + Sent to {printer} 已发送到 {printer} + set in Print Settings… 在打印设置中设置… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8e4da035be..e6e8b921e5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2685,3 +2685,10 @@ curves Smooth 平滑 Step {step} is waiting for its dialog 步驟 {step} 正在等待其對話框 @plural {n} action|{n} actions {n} 個動作 Auto Add/Delete 自動增加/刪除 + +# Native Windows printing qualification + Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 請勿同時勾選列印設定中的鏡像:兩次翻轉會互相抵消。 + Print Settings… 列印設定… + Remember to turn off the printer's own colour management in Print Settings… 請記得在列印設定中關閉印表機本身的色彩管理… + Sent to {printer} 已傳送至 {printer} + set in Print Settings… 在列印設定中設定… From 3a2d657b9aa05292b9b5fc9ef2e959526070ace9 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Tue, 13 Oct 2026 20:43:45 +0200 Subject: [PATCH 15/17] Keep custom paper for Windows PDF exports and repair merged catalogs --- crates/ui-egui/src/file_ui.rs | 19 ++++++++++++++++--- crates/ui-egui/src/i18n/ja.tsv | 7 ------- crates/ui-egui/src/i18n/sr.tsv | 9 +++++---- crates/ui-egui/tests/custom_print_paper.rs | 2 ++ 4 files changed, 23 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index d86f9cf12d..ba7efccaf6 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -726,7 +726,6 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 { f.insert("printer".into(), json!(fallback)); f.remove("printerSettings"); } - driver_page(&mut f); } app.ui.open_dialog(DialogKind::Command, f) } @@ -828,6 +827,22 @@ fn print_paper_controls(ui: &mut egui::Ui, f: &mut Map) { fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { let t = Tokens::get(ui.ctx()); let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return }; + // PDF exports and previews retain editable paper on Windows too. Only a real native + // submission takes its media from the printer; entering that mode refreshes the driver + // geometry after any export-only paper edits. + let printers: Option> = if !b(f, "dryRun", false) && s(f, "output", "").is_empty() { + f.get("__printers").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()) + } else { + None + }; + if printers.is_some() { + if !b(f, "__driverPageInitialized", false) { + driver_page(f); + f.insert("__driverPageInitialized".into(), json!(true)); + } + } else { + f.remove("__driverPageInitialized"); + } let p = params(f); ui.horizontal_top(|ui| { // Page preview. @@ -904,8 +919,6 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map> = - f.get("__printers").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()); if let Some(printers) = &printers { // Windows: Photoshop's Printer menu and Print Settings… (the driver's own dialog). ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d382744c51..905c62874e 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3796,13 +3796,6 @@ curves Smooth スムーズ Sent to {printer} {printer} に送信しました set in Print Settings… 印刷設定で指定… # Restored rows (custom print paper #3820, brush presets, Vanishing Point help, brush panel menu) - Paper Width 用紙の幅 - Paper Height 用紙の高さ - Capture Brush Size in Preset ブラシサイズをプリセットに保存 - Include Tool Settings ツール設定を含める - Include Color カラーを含める - Enter a name for the brush preset ブラシプリセットの名前を入力してください - A brush preset with this name already exists この名前のブラシプリセットは既に存在します Drag to pan · Scroll to zoom · Double-click to fit ドラッグで移動 · スクロールでズーム · ダブルクリックで全体表示 Clear Brush Controls ブラシのコントロールを消去 Reset All Locked Settings ロックされた設定をすべて初期化 diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 3d01325ef8..66fd394b20 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4192,10 +4192,11 @@ shape Appearance Izgled Remember to turn off the printer's own colour management in Print Settings… Ne zaboravite da isključite upravljanje bojama samog štampača u podešavanjima štampanja… Sent to {printer} Poslato na {printer} set in Print Settings… podešava se u podešavanjima štampanja… - Soft dark Blaga tamna - Soft light Blaga svetla - Soft Dark Theme Blaga tamna tema - Soft Light Theme Blaga svetla tema # Custom print paper (#3820) Paper Width Širina papira Paper Height Visina papira + +# Layer mask selection commands + Add Mask to Selection Dodaj masku izboru + Subtract Mask from Selection Oduzmi masku od izbora + Intersect Mask with Selection Presek maske i izbora diff --git a/crates/ui-egui/tests/custom_print_paper.rs b/crates/ui-egui/tests/custom_print_paper.rs index 7361468bbc..d0d81dea69 100644 --- a/crates/ui-egui/tests/custom_print_paper.rs +++ b/crates/ui-egui/tests/custom_print_paper.rs @@ -10,6 +10,8 @@ fn app() -> (PhotocraftApp, u64) { let id = open_print(&mut app); // Every UI path in these fixtures is safe even if an unexpected Enter confirms the dialog. app.ui.dialog_mut(id).unwrap().fields.insert("dryRun".into(), json!(true)); + // Exercise PDF paper controls even when native printers are available, on every OS. + app.ui.dialog_mut(id).unwrap().fields.insert("__printers".into(), json!(["Test native printer"])); (app, id) } From 6c1a3590f5116ad70de1a60b2cb4cdbf290969ed Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Tue, 13 Oct 2026 21:33:44 +0200 Subject: [PATCH 16/17] Remove obsolete app-owned Windows printing layer comment --- xtask/src/layers.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index e78613f37a..2128345148 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -46,7 +46,6 @@ pub const TABLE: &[(&str, Class)] = &[ ("adobe-assets", Class::Standalone), // Pen tablet input (the one isolated `unsafe` helper: AppKit interop on macOS). ("tablet", Class::Standalone), - // Windows printing (an isolated `unsafe` helper: winspool and GDI). ("doc", Class::Layer(1)), ("ops", Class::Layer(2)), ("paint", Class::Layer(2)), From a9ac922fc12a07cf5bf228644130693db45bcbd1 Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Wed, 14 Oct 2026 02:21:09 +0200 Subject: [PATCH 17/17] Align printer menu regression with the merged system-printer cache --- crates/ui-egui/src/file_ui.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs index 9809f33c96..c3b8abc4d7 100644 --- a/crates/ui-egui/src/file_ui.rs +++ b/crates/ui-egui/src/file_ui.rs @@ -1445,7 +1445,8 @@ mod tests { let (mut app, ctx) = app(); let id = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap(); let f = &app.ui.dialog_mut(id).unwrap().fields; - assert!(f.get("__printers").is_some_and(Value::is_array)); + assert!(f.get("__systemPrinters").is_some_and(Value::is_array)); + assert!(params(f).get("__systemPrinters").is_none()); assert!(params(f).get("__printers").is_none()); }