diff --git a/Cargo.lock b/Cargo.lock index 69fea687d..1605548e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2661,6 +2661,16 @@ dependencies = [ "ttf-parser", ] +[[package]] +name = "craft-press-print" +version = "0.1.0" +dependencies = [ + "craft-cms", + "craft-prepress", + "craft-print", + "thiserror 2.0.21", +] + [[package]] name = "craft-print" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c8ae36287..c0e4f0ed5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -142,6 +142,7 @@ craft-pcraft-bundle = { path = "crates/pcraft-bundle" } craft-pkcs7 = { path = "crates/pkcs7" } craft-plotter = { path = "crates/plotter" } craft-prepress = { path = "crates/prepress" } +craft-press-print = { path = "crates/press-print" } craft-print = { path = "crates/print" } craft-proof = { path = "crates/proof" } craft-raster-codecs = { path = "crates/raster-codecs" } diff --git a/README.md b/README.md index a3373f3a3..88c15eb62 100644 --- a/README.md +++ b/README.md @@ -326,6 +326,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation: masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations, comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`. +- [`craft-press-print`](crates/press-print/README.md): press-accurate printing: a PDF page separated + into plates by `craft-prepress`, composited into the printer's RGB profile and printed through + `craft-print`'s RGB transport, application-managed. - [`craft-print`](crates/print/README.md): PDF submission to CUPS and Windows, printer discovery, duplex/copies/colour and driver preferences. PDF generation stays in each app. - [`craft-proof`](crates/proof/README.md): proofing per language (spelling, suggestions, grammar, diff --git a/crates/prepress/README.md b/crates/prepress/README.md index fe559e8d4..6da17e334 100644 --- a/crates/prepress/README.md +++ b/crates/prepress/README.md @@ -163,7 +163,9 @@ let worst = over.regions().first().copied(); `Plates::composite_to(enabled, &output)` returns the enabled inks in an output profile, for a print or a proof. `Output::new(press, output, intent, bpc)` takes the press's CMYK profile -(`CmsConversion::profile`) and a gray, RGB or CMYK output profile: +(`CmsConversion::profile`) and a gray, RGB or CMYK output profile. `press_profile(pdf, page, +&opts)` returns the press a page's plates separate through (its output intent's profile, else +the fallback's; `None` for the device formulas), so the composite converts from the same one: - the process plates convert from the press straight to the output (CMYK to PCS to output), not through sRGB, at `intent`, with black point compensation when `bpc`. Relative diff --git a/crates/prepress/src/lib.rs b/crates/prepress/src/lib.rs index 1afc7cf6f..7f8a5518f 100644 --- a/crates/prepress/src/lib.rs +++ b/crates/prepress/src/lib.rs @@ -21,4 +21,6 @@ pub use coverage::{Above, Coverage, InkStats, MAX_REGIONS, Region, Stats}; pub use ink::{Alternate, Ink, InkColor, InkId, InkSet, Overprint, Process, Spot, normalize_name, to_pdf_color}; pub use marks::{MarkOptions, Marks, MarksError}; pub use output::{Output, OutputError}; -pub use plates::{Band, Conversion, Error, Fallback, MAX_BANDED_PIXELS, MAX_PLATE_PIXELS, MAX_SPOT_INKS, Options, Plates, plates, plates_in_bands}; +pub use plates::{ + Band, Conversion, Error, Fallback, MAX_BANDED_PIXELS, MAX_PLATE_PIXELS, MAX_SPOT_INKS, Options, Plates, plates, plates_in_bands, press_profile, +}; diff --git a/crates/prepress/src/plates.rs b/crates/prepress/src/plates.rs index b2e818efa..6c7752d97 100644 --- a/crates/prepress/src/plates.rs +++ b/crates/prepress/src/plates.rs @@ -16,6 +16,7 @@ use std::ops::ControlFlow; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::{Arc, Mutex}; +use craft_cms::Profile; use craft_pdf::interpret::InterpreterSettings; use craft_pdf::interpret::color::{CmykSimulation, Ink as PdfInk, InkSinkFn, Plate}; use craft_pdf::raster::{self, MAX_SIDE, RenderCache}; @@ -189,6 +190,26 @@ pub fn plates_in_bands(pdf: &[u8], page: usize, dpi: f32, opts: &Options, mut ea separate(pdf, page, dpi, opts, banded_scale, None, &mut each) } +/// The printing condition page `page` (from 0) of `pdf` separates through with `opts`: the CMYK +/// profile of its output intent, else of [`Options::fallback`]. Build an +/// [`Output`](crate::Output) from it, so a composite converts the plates from the profile they +/// were made for. `None` for [`Fallback::DeviceFormulas`] when the page has no usable output +/// intent: those plates are device values of no profile. Never panics. +pub fn press_profile(pdf: &[u8], page: usize, opts: &Options) -> Result, Error> { + let doc = open_slice(pdf, None)?; + if doc.pages().get(page).is_none() { + return Err(Error::NoPage(page)); + } + if let Ok(Some((_, conversion, _))) = catch_unwind(AssertUnwindSafe(|| intent_condition(&doc, page))) { + return Ok(Some(conversion.profile().clone())); + } + Ok(match &opts.fallback { + Fallback::DeviceFormulas => None, + Fallback::Fogra39 => Some(CmsConversion::fogra39().profile().clone()), + Fallback::Profile(icc) => Some(CmsConversion::new(icc)?.profile().clone()), + }) +} + /// Separates in bands of `rows` rows, else as many as fit [`MAX_PLATE_PIXELS`], at `scale_of`'s /// scale. fn separate( @@ -369,17 +390,24 @@ pub(crate) fn pdf_text(bytes: &[u8]) -> String { /// `/OutputIntents` (PDF 2.0), else the catalog's, the first whose `/DestOutputProfile` is a /// CMYK profile craft-cms converts into, a `GTS_PDFX` intent before the others. pub(crate) fn output_intent(pdf: &Pdf, page: usize) -> Option<(CmykSimulation, Conversion)> { - output_intents(pdf, page).iter().find_map(|intent| { + let (intent, conversion, icc) = intent_condition(pdf, page)?; + let simulation = conversion.simulation(&icc); + let condition = text_entry(&intent, OUTPUT_CONDITION_IDENTIFIER); + let profile = simulation + .description() + .map(str::to_string) + .or_else(|| text_entry(&intent, OUTPUT_CONDITION)) + .or_else(|| condition.clone()) + .unwrap_or_else(|| "unnamed CMYK profile".to_string()); + Some((simulation, Conversion::OutputIntent { profile, condition })) +} + +/// The output intent [`output_intent`] picks, its printing condition and its profile's bytes. +fn intent_condition<'a>(pdf: &'a Pdf, page: usize) -> Option<(Dict<'a>, CmsConversion, Vec)> { + output_intents(pdf, page).into_iter().find_map(|intent| { let icc = intent.get::>(DEST_OUTPUT_PROFILE)?.decoded_within(MAX_PROFILE_BYTES).ok()?; - let simulation = CmsConversion::new(&icc).ok()?.simulation(&icc); - let condition = text_entry(intent, OUTPUT_CONDITION_IDENTIFIER); - let profile = simulation - .description() - .map(str::to_string) - .or_else(|| text_entry(intent, OUTPUT_CONDITION)) - .or_else(|| condition.clone()) - .unwrap_or_else(|| "unnamed CMYK profile".to_string()); - Some((simulation, Conversion::OutputIntent { profile, condition })) + let conversion = CmsConversion::new(&icc).ok()?; + Some((intent, conversion, icc.into_owned())) }) } diff --git a/crates/prepress/tests/plates.rs b/crates/prepress/tests/plates.rs index 791d4a44b..f49190a81 100644 --- a/crates/prepress/tests/plates.rs +++ b/crates/prepress/tests/plates.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use craft_cms::{Intent, Profile, Transform, builtin}; -use craft_prepress::{Alternate, CmsConversion, Conversion, Error, Fallback, Ink, InkId, MAX_SPOT_INKS, Options, Process, plates}; +use craft_prepress::{Alternate, CmsConversion, Conversion, Error, Fallback, Ink, InkId, MAX_SPOT_INKS, Options, Process, plates, press_profile}; /// A 40 × 40 pt page with `content` and `resources`, `catalog` entries, and `objects` /// numbered from 5 (each a whole object body). @@ -128,6 +128,26 @@ fn process_color_converts_through_the_output_intent_else_the_fallback() { assert!(matches!(plates(&red(""), 0, 72.0, &broken), Err(Error::Profile(_)))); } +#[test] +fn the_press_profile_is_the_one_the_plates_separate_through() { + let synthetic = builtin::COATED_CMYK_ICC; + let intent = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /DestOutputProfile 5 0 R >>]"; + let red = |catalog: &str| page_pdf("1 0 0 rg 0 0 40 40 re f", "", catalog, &[stream("/N 4", synthetic)]); + let parsed = |icc: &[u8]| Some(Profile::parse(icc).unwrap()); + let defaults = Options::default(); + + assert_eq!(press_profile(&red(intent), 0, &defaults).unwrap(), parsed(synthetic), "the output intent's"); + assert_eq!(press_profile(&red(""), 0, &defaults).unwrap(), parsed(builtin::COATED_FOGRA39_ICC), "FOGRA39"); + let callers = Options { fallback: Fallback::Profile(Arc::from(synthetic)), ..Options::default() }; + assert_eq!(press_profile(&red(""), 0, &callers).unwrap(), parsed(synthetic), "the caller's"); + let formulas = Options { fallback: Fallback::DeviceFormulas, ..Options::default() }; + assert_eq!(press_profile(&red(""), 0, &formulas).unwrap(), None, "device formulas have no profile"); + assert_eq!(press_profile(&red(intent), 0, &formulas).unwrap(), parsed(synthetic), "an output intent still wins"); + assert!(matches!(press_profile(&red(""), 1, &defaults), Err(Error::NoPage(1)))); + let broken = Options { fallback: Fallback::Profile(Arc::from(&b"not a profile"[..])), ..Options::default() }; + assert!(matches!(press_profile(&red(""), 0, &broken), Err(Error::Profile(_)))); +} + #[test] fn spot_inks_past_the_cap_are_listed_not_separated_and_bad_input_is_refused() { let n = MAX_SPOT_INKS + 2; diff --git a/crates/press-print/Cargo.toml b/crates/press-print/Cargo.toml new file mode 100644 index 000000000..92ca65455 --- /dev/null +++ b/crates/press-print/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "craft-press-print" +description = "Press-accurate printing for the Craft apps: a PDF page separated into plates, composited into the printer's RGB profile and printed application-managed" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-cms = { workspace = true } +craft-prepress = { workspace = true } +craft-print = { workspace = true } +thiserror = { workspace = true } diff --git a/crates/press-print/README.md b/crates/press-print/README.md new file mode 100644 index 000000000..acb4f5d7f --- /dev/null +++ b/crates/press-print/README.md @@ -0,0 +1,57 @@ +# craft-press-print + +Press-accurate printing for the Craft apps. A page prints as the press would print it: overprint +decided per plate, spot inks as inks rather than their alternates, knockout and isolated groups, +and the press's colors, converted once into the printer's RGB profile. + +It is an opt-in alternative to craft-print's PDF path, which draws a job with the system's PDF +renderer. That renderer does not simulate overprint and draws spot and DeviceN colors through their +alternates. + +## How a page prints + +1. craft-prepress separates the page in bands (`plates_in_bands`), one 8-bit plate per ink. +2. Each band composites into the printer's profile (`Plates::composite_to`). The process plates + convert from the printing condition they were separated through (`press_profile`: the page's + output intent, else `Options::fallback`), straight from CMYK to the printer. Spot plates + combine over them. +3. The bands join into one RGB image of the page. +4. `craft_print::rgb::print` sends it with `ColorPolicy::ApplicationManaged`, so the driver + applies no second conversion. + +```rust +use craft_cms::Profile; +use craft_press_print::{Settings, print, render}; +use craft_print::rgb; + +let settings = Settings::new(Profile::parse(&printer_icc)?); +// The page as it prints, to preview or to keep. +let page = render(&pdf, 0, 600.0, &settings)?; +// Or straight to a printer, at its resolution. +let job = rgb::Job { + printer: "Office printer", + settings: None, + title: "proof.pdf", + output_file: None, + copies: 1, + color_policy: rgb::ColorPolicy::ApplicationManaged, + primitives: &[], +}; +print(&job, &pdf, 0, &settings, (0.0, 0.0, 612.0, 792.0))?; +``` + +`Settings` holds the separation options, the printer's RGB profile (sRGB when the printer's own +profile is not known), the rendering intent and black point compensation. A gray or CMYK printer +profile is refused: `rgb::print` takes RGB. + +## Limits + +- `rgb::print` takes one image per job, so `print` sends one page per job. +- `print` separates at the printer's resolution, whatever the size of `rect`, within + craft-prepress's limits: the renderer's 8192-pixel side limit across the page (about 960 dpi on + Letter or A4) and `MAX_BANDED_PIXELS` in all. The page image is 3 bytes per pixel and is held + whole. `rgb::print` takes at most 512 MiB, so a page past that separates again at the + resolution that fits. +- Each band renders the page once per ink, so time grows with resolution and ink count. +- Printing needs Windows. Elsewhere `print` returns `rgb::PrintError::Unsupported`, and `render` + still works. diff --git a/crates/press-print/src/lib.rs b/crates/press-print/src/lib.rs new file mode 100644 index 000000000..74c55fb02 --- /dev/null +++ b/crates/press-print/src/lib.rs @@ -0,0 +1,222 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! Press-accurate printing for the Craft apps: a PDF page separated into plates by +//! craft-prepress, composited into the printer's RGB profile and printed through +//! `craft_print::rgb` with its color already managed, so overprint, spot inks and the press's +//! colors reach the driver as the plates have them. See the README. + +use std::ops::ControlFlow; + +use craft_cms::{Builtin, ColorSpace, Intent, Profile}; +use craft_prepress::{Band, Conversion, Options, Output, OutputError, plates_in_bands, press_profile}; +use craft_print::rgb; + +/// How a page becomes the printer's pixels. +#[derive(Clone, Debug)] +pub struct Settings { + /// How the page separates: overprint, and the printing condition when the page has no + /// output intent. + pub separation: Options, + /// The printer's RGB profile: the pixels go to the driver in this space. sRGB when the + /// printer's own is not known. + pub printer: Profile, + /// The rendering intent from the press to the printer. + pub intent: Intent, + /// Black point compensation from the press to the printer. + pub bpc: bool, +} + +impl Settings { + /// Default separation, relative colorimetric with black point compensation, into `printer`. + pub fn new(printer: Profile) -> Self { + Self { separation: Options::default(), printer, intent: Intent::RelativeColorimetric, bpc: true } + } +} + +/// A page as the press prints it, in the printer's RGB. +#[derive(Clone, Debug)] +pub struct PressPage { + pub width: u32, + pub height: u32, + /// The resolution separated at, after craft-prepress's limits. + pub dpi: f32, + /// How process color that wasn't CMYK became CMYK. + pub conversion: Conversion, + /// Rows top to bottom, `width * 3` bytes each. + pub rgb: Vec, +} + +impl PressPage { + /// The page as `craft_print::rgb` takes it. + pub fn image(&self) -> rgb::RgbImage<'_> { + rgb::RgbImage { width: self.width, height: self.height, data: &self.rgb } + } +} + +/// Why a page couldn't be rendered or printed. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + #[error(transparent)] + Separate(#[from] craft_prepress::Error), + #[error(transparent)] + Output(#[from] OutputError), + #[error("the printer profile is not RGB")] + PrinterNotRgb, + #[error("the page image is too large to hold")] + TooLarge, + #[error("the plates could not be converted into the printer profile")] + Composite, + #[error(transparent)] + Print(#[from] rgb::PrintError), +} + +/// Page `page` (from 0) of `pdf` at `dpi` as the press prints it, in `settings.printer`. +/// +/// The page separates in bands (`plates_in_bands`), each band composites into the printer's +/// profile from the printing condition its plates were made for (`press_profile`), and the +/// bands join into one image. Plates made by the device formulas have no profile; they convert +/// from craft-cms's Coated FOGRA39, as craft-prepress's preview does by default. The image is +/// at most `MAX_BANDED_PIXELS` pixels, 3 bytes each. Never panics. +pub fn render(pdf: &[u8], page: usize, dpi: f32, settings: &Settings) -> Result { + match render_within(pdf, page, dpi, settings, usize::MAX)? { + Within::Page(page) => Ok(page), + Within::Over(_) => Err(Error::TooLarge), + } +} + +/// Bytes of the largest image `rgb::print` takes. +const PRINT_BYTES: usize = 512 * 1024 * 1024; + +/// A render that fits in a byte limit, or the bytes the page would take at that resolution. +enum Within { + Page(PressPage), + Over(usize), +} + +/// [`render`], stopping at the first band when the page image would take more than `max` bytes. +fn render_within(pdf: &[u8], page: usize, dpi: f32, settings: &Settings, max: usize) -> Result { + if settings.printer.color_space != ColorSpace::Rgb { + return Err(Error::PrinterNotRgb); + } + let press = press_profile(pdf, page, &settings.separation)?.unwrap_or_else(|| Builtin::CoatedFogra39.profile().clone()); + let output = Output::new(&press, &settings.printer, settings.intent, settings.bpc)?; + let mut joined: Option = None; + let mut over = None; + let mut failed = None; + plates_in_bands(pdf, page, dpi, &settings.separation, |band| { + let len = image_len(band.plates.width, band.page_height); + if joined.is_none() && len.is_some_and(|len| len > max) { + over = len; + return ControlFlow::Break(()); + } + match add_band(&mut joined, band, &output) { + Ok(()) => ControlFlow::Continue(()), + Err(e) => { + failed = Some(e); + ControlFlow::Break(()) + } + } + })?; + if let Some(e) = failed { + return Err(e); + } + if let Some(bytes) = over { + return Ok(Within::Over(bytes)); + } + let page = joined.ok_or(Error::Composite)?; + if Some(page.rgb.len()) != image_len(page.width, page.height) { + return Err(Error::Composite); + } + Ok(Within::Page(page)) +} + +/// [`render`] at `dpi`, or at the resolution that keeps the page image within `max` bytes when +/// `dpi` would exceed it. The page then separates twice: the first time stops at its first band. +fn fitted(pdf: &[u8], page: usize, dpi: f32, settings: &Settings, max: usize) -> Result { + let bytes = match render_within(pdf, page, dpi, settings, max)? { + Within::Page(page) => return Ok(page), + Within::Over(bytes) => bytes, + }; + // Pixels scale with the square of the resolution; the margin covers the floored sides. + let dpi = dpi * ((max as f64 / bytes as f64).sqrt() * 0.99) as f32; + match render_within(pdf, page, dpi, settings, max)? { + Within::Page(page) => Ok(page), + Within::Over(_) => Err(Error::TooLarge), + } +} + +/// Prints page `page` of `pdf` as the press prints it, on `job.printer` with `job.settings`, +/// into `rect` (points from the sheet's top-left, as `rgb::print` takes it), `job.copies` +/// times. +/// +/// The page separates at the printer's resolution, the larger of its two, whatever the size of +/// `rect`, within craft-prepress's limits and the 512 MiB image `rgb::print` takes: past that, +/// at the resolution that fits. The job is application-managed whatever `job.color_policy` says: +/// the pixels are in the printer's profile already, and a second conversion by the driver +/// would undo the press colors. One call is one job; `rgb::print` takes one image per job. +pub fn print(job: &rgb::Job<'_>, pdf: &[u8], page: usize, settings: &Settings, rect: (f64, f64, f64, f64)) -> Result { + let device = rgb::page(job.printer, job.settings)?; + let dpi = device.dpi.0.max(device.dpi.1) as f32; + let press = fitted(pdf, page, dpi, settings, PRINT_BYTES)?; + let job = rgb::Job { color_policy: rgb::ColorPolicy::ApplicationManaged, ..*job }; + Ok(rgb::print(&job, &press.image(), rect)?) +} + +/// Bytes of a `width` × `height` RGB image, `None` on overflow. +fn image_len(width: u32, height: u32) -> Option { + usize::try_from(width).ok()?.checked_mul(usize::try_from(height).ok()?)?.checked_mul(3) +} + +/// Composites `band` into `output` and appends it to the page, allocated on the first band. +fn add_band(joined: &mut Option, band: Band, output: &Output) -> Result<(), Error> { + let plates = band.plates; + if joined.is_none() { + let len = image_len(plates.width, band.page_height).ok_or(Error::TooLarge)?; + let mut rgb = Vec::new(); + rgb.try_reserve_exact(len).map_err(|_| Error::TooLarge)?; + *joined = Some(PressPage { width: plates.width, height: band.page_height, dpi: plates.dpi, conversion: plates.conversion.clone(), rgb }); + } + let page = joined.as_mut().ok_or(Error::Composite)?; + let start = image_len(plates.width, band.top).ok_or(Error::TooLarge)?; + let pixels = plates.composite_to(&[], output); + let fits = plates.width == page.width + && page.rgb.len() == start + && image_len(plates.width, plates.height) == Some(pixels.len()) + && start.checked_add(pixels.len()).is_some_and(|end| Some(end) <= image_len(page.width, page.height)); + if !fits { + return Err(Error::Composite); + } + page.rgb.extend_from_slice(&pixels); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_page_too_large_to_print_separates_at_a_resolution_that_fits() { + let content = "0 0 1 0 k 0 0 40 40 re f"; + let pdf = format!( + "%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R >> endobj +4 0 obj << /Length {} >> stream +{content} +endstream endobj +trailer << /Root 1 0 R >> +%%EOF", + content.len() + ); + let settings = Settings::new(craft_cms::builtin::srgb().clone()); + // 40 pt at 1800 dpi is 1000 × 1000 pixels, 3 MB. + let max = 1_000_000; + assert!(matches!(render_within(pdf.as_bytes(), 0, 1800.0, &settings, max).unwrap(), Within::Over(3_000_000))); + let page = fitted(pdf.as_bytes(), 0, 1800.0, &settings, max).unwrap(); + assert!(page.rgb.len() <= max && page.rgb.len() > max * 9 / 10, "{} bytes", page.rgb.len()); + assert!(page.dpi < 1800.0 * 0.6, "at {} dpi", page.dpi); + assert_eq!(fitted(pdf.as_bytes(), 0, 72.0, &settings, max).unwrap().dpi, 72.0, "a page that fits keeps its resolution"); + } +} diff --git a/crates/press-print/tests/press_print.rs b/crates/press-print/tests/press_print.rs new file mode 100644 index 000000000..d4e1e1046 --- /dev/null +++ b/crates/press-print/tests/press_print.rs @@ -0,0 +1,113 @@ +use craft_cms::{Builtin, Intent, Profile, builtin}; +use craft_prepress::{MAX_PLATE_PIXELS, Options, Output, plates}; +use craft_press_print::{Error, PressPage, Settings, print, render}; +use craft_print::rgb; + +/// A one-page PDF of `w` × `h` pt with `content`, `resources` and `catalog` entries, and +/// `objects` numbered from 5 (each a whole object body). +fn page_pdf(w: u32, h: u32, content: &str, resources: &str, catalog: &str, objects: &[Vec]) -> Vec { + let mut out = b"%PDF-1.7\n".to_vec(); + out.extend_from_slice(format!("1 0 obj << /Type /Catalog /Pages 2 0 R {catalog} >> endobj\n").as_bytes()); + out.extend_from_slice(b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n"); + out.extend_from_slice( + format!("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 {w} {h}] /Contents 4 0 R /Resources << {resources} >> >> endobj\n").as_bytes(), + ); + out.extend_from_slice(format!("4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n", content.len()).as_bytes()); + for (i, body) in objects.iter().enumerate() { + out.extend_from_slice(format!("{} 0 obj ", i + 5).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b" endobj\n"); + } + out.extend_from_slice(b"trailer << /Root 1 0 R >>\n%%EOF"); + out +} + +fn srgb() -> Settings { + Settings::new(builtin::srgb().clone()) +} + +fn px(page: &PressPage, x: u32, y: u32) -> [u8; 3] { + let at = ((y * page.width + x) * 3) as usize; + page.rgb[at..at + 3].try_into().unwrap() +} + +/// Yellow paper, a 50% cyan bar that overprints it (x 10..20) and one that knocks it out +/// (x 25..35), both the full height of the page, so every row is the same. Overprint mode 1 +/// leaves the yellow under the zero components of the overprinting cyan. +const BARS: &str = "0 0 1 0 k 0 0 40 40 re f /OP gs 0.5 0 0 0 k 10 0 10 40 re f /KO gs 25 0 10 40 re f"; +const BARS_RESOURCES: &str = "/ExtGState << /OP << /op true /OP true /OPM 1 >> /KO << /op false /OP false >> >>"; + +/// Yellow paper with cyan over its top half: in device rows, cyan down to the middle, then +/// yellow. +const HALVES: &str = "0 0 1 0 k 0 0 40 40 re f 1 0 0 0 k 0 20 40 20 re f"; + +#[test] +fn bands_join_without_a_seam_into_one_page_image() { + let pdf = page_pdf(40, 40, HALVES, "", "", &[]); + let page = render(&pdf, 0, 3700.0, &srgb()).unwrap(); + assert_eq!(page.rgb.len(), (page.width * page.height * 3) as usize); + assert!((page.width * page.height) as f32 > MAX_PLATE_PIXELS, "more than one band: {} × {}", page.width, page.height); + let rows: Vec<&[u8]> = page.rgb.chunks_exact((page.width * 3) as usize).collect(); + let (top, bottom) = (rows[0], rows[rows.len() - 1]); + assert_ne!(top, bottom); + // Every row is the top's or the bottom's, except at most one at the edge, which is in the + // middle of the page. + let cyan = rows.iter().take_while(|r| **r == top).count(); + let yellow = rows.iter().rev().take_while(|r| **r == bottom).count(); + assert!(cyan + yellow + 1 >= rows.len(), "{cyan} cyan and {yellow} yellow rows of {}", rows.len()); + assert!(cyan.abs_diff(rows.len() / 2) <= 1, "the edge at row {cyan} of {}", rows.len()); +} + +#[test] +fn overprint_reaches_the_printer_pixels() { + let pdf = page_pdf(40, 40, BARS, BARS_RESOURCES, "", &[]); + let page = render(&pdf, 0, 72.0, &srgb()).unwrap(); + let wide = |p: [u8; 3]| p.map(i32::from); + let [r, g, b] = wide(px(&page, 15, 20)); + assert!(g > r && g > b + 60, "cyan over yellow prints green: {:?}", [r, g, b]); + let [r, g, b] = wide(px(&page, 30, 20)); + assert!(b > g - 40 && b > r + 60, "knocked-out cyan prints cyan: {:?}", [r, g, b]); + + let off = Settings { separation: Options { overprint: false, ..Options::default() }, ..srgb() }; + let knocked = render(&pdf, 0, 72.0, &off).unwrap(); + assert_eq!(px(&knocked, 15, 20), px(&knocked, 30, 20), "with overprint off both bars knock out"); +} + +#[test] +fn the_plates_convert_from_the_output_intents_profile() { + let intent = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /DestOutputProfile 5 0 R >>]"; + let icc = builtin::COATED_CMYK_ICC; + let mut profile = format!("<< /N 4 /Length {} >> stream\n", icc.len()).into_bytes(); + profile.extend_from_slice(icc); + profile.extend_from_slice(b"\nendstream"); + let pdf = page_pdf(40, 40, "1 0 0 rg 0 0 20 40 re f 0.2 0.6 0.9 0.1 k 20 0 20 40 re f", "", intent, &[profile]); + + let page = render(&pdf, 0, 72.0, &srgb()).unwrap(); + let plates = plates(&pdf, 0, 72.0, &Options::default()).unwrap(); + let synthetic = Profile::parse(icc).unwrap(); + let through = |press: &Profile| plates.composite_to(&[], &Output::new(press, builtin::srgb(), Intent::RelativeColorimetric, true).unwrap()); + assert_ne!(through(&synthetic), through(Builtin::CoatedFogra39.profile()), "the two presses differ here"); + assert_eq!(page.rgb, through(&synthetic), "the press is the output intent's"); +} + +#[test] +fn bad_input_is_refused_before_anything_prints() { + let pdf = page_pdf(40, 40, BARS, BARS_RESOURCES, "", &[]); + let cmyk = Settings::new(Builtin::CoatedFogra39.profile().clone()); + assert!(matches!(render(&pdf, 0, 72.0, &cmyk), Err(Error::PrinterNotRgb))); + assert!(matches!(render(&pdf, 0, f32::NAN, &srgb()), Err(Error::Separate(_)))); + assert!(matches!(render(&pdf, 3, 72.0, &srgb()), Err(Error::Separate(_)))); + assert!(matches!(render(b"not a pdf", 0, 72.0, &srgb()), Err(Error::Separate(_)))); + + // No such printer: refused while asking for its page, before a job starts. + let job = rgb::Job { + printer: "Craft press print: no such printer", + settings: None, + title: "press", + output_file: None, + copies: 1, + color_policy: rgb::ColorPolicy::DriverManaged, + primitives: &[], + }; + assert!(matches!(print(&job, &pdf, 0, &srgb(), (0.0, 0.0, 40.0, 40.0)), Err(Error::Print(_)))); +}