PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Make native RGB color policy explicit and preserve embedded profiles
skylartaylor3702555aa9de
diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rsindex 4093c8dd3..aa8f7d2a8 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<Value> {// 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<Value> {}));}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<Value> {/// 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) -> Resullet 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.rsindex b240efb48..023829d72 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.rsindex e0c572988..ef20e28ce 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.rsindex 0e0033866..103309dcd 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<u8> = (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();