LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
LRC-PRINT-JOB: colour-managed print PDFs (printer profiles, intent, black point compensation, print adjustment, print sharpening)
Atmik Shetty65775b47160a
diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rsindex 4fa77df86..b9033ad05 100644--- a/crates/engine/src/cmd/print.rs+++ b/crates/engine/src/cmd/print.rs@@ -247,6 +247,8 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {s.check_write_target(path).map_err(|e| bad(ID, e))?;let ids = s.targets(p);let settings = s.print.clone();+ // a printer profile that can't be used fails the print before anything renders+ crate::print_color::PrintColorJob::new(&settings.job.color).map_err(|e| bad(ID, e))?;let title = std::path::Path::new(path).file_stem().and_then(|n| n.to_str()).unwrap_or("Print").to_string();let work = crate::print::compose::prepare(s, &settings, &ids).map_err(|e| bad(ID, e))?;let total = work.len() as u64;@@ -322,7 +324,7 @@ pub fn specs() -> Vec<CommandSpec> {"{ids?} → {settings: {layout, image, page, guides, job}, papers, pageWidth, pageHeight, printable, pageCount, cellsPerPage, gridCells?, overlaps}; lengths are inches",always, get),cmd!(query "print.set", "Set Print Settings", [], None,- "{layout?: {style: singleImage|contactSheet|picturePackage|customPackage, page: {paper, customWidth, customHeight, orientation: portrait|landscape, margins: {top,right,bottom,left}}, grid: {columns, rows, spacingX, spacingY, keepSquare}, spacing}, image?: {zoomToFill, rotateToFit, borderEnabled, borderWidth, borderColor: [r,g,b], strokeEnabled, strokeWidthPt, strokeColor}, page?: {background: [r,g,b]}, guides?: {showRulers, units: in|cm|mm|pt, snap: off|cells|grid, gridSize, showMargins, showBleed, showPageGrid, showCells, showDimensions}, job?: {ppi: 72..720}} — merges into the current print; cells and pages change with print.cell.* / print.layout.*; → print.get",+ "{layout?: {style: singleImage|contactSheet|picturePackage|customPackage, page: {paper, customWidth, customHeight, orientation: portrait|landscape, margins: {top,right,bottom,left}}, grid: {columns, rows, spacingX, spacingY, keepSquare}, spacing}, image?: {zoomToFill, rotateToFit, borderEnabled, borderWidth, borderColor: [r,g,b], strokeEnabled, strokeWidthPt, strokeColor}, page?: {background: [r,g,b]}, guides?: {showRulers, units: in|cm|mm|pt, snap: off|cells|grid, gridSize, showMargins, showBleed, showPageGrid, showCells, showDimensions}, job?: {ppi: 72..720, color?: {profile: {kind: managed, space: srgb|adobeRgb} | {kind: icc, path}, intent: perceptual|relative, blackPointCompensation, brightness: -100..100, contrast: -100..100, sharpen: off|low|standard|high, media: matte|glossy, sixteenBit}}} — merges into the current print; cells and pages change with print.cell.* / print.layout.*; → print.get",always, set),cmd!(query "print.reset", "Reset Print Settings", [], None, "{} → print.get", always, reset),cmd!(query "print.cell.add", "Add Print Cell", [], None,diff --git a/crates/engine/src/contact_sheet.rs b/crates/engine/src/contact_sheet.rsindex af4228e67..e83ad8c67 100644--- a/crates/engine/src/contact_sheet.rs+++ b/crates/engine/src/contact_sheet.rs@@ -197,14 +197,14 @@ fn blit(dst: &mut Rgba8, src: &Rgba8, x: usize, y: usize) -> Result<(), String>}// Minimal PDF 1.4: one JPEG XObject per page, explicit byte lengths and classic xref offsets.-pub(crate) struct Pdf {- pub(crate) bytes: Vec<u8>,+struct Pdf {+ bytes: Vec<u8>,offsets: Vec<usize>,points: (f64, f64),}impl Pdf {- pub(crate) fn new(pages: usize, points: (f64, f64)) -> Self {+ fn new(pages: usize, points: (f64, f64)) -> Self {let mut p = Self { bytes: b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(), offsets: vec![0], points };p.object(1, b"<< /Type /Catalog /Pages 2 0 R >>");let kids = (0..pages).map(|i| format!("{} 0 R", 3 + i * 3)).collect::<Vec<_>>().join(" ");@@ -226,7 +226,7 @@ impl Pdf {self.object(id, &body);}- pub(crate) fn page(&mut self, index: usize, jpg: &[u8], width: usize, height: usize) {+ fn page(&mut self, index: usize, jpg: &[u8], width: usize, height: usize) {let id = 3 + index * 3;let (w, h) = self.points;self.object(@@ -246,7 +246,7 @@ impl Pdf {);}- pub(crate) fn finish(mut self) -> Vec<u8> {+ fn finish(mut self) -> Vec<u8> {let start = self.bytes.len();self.bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", self.offsets.len()).as_bytes());for offset in self.offsets.iter().skip(1) {diff --git a/crates/engine/src/pdf.rs b/crates/engine/src/pdf.rsindex 29f0b73f7..abce4061e 100644--- a/crates/engine/src/pdf.rs+++ b/crates/engine/src/pdf.rs@@ -31,6 +31,8 @@ pub enum ImageData {Raw { bits: u8, samples: Vec<u8> },/// A baseline JPEG stream, copied into the file as it is.Jpeg(Vec<u8>),+ /// Samples already compressed with zlib (see [`PdfImage::deflated`]), `bits` per component.+ Flate { bits: u8, data: Vec<u8> },}/// A raster image and the colour space its samples are in.@@ -52,6 +54,17 @@ impl PdfImage {PdfImage { width, height, channels, data: ImageData::Raw { bits: 16, samples: bytes }, icc }}+ /// The same image with its samples compressed now (checked first), so a long print doesn't+ /// hold every page's uncompressed samples until the file is written.+ pub fn deflated(self) -> Result<PdfImage, String> {+ self.check()?;+ let data = match self.data {+ ImageData::Raw { bits, samples } => ImageData::Flate { bits, data: deflate(&samples) },+ other => other,+ };+ Ok(PdfImage { data, ..self })+ }+fn check(&self) -> Result<(), String> {if self.width == 0 || self.height == 0 || self.width > MAX_IMAGE_SIDE || self.height > MAX_IMAGE_SIDE {return Err(format!("an image of {} × {} pixels can't be written", self.width, self.height));@@ -74,6 +87,11 @@ impl PdfImage {return Err("the image isn't a JPEG stream".into());}}+ ImageData::Flate { bits, data } => {+ if !matches!(bits, 8 | 16) || data.is_empty() {+ return Err("a compressed image has 8 or 16 bits per component and some data".into());+ }+ }}Ok(())}@@ -253,9 +271,10 @@ pub fn write(pages: &[PdfPage], info: &PdfInfo) -> Result<Vec<u8>, String> {},};let id = w.reserve();- let (bits, filter, data) = match &image.data {- ImageData::Raw { bits, samples } => (*bits, "/FlateDecode", deflate(samples)),- ImageData::Jpeg(jpeg) => (8, "/DCTDecode", jpeg.clone()),+ let (bits, filter, data): (u8, &str, std::borrow::Cow<[u8]>) = match &image.data {+ ImageData::Raw { bits, samples } => (*bits, "/FlateDecode", deflate(samples).into()),+ ImageData::Flate { bits, data } => (*bits, "/FlateDecode", data.as_slice().into()),+ ImageData::Jpeg(jpeg) => (8, "/DCTDecode", jpeg.as_slice().into()),};w.object(id,@@ -444,6 +463,21 @@ mod tests {assert_eq!(dicts[2].1, jpeg, "JPEG streams are copied as they are");}+ #[test]+ fn compressing_early_writes_the_same_file() {+ let samples: Vec<u16> = (0..4 * 3 * 3).map(|i| (i * 977) as u16).collect();+ let raw = PdfImage::from_u16(4, 3, 3, &samples, Some(srgb()));+ let early = raw.clone().deflated().unwrap();+ assert!(matches!(early.data, ImageData::Flate { bits: 16, .. }));+ let at = full(100.0, 75.0);+ let a = write(&[page(vec![(raw, at)])], &PdfInfo::default()).unwrap();+ let b = write(&[page(vec![(early, at)])], &PdfInfo::default()).unwrap();+ assert_eq!(a, b);+ let mut short = PdfImage::from_u16(4, 3, 3, &samples, None);+ short.width = 5;+ assert!(short.deflated().is_err(), "checked before compressing");+ }+#[test]fn hostile_documents_are_errors() {let ok = || PdfImage::from_u16(1, 1, 3, &[1, 2, 3], None);diff --git a/crates/engine/src/print/compose.rs b/crates/engine/src/print/compose.rsindex 58b29b0d9..91e5db69e 100644--- a/crates/engine/src/print/compose.rs+++ b/crates/engine/src/print/compose.rs@@ -402,6 +402,8 @@ pub struct Prepared {ppi: f32,background: [u16; 3],style: CellStyle,+ /// Print sharpening, applied to each photo once it's rendered at its print size.+ color: crate::print_color::PrintColorSettings,}impl Prepared {@@ -437,7 +439,7 @@ impl Prepared {let at = match at {Some(at) => at,None => {- let img = render(item.job).map_err(|e| format!("{}: {e}", item.name))?;+ let img = render(item.job, &self.color).map_err(|e| format!("{}: {e}", item.name))?;if cache.len() >= RENDER_CACHE {cache.remove(0);}@@ -457,9 +459,11 @@ impl Prepared {}}-fn render(job: RenderJob) -> Result<Image16, String> {+fn render(job: RenderJob, color: &crate::print_color::PrintColorSettings) -> Result<Image16, String> {let rendered = job.run().rendered?;- let deep = rendered.deep.ok_or("the render has no 16-bit samples")?;+ let mut deep = rendered.deep.ok_or("the render has no 16-bit samples")?;+ // print sharpening for the paper, at the size the photo prints+ color.sharpen_photo(&mut deep);let DeepSamples::U16(rgb) = deep.samples else { return Err("the render is not 16-bit".into()) };if deep.space != OutputSpace::Rec2020 || rgb.len() != deep.width.saturating_mul(deep.height).saturating_mul(3) {return Err("the render is not Rec. 2020 RGB".into());@@ -498,7 +502,14 @@ pub fn prepare(session: &mut Session, settings: &PrintSettings, photos: &[PhotoIitems.push(Item { page, name, cell, key: (id.0, rw, rh), job });}}- Ok(Prepared { pages: vec![(pw, ph); plan.len()], items, ppi: ppi as f32, background: rec2020_from_srgb8(settings.page.background), style })+ Ok(Prepared {+ pages: vec![(pw, ph); plan.len()],+ items,+ ppi: ppi as f32,+ background: rec2020_from_srgb8(settings.page.background),+ style,+ color: settings.job.color.clone(),+ })}#[cfg(test)]diff --git a/crates/engine/src/print/mod.rs b/crates/engine/src/print/mod.rsindex a9ca3e35f..c984cbf54 100644--- a/crates/engine/src/print/mod.rs+++ b/crates/engine/src/print/mod.rs@@ -31,17 +31,20 @@ pub struct PageRaster {pub rgb: Vec<u16>,}-/// How a print job is produced (Lightroom's Print Job panel; colour management joins it later).+/// How a print job is produced (Lightroom's Print Job panel): resolution, and the colour+/// management, print adjustment, print sharpening and depth of [`crate::print_color`].#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]#[serde(default, rename_all = "camelCase", deny_unknown_fields)]pub struct PrintJob {/// Print resolution in pixels per inch, 72 to 720.pub ppi: f32,+ /// Profile, rendering intent, black point compensation, print adjustment, print sharpening.+ pub color: crate::print_color::PrintColorSettings,}impl Default for PrintJob {fn default() -> Self {- Self { ppi: 240.0 }+ Self { ppi: 240.0, color: crate::print_color::PrintColorSettings::default() }}}@@ -54,11 +57,10 @@ impl PrintJob {/// Rejects a resolution outside the supported range (commands and templates, which should/// say so rather than silently clamp).pub fn validate(&self) -> Result<(), String> {- if self.ppi.is_finite() && (MIN_PPI..=MAX_PPI).contains(&self.ppi) {- Ok(())- } else {- Err(format!("ppi must be a number from {MIN_PPI} to {MAX_PPI}"))+ if !(self.ppi.is_finite() && (MIN_PPI..=MAX_PPI).contains(&self.ppi)) {+ return Err(format!("ppi must be a number from {MIN_PPI} to {MAX_PPI}"));}+ self.color.validate()}}@@ -70,14 +72,20 @@ mod tests {fn ppi_is_clamped_and_validated() {assert_eq!(PrintJob::default().effective_ppi(), 240.0);for (v, e) in [(10.0, 72.0), (5000.0, 720.0), (f32::NAN, 240.0), (f32::INFINITY, 240.0), (300.0, 300.0)] {- assert_eq!(PrintJob { ppi: v }.effective_ppi(), e);+ assert_eq!(PrintJob { ppi: v, ..Default::default() }.effective_ppi(), e);}- assert!(PrintJob { ppi: 300.0 }.validate().is_ok());+ assert!(PrintJob { ppi: 300.0, ..Default::default() }.validate().is_ok());for bad in [0.0, 71.0, 721.0, f32::NAN, f32::NEG_INFINITY] {- assert!(PrintJob { ppi: bad }.validate().is_err());+ assert!(PrintJob { ppi: bad, ..Default::default() }.validate().is_err());}let j: PrintJob = serde_json::from_str("{}").unwrap();assert_eq!(j, PrintJob::default());assert!(serde_json::from_str::<PrintJob>(r#"{"dpi": 1}"#).is_err());+ // the colour settings ride along, defaults filled in, and are validated with the job+ let j: PrintJob = serde_json::from_str(r#"{"ppi": 300, "color": {"intent": "relative", "brightness": 20}}"#).unwrap();+ assert_eq!(j.color.intent, crate::print_color::PrintIntent::Relative);+ assert!(j.color.black_point_compensation && j.validate().is_ok());+ let j: PrintJob = serde_json::from_str(r#"{"color": {"contrast": 500}}"#).unwrap();+ assert!(j.validate().is_err());}}diff --git a/crates/engine/src/print/output.rs b/crates/engine/src/print/output.rsindex 937884a8e..e1c69e373 100644--- a/crates/engine/src/print/output.rs+++ b/crates/engine/src/print/output.rs@@ -1,10 +1,11 @@-//! Writes composed pages as a PDF.-//!-//! Interim writer: each page is converted from Rec. 2020 to 8-bit sRGB and embedded as a JPEG-//! covering the paper. Colour-managed output replaces the body of [`write`], not its signature.+//! Writes composed pages as a print-ready PDF: each page is converted to the job's colour target+//! (a printer / paper profile, or sRGB / Adobe RGB when the printer manages colour) with its+//! intent, black point compensation and print adjustment ([`crate::print_color`]), then embedded+//! covering the paper as an ICC-tagged, losslessly compressed 16-bit (or 8-bit) image. A printer+//! profile is also named as the document's output intent ([`crate::pdf`]).use super::{MAX_JOB_PAGES, PageRaster, PrintJob};-use crate::contact_sheet::Pdf;-use crate::export::{ExportFormat, ExportOptions, encode_image};+use crate::pdf::ImageData;+use crate::print_color::PrintColorJob;use lightcraft_color::transfer::encode_srgb8;use lightcraft_color::{REC2020, SRGB};use lightcraft_pipeline::OutputSpace;@@ -34,9 +35,9 @@ pub fn page_to_srgb8(page: &PageRaster) -> Result<Rgba8, String> {}/// The PDF for `pages` (all the same size): one page per raster, its MediaBox the paper size in-/// points (`pixels / ppi * 72`) with the image covering it.+/// points (`pixels / ppi * 72`) with the image covering it. Each page is converted and compressed+/// in turn, so memory holds one page's device samples at a time.pub fn write(pages: &[PageRaster], job: &PrintJob, title: &str) -> Result<Vec<u8>, String> {- let _ = (job, title);let first = pages.first().ok_or("nothing to print")?;if pages.len() > MAX_JOB_PAGES {return Err(format!("a print is limited to {MAX_JOB_PAGES} pages"));@@ -46,19 +47,23 @@ pub fn write(pages: &[PageRaster], job: &PrintJob, title: &str) -> Result<Vec<u8}let points = |px: u32| f64::from(px) / f64::from(first.ppi) * 72.0;let size = (points(first.width), points(first.height));- let mut pdf = Pdf::new(pages.len(), size);- for (i, page) in pages.iter().enumerate() {+ let color = PrintColorJob::new(&job.color)?;+ let mut out = Vec::with_capacity(pages.len());+ let mut bytes = 0usize;+ for page in pages {if (page.width, page.height) != (first.width, first.height) {return Err("all pages of a PDF must be the same size".into());}- let rgba = page_to_srgb8(page)?;- let jpg = encode_image(&rgba, &ExportOptions { format: ExportFormat::Jpeg, quality: 92, ..Default::default() })?;- if pdf.bytes.len().saturating_add(jpg.len()) > MAX_PDF_BYTES {- return Err("the PDF would exceed 256 MiB; lower the print resolution or print fewer pages".into());+ let image = color.page_image(page.width, page.height, &page.rgb)?.deflated()?;+ if let ImageData::Flate { data, .. } = &image.data {+ bytes = bytes.saturating_add(data.len());}- pdf.page(i, &jpg, page.width as usize, page.height as usize);+ if bytes > MAX_PDF_BYTES {+ return Err("the PDF would exceed 256 MiB; lower the print resolution, use 8 bits or print fewer pages".into());+ }+ out.push((size, image));}- Ok(pdf.finish())+ color.pdf(out, title)}#[cfg(test)]@@ -94,6 +99,8 @@ mod tests {let nums: Vec<f64> = text[at..].split(']').next().unwrap().split_whitespace().map(|v| v.parse().unwrap()).collect();assert_eq!((nums[2], nums[3]), (306.0, 396.0), "4.25 x 5.5 in is 306 x 396 pt");assert!(text.contains("/Width 425 /Height 550"));+ // managed by the printer: sRGB, 16 bits, tagged, no output intent+ assert!(text.contains("/ICCBased") && text.contains("/BitsPerComponent 16") && !text.contains("/OutputIntents"));assert!(write(&[], &PrintJob::default(), "t").is_err());let mixed = [raster(10, 10, [0; 3]), raster(10, 12, [0; 3])];assert!(write(&mixed, &PrintJob::default(), "t").is_err());@@ -102,4 +109,28 @@ mod tests {let zero = PageRaster { ppi: 0.0, ..raster(4, 4, [0; 3]) };assert!(write(&[zero], &PrintJob::default(), "t").is_err());}++ #[test]+ fn a_printer_profile_is_converted_to_and_named_as_the_output_intent() {+ use crate::print_color::{PrintColorSettings, PrintIntent, PrintProfile};+ let dir = std::env::temp_dir().join(format!("lc-print-output-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let icc = dir.join("Lustre Paper.icc");+ std::fs::write(&icc, lightcraft_codecs::icc::write_named(lightcraft_codecs::NamedSpace::AdobeRgb)).unwrap();+ let color =+ PrintColorSettings { profile: PrintProfile::Icc { path: icc }, intent: PrintIntent::Relative, sixteen_bit: false, ..Default::default() };+ let job = PrintJob { color, ..Default::default() };+ let bytes = write(&[raster(20, 30, [200, 30, 30])], &job, "Lustre").unwrap();+ let text = String::from_utf8_lossy(&bytes);+ assert!(text.contains("/OutputIntents") && text.contains("/DestOutputProfile"), "{}", &text[..text.len().min(500)]);+ assert!(text.contains("/BitsPerComponent 8") && text.contains("/Title (Lustre)"));+ // a profile that isn't one fails the print and says which file+ std::fs::write(dir.join("Junk.icc"), [7u8; 200]).unwrap();+ let junk = PrintJob {+ color: PrintColorSettings { profile: PrintProfile::Icc { path: dir.join("Junk.icc") }, ..Default::default() },+ ..Default::default()+ };+ let err = write(&[raster(2, 2, [0; 3])], &junk, "t").unwrap_err();+ assert!(err.contains("Junk"), "{err}");+ }}diff --git a/crates/engine/src/print_color.rs b/crates/engine/src/print_color.rsindex 540e48952..c897f8990 100644--- a/crates/engine/src/print_color.rs+++ b/crates/engine/src/print_color.rs@@ -110,6 +110,39 @@ impl Default for PrintColorSettings {}}+impl PrintColorSettings {+ /// Refuse settings a command or template shouldn't carry (out-of-range adjustments, an empty+ /// profile path); whether the profile file is usable is checked when the job is built.+ pub fn validate(&self) -> Result<(), String> {+ for (name, v) in [("brightness", self.brightness), ("contrast", self.contrast)] {+ if !(v.is_finite() && (-100.0..=100.0).contains(&v)) {+ return Err(format!("{name} must be a number from -100 to 100"));+ }+ }+ if let PrintProfile::Icc { path } = &self.profile+ && path.as_os_str().is_empty()+ {+ return Err("the printer profile needs a path".into());+ }+ Ok(())+ }++ /// Sharpen one photo for the paper, at the size it prints (before it goes on the page).+ pub fn sharpen_photo(&self, photo: &mut DeepImage) {+ let amount = match self.sharpen {+ PrintSharpen::Off => return,+ PrintSharpen::Low => SharpenAmount::Low,+ PrintSharpen::Standard => SharpenAmount::Standard,+ PrintSharpen::High => SharpenAmount::High,+ };+ let target = match self.media {+ PrintMedia::Matte => SharpenFor::Matte,+ PrintMedia::Glossy => SharpenFor::Glossy,+ };+ output_sharpen_deep(photo, target, amount);+ }+}+/// Read a printer profile, refusing files that can't be one (the parse happens later).fn read_profile(path: &Path) -> Result<Vec<u8>, String> {let shown = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());@@ -163,19 +196,9 @@ impl PrintColorJob {Ok(PrintColorJob { settings: s, transform, intent })}- /// Sharpen one photo for the paper, at the size it prints (before it goes on the page).+ /// Sharpen one photo for the paper ([`PrintColorSettings::sharpen_photo`]).pub fn sharpen_photo(&self, photo: &mut DeepImage) {- let amount = match self.settings.sharpen {- PrintSharpen::Off => return,- PrintSharpen::Low => SharpenAmount::Low,- PrintSharpen::Standard => SharpenAmount::Standard,- PrintSharpen::High => SharpenAmount::High,- };- let target = match self.settings.media {- PrintMedia::Matte => SharpenFor::Matte,- PrintMedia::Glossy => SharpenFor::Glossy,- };- output_sharpen_deep(photo, target, amount);+ self.settings.sharpen_photo(photo);}/// Convert a composed page (16-bit RGB, `Rec2020` output encoding) to the PDF image that covers@@ -312,7 +335,7 @@ mod tests {let bright = PrintColorJob::new(&PrintColorSettings { brightness: 60.0, ..Default::default() }).unwrap().page_image(1, 1, &mid).unwrap();let first = |i: &PdfImage| match &i.data {ImageData::Raw { samples, .. } => u16::from_be_bytes([samples[0], samples[1]]),- ImageData::Jpeg(_) => 0,+ ImageData::Jpeg(_) | ImageData::Flate { .. } => 0,};assert!(first(&bright) > first(&plain) + 1500, "{} vs {}", first(&bright), first(&plain));assert!(print_adjust(0.5, 60.0, 0.0) > 0.5);@@ -340,6 +363,16 @@ mod tests {assert!(dark < 20000 && light > 40000, "the edge gets more contrast: {dark} {light}");}+ #[test]+ fn validation_refuses_out_of_range_settings() {+ assert!(PrintColorSettings::default().validate().is_ok());+ for (b, c) in [(101.0, 0.0), (0.0, -100.5), (f32::NAN, 0.0), (0.0, f32::INFINITY)] {+ assert!(PrintColorSettings { brightness: b, contrast: c, ..Default::default() }.validate().is_err(), "{b} {c}");+ }+ assert!(PrintColorSettings { profile: PrintProfile::Icc { path: PathBuf::new() }, ..Default::default() }.validate().is_err());+ assert!(PrintColorSettings { brightness: -100.0, contrast: 100.0, ..Default::default() }.validate().is_ok());+ }+#[test]fn hostile_pages_are_errors() {let job = PrintColorJob::new(&PrintColorSettings::default()).unwrap();diff --git a/crates/engine/src/tests_print.rs b/crates/engine/src/tests_print.rsindex eb7ab032c..5b890a7f0 100644--- a/crates/engine/src/tests_print.rs+++ b/crates/engine/src/tests_print.rs@@ -213,6 +213,33 @@ fn export_pdf_prints_the_current_settings() {fails(&mut s, "print.exportPdf", json!({"path": path, "ids": ids}));}+#[test]+fn export_pdf_with_a_printer_profile() {+ let mut s = Session::with_demo();+ let ids: Vec<u64> = s.catalog.photos().take(1).map(|p| p.id.0).collect();+ let dir = std::env::temp_dir().join(format!("lightcraft-print-icc-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let icc = dir.join("Fine Art Matte.icc");+ std::fs::write(&icc, lightcraft_codecs::icc::write_named(lightcraft_codecs::NamedSpace::AdobeRgb)).unwrap();+ let color = json!({"profile": {"kind": "icc", "path": icc}, "intent": "relative", "sharpen": "high", "media": "matte", "brightness": 10});+ run(+ &mut s,+ "print.set",+ json!({"layout": {"style": "contactSheet", "grid": {"columns": 1, "rows": 1}, "page": {"paper": "4x6"}}, "job": {"ppi": 72.0, "color": color}}),+ );+ assert_eq!(run(&mut s, "print.get", json!({}))["settings"]["job"]["color"]["media"], "matte");+ let path = temp_pdf("icc");+ run(&mut s, "print.exportPdf", json!({"path": path, "ids": ids}));+ let text = String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into_owned();+ assert!(text.contains("/OutputIntents") && text.contains("/ICCBased") && text.contains("/BitsPerComponent 16"));+ // out-of-range adjustments are refused when set; a missing profile fails before rendering+ fails(&mut s, "print.set", json!({"job": {"color": {"contrast": 150}}}));+ run(&mut s, "print.set", json!({"job": {"color": {"profile": {"kind": "icc", "path": dir.join("gone.icc")}}}}));+ let err = fails(&mut s, "print.exportPdf", json!({"path": path, "ids": ids}));+ assert!(err.contains("gone.icc"), "{err}");+ assert!(s.activity.list().is_empty(), "nothing started");+}+#[test]fn custom_package_prints_each_cells_photo() {let mut s = Session::with_demo();diff --git a/docs/gaps.md b/docs/gaps.mdindex f24cbf5bc..8bea73112 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -1,6 +1,6 @@# Gaps: where LightCraft falls short of Lightroom-> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (gap 15: print layout model; CR3 entry names the EOS R7 C-RAW fix and the refused CRX variants; CI and Windows / Linux entries note the 0.6.0 riscv64 build; camera colour: tone curve from black-and-white camera JPEGs; Compare and Reference get sharp zoom windows; gap 4 shrinks; gap 14: the HDR switch is read from crs XMP; gaps 2 and 10: EOS R5 Mark II CR3 verified) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6+> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-12 · **Change:** minor (gap 15: printer colour management; gap 15: print layout model; CR3 entry names the EOS R7 C-RAW fix and the refused CRX variants; CI and Windows / Linux entries note the 0.6.0 riscv64 build; camera colour: tone curve from black-and-white camera JPEGs; Compare and Reference get sharp zoom windows; gap 4 shrinks; gap 14: the HDR switch is read from crs XMP; gaps 2 and 10: EOS R5 Mark II CR3 verified) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6Every known shortfall, one entry each, ranked by user impact (how many Lightroom users hit it, andhow hard it blocks them), then by effort. **Agents pick work from the top** (the first entry nobody is@@ -29,7 +29,7 @@ Hours are Opus 5.5 agent wall-clock hours (see [target-app-parity.md](target-app| 12 | **Content-aware / generative remove, detect distractions, reflections removal** | REM rows 75%; patch synthesis missing | cleanup work goes back to Photoshop | 25–45 (+ generative model) | [target-app-parity](target-app-parity.md#ai) || 13 | **Lightroom catalog migration is one-way and approximate**: unsupported Adobe profiles / AI settings archived, history kept as data | lightroom-catalog-import.md | switching users lose some looks | 8–12 | [file-format-parity](file-format-parity.md) || 14 | **HDR display** (EDR / Windows HDR); HLG; the headroom limit and SDR rendition from `crs` XMP (the HDR switch, `HDREditMode`, is read) | HDR rows 70%; LR-VIEW-HDR-DISPLAY ⬜ | HDR editing works blind on HDR monitors | 12–25 | [hardware-parity](hardware-parity.md) |-| 15 | **Print module**: printer colour management (profile, rendering intent, black point compensation, print adjustment and sharpening), identity plate / watermark / page numbers / crop marks / photo info overlays, Custom Package Auto Layout, printer-driver Page Setup and direct printing (the Print dialog writes a PDF) | LRC-PRINT rows | Classic users who print | 25–40 | [target-app-parity](target-app-parity.md#features) |+| 15 | **Print module**: identity plate / watermark / page numbers / crop marks / photo info overlays, Custom Package Auto Layout, printer-driver Page Setup and direct printing, JPEG file output (the Print dialog writes a colour-managed PDF) | LRC-PRINT rows | Classic users who print | 15–25 | [target-app-parity](target-app-parity.md#features) || 16 | **Map view, Book, Slideshow module, publish services** | LRC-MAP / BOOK / SS rows ⬜ | Classic users; publish services matter for Flickr / SmugMug workflows | 60–100 | [target-app-parity](target-app-parity.md#features) || 17 | **Tethered capture** | ⬜ | studio photographers | 25–45 + cameras | [hardware-parity](hardware-parity.md) || 18 | **Video**: playback, trim, global edits, export | VID rows 0% | users who mix stills and clips | 25–45 | [target-app-parity](target-app-parity.md#features) |@@ -72,6 +72,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w| Date | Change | Summary ||---|---|---|+| 2026-10-12 | minor | Gap 15: printer colour management lands (printer / paper ICC profiles or Managed by Printer, intent, black point compensation, print adjustment, print sharpening, 16-bit ICC-tagged PDF with an output intent); page overlays and direct printing remain || 2026-10-12 | minor | Gap 15 shrinks: File → Print… is a Print dialog with the four layout styles, cell editing, image settings, guides, page setup and templates; printer colour management, page overlays and direct printing remain || 2026-10-12 | minor | Gap 15: the Print module's layout styles, cells, image settings, templates and PDF are `print.*` commands (CLI, control, MCP); the Print view, printer colour management and page overlays remain || 2026-10-12 | minor | Gap 15: print pages compose in the engine (fit / Zoom to Fill, Rotate to Fit, border, stroke, background) with an interim PDF writer; commands and UI still to land |diff --git a/docs/parity-checklist.md b/docs/parity-checklist.mdindex 4edb4eff5..010506b9f 100644--- a/docs/parity-checklist.md+++ b/docs/parity-checklist.md@@ -1,6 +1,6 @@# Lightroom parity checklist-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (LRC-PRINT-GUIDES and the other print rows: the Print dialog (File → Print…); LRC-PRINT-LAYOUTSTYLE, LRC-PRINT-CELLS, LRC-PRINT-TEMPLATES and the other print rows: `print.*` commands; LRC-PRINT-IMAGESETTINGS: print page composition (fit / Zoom to Fill, Rotate to Fit, border, stroke, background); LRC-PRINT-LAYOUT: print layout model; rapid slider entry; LR-PROF-CAMERACOLOR: tone curve from black-and-white camera JPEGs; LR-VIEW-ZOOM, LR-VIEW-COMPARE: Compare and Reference zoom windows; LR-IMP-FORMATS, LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md; filesystem history retry/Undo/Redo evidence; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (LRC-PRINT-JOB: print colour management and ICC-tagged print PDFs; LRC-PRINT-GUIDES and the other print rows: the Print dialog (File → Print…); LRC-PRINT-LAYOUTSTYLE, LRC-PRINT-CELLS, LRC-PRINT-TEMPLATES and the other print rows: `print.*` commands; LRC-PRINT-IMAGESETTINGS: print page composition (fit / Zoom to Fill, Rotate to Fit, border, stroke, background); LRC-PRINT-LAYOUT: print layout model; rapid slider entry; LR-PROF-CAMERACOLOR: tone curve from black-and-white camera JPEGs; LR-VIEW-ZOOM, LR-VIEW-COMPARE: Compare and Reference zoom windows; LR-IMP-FORMATS, LR-IMP-CAMERA-COVERAGE: EOS R5 Mark II CR3 decodes; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md; filesystem history retry/Undo/Redo evidence; renamed from `parity.md`; Top gaps moved to gaps.md, shortcut notes to ui-parity.md) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what wehave and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good@@ -753,7 +753,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-| LRC-PRINT-GUIDES | Print guides | P2 | ✅ | `cmd:print.set`, `cmd:print.cell.move`, `crates/ui-egui/src/print_view.rs` | rulers in in/cm/mm/pt, snap off/cells/grid with a grid size, and Page Margins / Page Bleed (a fixed 0.125 in outline) / Page Grid / Image Cells / Dimensions guides drawn on the preview || LRC-PRINT-CELLS | Picture-package cells | P2 | ✅ | `cmd:print.cell.add`, `cmd:print.cell.move`, `cmd:print.cell.resize`, `cmd:print.cell.delete`, `cmd:print.cell.stack`, `cmd:print.cell.photo`, `cmd:print.cell.page`, `cmd:print.layout.autoLayout`, `crates/ui-egui/src/print_view.rs` | add cells at standard or custom sizes, drag and resize them on the page preview (snap to cells, grid or off), Send to Back / Backward / Forward / Bring to Front, a photo per cell (Custom Package), Auto Layout packing, New Page, Clear Layout; no Auto Layout for Custom Package || LRC-PRINT-PAGE | Print page options | P2 | 🟡 | `cmd:print.set`, `cmd:export.contactSheet`, `crates/engine/src/print/compose.rs`, `crates/ui-egui/src/print_view.rs` | page background colour and margins in the Print dialog; filename captions in the contact-sheet PDF; no identity plate, watermark, page numbers, crop marks or photo info |-| LRC-PRINT-JOB | Print job & colour management | P2 | 🟡 | `cmd:export.contactSheet`, `cmd:app.contactSheet`, `crates/ui-egui/src/export_task.rs` | PDF export at fixed 150 dpi in sRGB, current edits, background progress/cancel and original protection; no native printer integration, ICC soft proof/print profiles or selectable resolution |+| LRC-PRINT-JOB | Print job & colour management | P2 | 🟡 | `cmd:print.set`, `cmd:print.exportPdf`, `crates/engine/src/print_color.rs`, `crates/codecs/src/print.rs`, `crates/engine/src/pdf.rs`, `cmd:export.contactSheet` | print resolution 72–720 ppi; colour management: Managed by Printer (sRGB / Adobe RGB, profile embedded) or a printer / paper ICC profile (RGB, CMYK or grey) converted here and named as the PDF's output intent; perceptual / relative colorimetric with black point compensation; Print Adjustment brightness / contrast; print sharpening Low / Standard / High for Matte / Glossy; 16-bit (or 8-bit) ICC-tagged lossless page images; a bad profile fails before rendering (`tests_print::export_pdf_with_a_printer_profile`). The contact sheet keeps its fixed 150 dpi sRGB JPEG PDF. Missing: printing to a printer (OS print dialog), JPEG file output, Draft Mode || LRC-PRINT-TEMPLATES | Print templates | P2 | 🟡 | `cmd:print.template.save`, `cmd:print.template.apply`, `cmd:print.template.list`, `cmd:print.template.delete`, `crates/ui-egui/src/print_view.rs` | save, apply and delete named templates (layout, image settings, page, job) at the top of the Print dialog, kept with the library; no built-in templates, no folders, no import / export of template files || LRC-WEB-LAYOUT | Web gallery layouts | OOS | 🚫 | | || LRC-WEB-SITEINFO | Web gallery site info | OOS | 🚫 | | |@@ -787,6 +787,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove| Date | Change | Summary ||---|---|---|+| 2026-10-12 | minor | LRC-PRINT-JOB: print colour management (printer / paper ICC profiles or Managed by Printer, intent, black point compensation, print adjustment, print sharpening) and a 16-bit ICC-tagged PDF with an output intent; still 🟡 (no OS print dialog or JPEG output) || 2026-10-12 | minor | LRC-PRINT-GUIDES, LRC-PRINT-CELLS, LRC-PRINT-LAYOUTSTYLE, LRC-PRINT-IMAGESETTINGS (✅), LRC-PRINT-LAYOUT, LRC-PRINT-PAGE, LRC-PRINT-TEMPLATES (🟡): File → Print… opens the Print dialog with a scaled page preview, rulers and guides, cells dragged and resized with snapping, image settings, page setup and templates, and prints to PDF in the background || 2026-10-12 | minor | LRC-PRINT-LAYOUTSTYLE, LRC-PRINT-IMAGESETTINGS, LRC-PRINT-LAYOUT, LRC-PRINT-CELLS, LRC-PRINT-PAGE, LRC-PRINT-TEMPLATES: the Print module is reachable as 18 `print.*` commands (settings, cells, Auto Layout, PDF, templates saved in prefs.json) from the CLI, control channel and MCP; 🟡 until the Print UI lands, LRC-PRINT-GUIDES stays ⬜ || 2026-10-12 | minor | LRC-PRINT-IMAGESETTINGS: `print/compose.rs` composes pages (Zoom to Fill, Rotate to Fit, Photo Border, Inner Stroke, background) from the layout model into 16-bit Rec. 2020 `PageRaster`s, with an interim sRGB PDF writer in `print/output.rs`; rows stay until commands and UI reach them |