diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index dc956e6e6..e77d422ea 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -32,6 +32,13 @@ re-sync brings these PdfCraft changes: PdfCraft's vendored `vello_common` patch (clip-intersection performance) is not part of this reader snapshot. +Changes ported from PdfCraft pull requests that were open when they were ported, under the +same MIT OR Apache-2.0 licence. Code comments keep the pull request's patch numbers. + +| PdfCraft PR | Author | Source commit | Files | Change | +|---|---|---|---|---| +| [#2770](https://github.com/storytold/pdfcraft/pull/2770) | Guillem Hermida (guillehr2) | [6fcf2a4](https://github.com/guillehr2/pdfcraft/commit/6fcf2a4aca29e943e28cb69017ff8f87d00656c6) | hayro-interpret `color.rs`, `interpret/mod.rs`, `interpret/path.rs`, `interpret/state.rs`, `pattern.rs`, `shading.rs`, `soft_mask.rs`, `x_object.rs` | Patches 35 and 36, plate mode: `InterpreterSettings::plate` draws one ink's separation as a gray film (`color::Plate`, `ColorSpace::ink_use`/`ink_tint`); the graphics state reads `OP`, `op` and `OPM` and an overprinting paint that doesn't specify the plate's ink leaves the plate as it is (ISO 32000-2 §8.6.7); `InterpreterSettings::ink_sink` reports spot inks; `color::CmykSimulation` converts process colour to an output intent's CMYK. Only the vendored interpreter part is ported; PdfCraft's `separations.rs` and Output Preview UI are not | + The shared snapshot adds immutable per-document ordinary decode limits, threaded through initial xrefs, object streams, fallback and repair. Existing constructors retain their previous default. Known-size image budgets and streaming content budgets remain distinct. diff --git a/vendor/hayro-interpret/SOURCE.json b/vendor/hayro-interpret/SOURCE.json index 2507cd074..3733e2998 100644 --- a/vendor/hayro-interpret/SOURCE.json +++ b/vendor/hayro-interpret/SOURCE.json @@ -182,7 +182,7 @@ "path": "src/color.rs", "source_sha256": "799ce29bb5e59c8fc94db202873e48c2047dd35962e6f26efd215156c47158c1", "source_git_blob": "56bb04f24c04ba33ab6bf99c02a24735670959ad", - "sha256": "149d5a6b1b9e6212d2b3e9d63e1803a6041eb1798bfb9231ef89fc6bfcb7b968" + "sha256": "784753b972d9a24167c8085f4e387ac7cc85007f4ab4ca83ab0c0aafe067c073" }, { "path": "src/context.rs", @@ -362,19 +362,19 @@ "path": "src/interpret/mod.rs", "source_sha256": "2b002323055bc19aa497e92c81ad8e06dc60ee03686cad89366df4ac7c7a06b2", "source_git_blob": "fe08fc284ba7c914d1414b68a5a346674a6f910f", - "sha256": "1ed42a7777a6265f14efaaa5899dc96b93dc53aff85afacfcac60065e6e490d5" + "sha256": "2f50fcd65da262f4ef66c9611adcdb993015c57181bc2a51a551611152a59f5f" }, { "path": "src/interpret/path.rs", "source_sha256": "a5defbc4b883b262662f7e7474a00ec1f97dbef8c03b8669859f624f5d02344b", "source_git_blob": "838ea099f11d918d6e333e32503368be864689f8", - "sha256": "a5defbc4b883b262662f7e7474a00ec1f97dbef8c03b8669859f624f5d02344b" + "sha256": "eb42777dc3063794c21aa914b61e40a8547820de3e4d7b47924d169890f4fbb4" }, { "path": "src/interpret/state.rs", "source_sha256": "dce778291b13f6df83c8c13aee22f60edd033ec9f7d89309ef148d46d3ba9814", "source_git_blob": "95b773fb5cc434ab8db362d00e4e5180a8b740c9", - "sha256": "dce778291b13f6df83c8c13aee22f60edd033ec9f7d89309ef148d46d3ba9814" + "sha256": "393371ec56dccdc3c2fc20d61da39d87e3e8393bf69ddbd249417490f8f9923b" }, { "path": "src/interpret/text.rs", @@ -404,19 +404,19 @@ "path": "src/pattern.rs", "source_sha256": "17b49a465275c20e6645dea9443f2cb3a64c594925fd860e74b80b44d5344e37", "source_git_blob": "9295f51709f8915951d7b9afca9411651d65a1f8", - "sha256": "24ac7a1cfd9a55b7d40d572120f52743bd390fab0007603aec64034ae7d2fd23" + "sha256": "ae362a5074b40482f2c5e16ea66a0398b27ec866a7b4adb8f45fe7221c960ae1" }, { "path": "src/shading.rs", "source_sha256": "5d541a2d52f69c88e87a40580bf28afa4b8a6a2d62a3385009087264384ead32", "source_git_blob": "2e619e47f2800d7fc7cbdae77c66c58f012c84c2", - "sha256": "5d541a2d52f69c88e87a40580bf28afa4b8a6a2d62a3385009087264384ead32" + "sha256": "6e80c039ab7ca38ede2b1778709f1b4258d8cf219d044d3298f4a5f6dd2c8f9a" }, { "path": "src/soft_mask.rs", "source_sha256": "6cd9c59c0cff580879c1f06ff40f3537c04b719bdb3ea59008fa1ab7559db5dd", "source_git_blob": "4d97d565b53c820fa927fbba8c3dda6acead7f34", - "sha256": "780ffbf73567a7ae33f2fb673676840e0a29cb6b59f1d8b625034f42c4d17a22" + "sha256": "0e3871896575006f194fb46242fcaa6e1026f459c6144c38da438f82ace95e50" }, { "path": "src/types.rs", @@ -434,7 +434,7 @@ "path": "src/x_object.rs", "source_sha256": "e1c51e96a335c32c122011b2d05c5020c36a33c2c73342ba173c28a3e2fe0219", "source_git_blob": "21b134ce8cd9604399cd0776febf923d69c02673", - "sha256": "48d296abf28696c4a3e01e9d12169c754062b0840c9f2b93051435247aba9144" + "sha256": "20e9d2f4fcafd20e11d6255f2800c8732ea84e74e5061287c8d5fbcfb4ffe013" } ], "compatibility_reference": { diff --git a/vendor/hayro-interpret/src/color.rs b/vendor/hayro-interpret/src/color.rs index af3597414..55904609d 100644 --- a/vendor/hayro-interpret/src/color.rs +++ b/vendor/hayro-interpret/src/color.rs @@ -2,6 +2,7 @@ use crate::cache::{Cache, CacheKey}; use crate::function::Function; +use crate::util::hash128; use hayro_syntax::object; use hayro_syntax::object::Array; use hayro_syntax::object::Dict; @@ -10,8 +11,8 @@ use hayro_syntax::object::Object; use hayro_syntax::object::Stream; use hayro_syntax::object::dict::keys::*; use moxcms::{ - ColorProfile, DataColorSpace, Layout, Transform8BitExecutor, TransformF32Executor, - TransformOptions, + ColorProfile, DataColorSpace, Layout, ProfileText, RenderingIntent, Transform8BitExecutor, + TransformF32Executor, TransformOptions, }; use smallvec::{SmallVec, ToSmallVec, smallvec}; use std::borrow::Cow; @@ -117,6 +118,8 @@ pub(crate) enum ColorSpaceType { Lab(Lab), Separation(Separation), DeviceN(DeviceN), + /// PdfCraft patch (35): `inner` drawn as the plate of one ink (see [`Plate`]). + Plate(PlateSpace), } impl ColorSpaceType { @@ -270,7 +273,12 @@ impl ColorSpace { /// Return `true` if the current color space is an indexed color space. pub(crate) fn is_indexed(&self) -> bool { - matches!(self.0.as_ref(), ColorSpaceType::Indexed(_)) + match self.0.as_ref() { + ColorSpaceType::Indexed(_) => true, + // PdfCraft patch (35): a plate decodes its samples as its space does. + ColorSpaceType::Plate(p) => p.inner.is_indexed(), + _ => false, + } } /// Get the default decode array for the color space. @@ -290,6 +298,7 @@ impl ColorSpace { ColorSpaceType::Indexed(_) => smallvec![(0.0, 2.0_f32.powf(n) - 1.0)], ColorSpaceType::Separation(_) => smallvec![(0.0, 1.0)], ColorSpaceType::DeviceN(d) => smallvec![(0.0, 1.0); d.num_components as usize], + ColorSpaceType::Plate(p) => p.inner.default_decode_arr(n), // Not a valid image color space. ColorSpaceType::Pattern(_) => smallvec![(0.0, 1.0)], } @@ -321,6 +330,7 @@ impl ColorSpace { ColorSpaceType::Separation(_) => smallvec![1.0], ColorSpaceType::Pattern(c) => c.initial_color(), ColorSpaceType::DeviceN(d) => smallvec![1.0; d.num_components as usize], + ColorSpaceType::Plate(p) => p.inner.initial_color(), } } @@ -342,6 +352,7 @@ impl ColorSpace { ColorSpaceType::Separation(_) => 1, ColorSpaceType::Pattern(p) => p.num_components(), ColorSpaceType::DeviceN(d) => d.num_components, + ColorSpaceType::Plate(p) => p.inner.num_components(), } } @@ -392,6 +403,7 @@ impl ToRgb for ColorSpace { ColorSpaceType::Lab(i) => i.convert_f32(input, output, manual_scale), ColorSpaceType::Separation(i) => i.convert_f32(input, output, manual_scale), ColorSpaceType::DeviceN(i) => i.convert_f32(input, output, manual_scale), + ColorSpaceType::Plate(i) => i.convert_f32(input, output, manual_scale), } } @@ -408,6 +420,7 @@ impl ToRgb for ColorSpace { ColorSpaceType::Lab(i) => i.supports_u8(), ColorSpaceType::Separation(i) => i.supports_u8(), ColorSpaceType::DeviceN(i) => i.supports_u8(), + ColorSpaceType::Plate(i) => i.supports_u8(), } } @@ -436,6 +449,7 @@ impl ToRgb for ColorSpace { ColorSpaceType::Lab(i) => i.convert_u8(input, output), ColorSpaceType::Separation(i) => i.convert_u8(input, output), ColorSpaceType::DeviceN(i) => i.convert_u8(input, output), + ColorSpaceType::Plate(i) => i.convert_u8(input, output), } } @@ -443,6 +457,7 @@ impl ToRgb for ColorSpace { match self.0.as_ref() { ColorSpaceType::Separation(s) => s.is_none(), ColorSpaceType::DeviceN(d) => d.is_none(), + ColorSpaceType::Plate(p) => p.inner.is_none(), _ => false, } } @@ -701,6 +716,11 @@ impl Lab { /// be expressed in LMS before taking their ratios. CalRGB's separate /// flat-white/black-point pipeline retains its existing normalization. fn adapt_to_d65(white_point: &[f32; 3], xyz: &[f32; 3]) -> [f32; 3] { + Self::adapt(white_point, &CalRgb::D65_WHITEPOINT, xyz) + } + + /// `xyz`, seen under `white_point`, Bradford-adapted to `destination`. + fn adapt(white_point: &[f32; 3], destination: &[f32; 3], xyz: &[f32; 3]) -> [f32; 3] { let source_lms = CalRgb::matrix_product(&CalRgb::BRADFORD_SCALE_MATRIX, white_point); // A malformed but positive XYZ white can still yield a zero or // overflowing cone response. Leave it unadapted rather than divide by @@ -708,7 +728,7 @@ impl Lab { if source_lms.iter().any(|v| !v.is_finite() || v.abs() <= f32::EPSILON) { return *xyz; } - let destination_lms = CalRgb::matrix_product(&CalRgb::BRADFORD_SCALE_MATRIX, &CalRgb::D65_WHITEPOINT); + let destination_lms = CalRgb::matrix_product(&CalRgb::BRADFORD_SCALE_MATRIX, destination); let lms = CalRgb::matrix_product(&CalRgb::BRADFORD_SCALE_MATRIX, xyz); let adapted = [ lms[0] * destination_lms[0] / source_lms[0], @@ -728,43 +748,60 @@ impl Lab { 3.0 * DELTA * DELTA * (t - 4.0 / 29.0) } } + + /// PdfCraft patch: the L*, a* and b* of the colour `input`, clamped to L* 0..100 and the + /// a*/b* /Range. `manual_scale` means the components arrive normalised to [0, 1] (an + /// `/Indexed` palette over Lab looks its bytes up as `byte / 255`): they map linearly onto + /// L* 0..100 and the /Range (ISO 32000-2 §8.6.6.3). + fn components(&self, input: &[f32], manual_scale: bool) -> [f32; 3] { + let [min_a, max_a, min_b, max_b] = self.range; + let get = |k: usize| input.get(k).copied().unwrap_or(0.0); + let (l, a, b) = if manual_scale { + ( + clamp_component(get(0), 0.0, 1.0) * 100.0, + min_a + clamp_component(get(1), 0.0, 1.0) * (max_a - min_a), + min_b + clamp_component(get(2), 0.0, 1.0) * (max_b - min_b), + ) + } else { + (get(0), get(1), get(2)) + }; + [ + clamp_component(l, 0.0, 100.0), + clamp_component(a, min_a, max_a), + clamp_component(b, min_b, max_b), + ] + } + + /// The XYZ of L*a*b*, in the coordinates of the space's white point. + fn xyz(&self, [l, a, b]: [f32; 3]) -> [f32; 3] { + let [xw, yw, zw] = self.usable_white_point(); + let fy = (l + 16.0) / 116.0; + let fx = fy + a / 500.0; + let fz = fy - b / 200.0; + [ + xw * Self::inverse_lab_f(fx), + yw * Self::inverse_lab_f(fy), + zw * Self::inverse_lab_f(fz), + ] + } + + /// PdfCraft patch (36): the colour `input` in the separation hub (see [`Hub`]), relative + /// colorimetric: the space's white point becomes the PCS white (Bradford-adapted). + fn to_hub(&self, input: &[f32], manual_scale: bool) -> [f32; 3] { + let xyz = self.xyz(self.components(input, manual_scale)); + HUB.from_xyz(&Self::adapt(&self.usable_white_point(), &HUB.white, &xyz)) + } } impl ToRgb for Lab { fn convert_f32(&self, input: &[f32], output: &mut [u8], manual_scale: bool) -> Option<()> { - let [min_a, max_a, min_b, max_b] = self.range; let white_point = self.usable_white_point(); - let [xw, yw, zw] = white_point; for (input, output) in input.chunks_exact(3).zip(output.chunks_exact_mut(3)) { - // PdfCraft patch: `manual_scale` means the components arrive - // normalised to [0, 1] (an `/Indexed` palette over Lab looks its - // bytes up as `byte / 255`). Map them linearly onto L* 0..100 and - // the a*/b* /Range (ISO 32000-2 §8.6.6.3) before converting. - let (l, a, b) = if manual_scale { - ( - clamp_component(input[0], 0.0, 1.0) * 100.0, - min_a + clamp_component(input[1], 0.0, 1.0) * (max_a - min_a), - min_b + clamp_component(input[2], 0.0, 1.0) * (max_b - min_b), - ) - } else { - (input[0], input[1], input[2]) - }; - let l = clamp_component(l, 0.0, 100.0); - let a = clamp_component(a, min_a, max_a); - let b = clamp_component(b, min_b, max_b); - // L*a*b* is relative to the space's own /WhitePoint. Map it to XYZ // in that white's coordinates, Bradford-adapt to D65 and convert to // sRGB (ISO 32000-2 §8.6.5.4). - let fy = (l + 16.0) / 116.0; - let fx = fy + a / 500.0; - let fz = fy - b / 200.0; - let xyz = [ - xw * Self::inverse_lab_f(fx), - yw * Self::inverse_lab_f(fy), - zw * Self::inverse_lab_f(fz), - ]; + let xyz = self.xyz(self.components(input, manual_scale)); let xyz_d65 = Self::adapt_to_d65(&white_point, &xyz); let srgb = CalRgb::matrix_product(&CalRgb::SRGB_D65_XYZ_TO_RGB_MATRIX, &xyz_d65); @@ -852,6 +889,8 @@ pub(crate) struct Separation { alternate_space: ColorSpace, tint_transform: Function, is_none_separation: bool, + /// PdfCraft patch (35): the colorant the space paints, for separations. + colorant: Colorant, } impl Separation { @@ -865,11 +904,13 @@ impl Separation { // Either I did something wrong, or no other viewers properly handles // `All`, so let's just ignore it as well. let is_none_separation = name.as_str() == "None"; + let colorant = Colorant::from_name(name.deref()); Some(Self { alternate_space, tint_transform, is_none_separation, + colorant, }) } } @@ -899,6 +940,8 @@ pub(crate) struct DeviceN { num_components: u8, tint_transform: Function, is_none: bool, + /// PdfCraft patch (35): the colorant of each component, for separations. + colorants: Vec, } impl DeviceN { @@ -920,11 +963,22 @@ impl DeviceN { return None; } + // `All` names every colorant only in a Separation (ISO 32000-2 §8.6.6.5), so a DeviceN + // component named `All` paints nothing in particular. + let colorants = names + .iter() + .map(|n| match Colorant::from_name(n.deref()) { + Colorant::All => Colorant::None, + c => c, + }) + .collect(); + Some(Self { alternate_space, num_components, tint_transform, is_none: all_none, + colorants, }) } } @@ -957,6 +1011,12 @@ struct ICCColorRepr { is_lab: bool, transform_u8: Arc, transform_f32: OnceLock>, + /// PdfCraft patch (36): a digest of the profile's bytes, to tell a colour in a + /// [`CmykSimulation`]'s own profile from one in another. + digest: u128, + /// PdfCraft patch (36): the transform into the separation hub (see [`Hub`]), made on first + /// use; `None` when the profile doesn't convert to it. + to_hub: OnceLock>>, } #[derive(Clone)] @@ -980,7 +1040,13 @@ impl ICCProfile { .unwrap_or(false); let is_lab = src_profile.color_space == DataColorSpace::Lab; - Self::new_from_src_profile(src_profile, is_srgb, is_lab, number_components) + Self::new_from_src_profile( + src_profile, + is_srgb, + is_lab, + number_components, + hash128(profile), + ) } fn new_from_src_profile( @@ -988,6 +1054,7 @@ impl ICCProfile { is_srgb: bool, is_lab: bool, number_components: usize, + digest: u128, ) -> Option { let src_layout = match number_components { 1 => Layout::Gray, @@ -1019,9 +1086,46 @@ impl ICCProfile { is_lab, transform_u8, transform_f32: OnceLock::new(), + digest, + to_hub: OnceLock::new(), }))) } + /// PdfCraft patch (36): `input` (whole colours of this profile's components) in the + /// separation hub, three values per colour in `rgb`. L*a*b* components are scaled to the + /// profile's encoding unless `manual_scale` says they already are (an Indexed palette's). + fn to_hub(&self, input: &[f32], manual_scale: bool, rgb: &mut [f32]) -> Option<()> { + let transform = self + .0 + .to_hub + .get_or_init(|| { + transform_f32( + &self.0.src_profile, + self.0.src_layout, + &HUB.profile, + Layout::Rgb, + ) + .map(|(transform, _)| transform) + }) + .as_ref()?; + let n = self.0.number_components; + let samples = input.len() / n.max(1); + if samples > SIMULATION_CHUNK || rgb.len() != samples.checked_mul(3)? { + return None; + } + // Values outside the encoding (or NaN) never reach the tables. + let mut encoded = [0.0_f32; SIMULATION_CHUNK * 4]; + let encoded = encoded.get_mut(..samples.checked_mul(n)?)?; + for (e, (k, v)) in encoded.iter_mut().zip(input.iter().enumerate()) { + *e = match (self.is_lab() && !manual_scale, k % 3) { + (true, 0) => unit(*v / 100.0), + (true, _) => unit((*v + 128.0) / 255.0), + (false, _) => unit(*v), + }; + } + transform.transform(encoded, rgb).ok() + } + fn is_srgb(&self) -> bool { self.0.is_srgb } @@ -1144,6 +1248,853 @@ impl Color { opacity: c[3], } } + + /// PdfCraft patch (35): the gray film of `tint` on a plate (see [`Plate`]). + pub(crate) fn film(tint: f32, opacity: f32) -> Self { + Self::new( + ColorSpace::device_gray(), + smallvec![1.0 - unit(tint)], + opacity, + ) + } + + /// PdfCraft patch (35): this colour as drawn on `plate`. `overprint` is the graphics + /// state's overprint parameter for this paint (`OP` for strokes, `op` otherwise) and + /// `overprint_mode` its `OPM` (ISO 32000-2 §8.6.7). A paint that leaves the plate as it is + /// becomes fully transparent. + pub(crate) fn for_plate(&self, plate: &Plate, overprint: bool, overprint_mode: u8) -> Self { + let overprint = plate.overprint && overprint; + let untouched = Self::film(0.0, 0.0); + match self.color_space.ink_use(&plate.ink) { + InkUse::Nothing => untouched, + InkUse::Unspecified if overprint => untouched, + InkUse::Unspecified => Self::film(0.0, self.opacity), + InkUse::Paints => { + let tint = self.color_space.ink_tint( + &self.components, + &plate.ink, + plate.simulation.as_ref(), + false, + ); + // Nonzero overprint mode: a DeviceCMYK component of 0 leaves its plate as it + // is. It applies to colours set in DeviceCMYK itself, not to images, shadings + // or colours converted from another space. + if overprint + && overprint_mode == 1 + && self.color_space.is_device_cmyk() + && tint <= 0.0 + { + untouched + } else { + Self::film(tint, self.opacity) + } + } + } + } +} + +/// PdfCraft patch (35): a printing ink, the unit of a separation: one of the four process +/// colorants or a spot colorant named by a `Separation` or `DeviceN` colour space (ISO 32000-2 +/// §8.6.6.4). +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Ink { + /// Process cyan. + Cyan, + /// Process magenta. + Magenta, + /// Process yellow. + Yellow, + /// Process black. + Black, + /// A spot colorant, by its name in the colour space. + Spot(Arc), +} + +impl Ink { + /// The four process inks, in plate order. + pub const PROCESS: [Ink; 4] = [Ink::Cyan, Ink::Magenta, Ink::Yellow, Ink::Black]; + + /// The ink's colorant name, as a `Separation` colour space spells it. + pub fn name(&self) -> &str { + match self { + Self::Cyan => "Cyan", + Self::Magenta => "Magenta", + Self::Yellow => "Yellow", + Self::Black => "Black", + Self::Spot(name) => name, + } + } + + /// The ink's position in a CMYK colour, for a process ink. + pub(crate) fn process_index(&self) -> Option { + match self { + Self::Cyan => Some(0), + Self::Magenta => Some(1), + Self::Yellow => Some(2), + Self::Black => Some(3), + Self::Spot(_) => None, + } + } +} + +/// PdfCraft patch (35): what a `Separation` or `DeviceN` colorant name paints (ISO 32000-2 +/// §8.6.6.4): an ink (the process names are the process inks), every ink (`All`), or nothing +/// (`None`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Colorant { + Ink(Ink), + All, + None, +} + +impl Colorant { + fn from_name(name: &[u8]) -> Self { + match name { + b"Cyan" => Self::Ink(Ink::Cyan), + b"Magenta" => Self::Ink(Ink::Magenta), + b"Yellow" => Self::Ink(Ink::Yellow), + b"Black" => Self::Ink(Ink::Black), + b"All" => Self::All, + b"None" => Self::None, + other => Self::Ink(Ink::Spot(Arc::from( + String::from_utf8_lossy(other).as_ref(), + ))), + } + } +} + +/// PdfCraft patch (35): draw one ink's separation instead of the composite page. Every paint +/// draws the ink's tint as a gray film: white where the plate carries no ink, black where it +/// carries 100%. Set through [`InterpreterSettings::plate`](crate::InterpreterSettings::plate). +#[derive(Clone, Debug, PartialEq)] +pub struct Plate { + /// The ink whose separation is drawn. + pub ink: Ink, + /// Honour the overprint parameters `OP`, `op` and `OPM` (ISO 32000-2 §8.6.7) as a + /// separating device does: a paint whose colour space doesn't specify this ink leaves the + /// plate as it is. When `false`, every paint knocks out what is under it, as on a + /// composite device. + pub overprint: bool, + /// PdfCraft patch (36): the printing condition process colour converts to, from the + /// document's output intent. `None` converts by the ISO 32000-2 §10.4.2 device formulas. + pub simulation: Option, +} + +/// PdfCraft patch (35): told about each spot ink a paint uses, with the ink's appearance: the +/// sRGB colour of that ink alone at a tint in `0.0..=1.0`, through the colour space's +/// alternate space and tint transform. +pub type InkSinkFn = Arc [u8; 3]) + Send + Sync>; + +/// PdfCraft patch (35): how a colour space paints one ink's plate. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum InkUse { + /// The space specifies the ink: its colours set the plate's tint. + Paints, + /// The space doesn't specify the ink. Overprinting leaves the plate alone; otherwise the + /// paint knocks it out (tint 0). + Unspecified, + /// The space paints nothing at all (the `None` colorant). + Nothing, +} + +/// PdfCraft patch (35): DeviceCMYK to sRGB as pages are drawn (the bundled CGATS-compatible +/// profile), to compose separations back into a preview. `cmyk` holds whole pixels of four +/// bytes and `rgb` the same number of three-byte pixels; `None` when the lengths disagree or +/// the transform fails. +pub fn cmyk_to_srgb8(cmyk: &[u8], rgb: &mut [u8]) -> Option<()> { + if cmyk.len() % 4 != 0 || (cmyk.len() / 4).checked_mul(3)? != rgb.len() { + return None; + } + CMYK_TRANSFORM.convert_u8(cmyk, rgb) +} + +/// A component as a tint: clamped to `0.0..=1.0`, NaN read as no ink. +fn unit(value: f32) -> f32 { + clamp_component(value, 0.0, 1.0) +} + +/// The DeviceCMYK colour of a DeviceRGB one by ISO 32000-2 §10.4.2.4, with black generation +/// and undercolour removal both the identity (`BG(k) = UCR(k) = k`). Those two functions are +/// device dependent; the identity is the simplest choice the formulas allow. +fn rgb_to_cmyk([r, g, b]: [f32; 3]) -> [f32; 4] { + let (c, m, y) = (1.0 - unit(r), 1.0 - unit(g), 1.0 - unit(b)); + let k = c.min(m).min(y); + [unit(c - k), unit(m - k), unit(y - k), unit(k)] +} + +/// PdfCraft patch (36): colours converted per step through a [`CmykSimulation`], so that the +/// buffers stay on the stack whatever an image's size. +const SIMULATION_CHUNK: usize = 256; + +/// PdfCraft patch (36): the printing condition separations simulate, from an output intent's +/// destination profile (ISO 32000-2 §14.11.5): a CMYK ICC profile with PCS-to-device (BToA) +/// tables. Set through [`Plate::simulation`]. Process colour in other spaces converts to the +/// profile's CMYK through those tables, instead of by the device formulas of §10.4.2: +/// +/// - DeviceRGB as sRGB, as pages are drawn; CalRGB and CalGray through their sRGB colours; +/// - Lab and ICCBased colours (RGB, gray, L\*a\*b\*, and CMYK in another profile) through +/// the separation hub, a D50 RGB wide enough for every surface colour (see [`Hub`]); +/// - DeviceCMYK, ICCBased CMYK in this same profile, and DeviceGray stay as they are: gray is a +/// device colour, which a CMYK device prints with black ink alone (§10.4.2.2). +/// +/// Conversions are relative colorimetric, the initial rendering intent (§8.6.5.8; the +/// graphics state's `ri` isn't read). A profile without colorimetric tables is used through +/// its perceptual ones (tag 0, which every LUT-based ICC.1 profile has). Black point +/// compensation isn't applied. +#[derive(Clone)] +pub struct CmykSimulation(Arc); + +struct SimulationRepr { + description: Option, + perceptual: bool, + digest: u128, + from_srgb: Arc, + from_hub: Arc, + to_srgb: Option>, +} + +impl Debug for CmykSimulation { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CmykSimulation") + .field("description", &self.0.description) + .field("perceptual", &self.0.perceptual) + .finish_non_exhaustive() + } +} + +/// Two simulations of the same profile are the same. +impl PartialEq for CmykSimulation { + fn eq(&self, other: &Self) -> bool { + self.0.digest == other.0.digest + } +} + +/// PdfCraft patch (36): why an ICC profile can't be simulated. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NoSimulation { + /// The profile doesn't parse. + Unreadable, + /// Its data colour space isn't CMYK. + NotCmyk, + /// It has no PCS-to-device (BToA) tables, or they don't convert. + NoPcsToDevice, +} + +impl CmykSimulation { + /// The longest description kept, in characters. + const MAX_DESCRIPTION: usize = 160; + + /// The printing condition of the ICC profile `profile`, if it is a CMYK profile whose + /// PCS-to-device tables convert. + pub fn new(profile: &[u8]) -> Result { + let parsed = ColorProfile::new_from_slice(profile).map_err(|_| NoSimulation::Unreadable)?; + if parsed.color_space != DataColorSpace::Cmyk { + return Err(NoSimulation::NotCmyk); + } + if parsed.lut_b_to_a_colorimetric.is_none() && parsed.lut_b_to_a_perceptual.is_none() { + return Err(NoSimulation::NoPcsToDevice); + } + let (from_hub, perceptual) = + transform_f32(&HUB.profile, Layout::Rgb, &parsed, Layout::Rgba) + .ok_or(NoSimulation::NoPcsToDevice)?; + let (from_srgb, _) = transform_f32(&SRGB, Layout::Rgb, &parsed, Layout::Rgba) + .ok_or(NoSimulation::NoPcsToDevice)?; + let to_srgb = transform_u8(&parsed, Layout::Rgba, &SRGB, Layout::Rgb); + Ok(Self(Arc::new(SimulationRepr { + description: profile_description(&parsed, Self::MAX_DESCRIPTION), + perceptual, + digest: hash128(profile), + from_srgb, + from_hub, + to_srgb, + }))) + } + + /// The profile's description (its `desc` tag) without control characters; `None` when it + /// has none. + pub fn description(&self) -> Option<&str> { + self.0.description.as_deref() + } + + /// Whether conversions use the profile's perceptual tables, because it has no + /// colorimetric ones. + pub fn perceptual(&self) -> bool { + self.0.perceptual + } + + /// A digest of the profile's bytes, for cache keys. + pub(crate) fn digest(&self) -> u128 { + self.0.digest + } + + /// CMYK in this printing condition to sRGB, relative colorimetric, to show what it prints. + /// As [`cmyk_to_srgb8`]; also `None` when the profile has no device-to-PCS tables. + pub fn cmyk_to_srgb8(&self, cmyk: &[u8], rgb: &mut [u8]) -> Option<()> { + if cmyk.len() % 4 != 0 || (cmyk.len() / 4).checked_mul(3)? != rgb.len() { + return None; + } + self.0.to_srgb.as_ref()?.transform(cmyk, rgb).ok() + } +} + +/// PdfCraft patch (36): a profile's description, without control characters and at most `max` +/// characters long; `None` when it has none. +fn profile_description(profile: &ColorProfile, max: usize) -> Option { + let text = match profile.description.as_ref()? { + ProfileText::PlainString(s) => s.as_str(), + ProfileText::Localizable(list) => { + &list + .iter() + .find(|s| s.language == "en") + .or(list.first())? + .value + } + ProfileText::Description(d) if d.ascii_string.trim().is_empty() => &d.unicode_string, + ProfileText::Description(d) => &d.ascii_string, + }; + let clean: String = text + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .take(max) + .collect(); + let clean = clean.trim(); + (!clean.is_empty()).then(|| clean.to_string()) +} + +/// PdfCraft patch (36): a transform from `source` to `destination`, relative colorimetric, or +/// through the perceptual tables (`true`) where a profile lacks colorimetric ones. +fn transform_f32( + source: &ColorProfile, + source_layout: Layout, + destination: &ColorProfile, + destination_layout: Layout, +) -> Option<(Arc, bool)> { + [ + RenderingIntent::RelativeColorimetric, + RenderingIntent::Perceptual, + ] + .into_iter() + .find_map(|rendering_intent| { + let options = TransformOptions { + rendering_intent, + ..TransformOptions::default() + }; + source + .create_transform_f32(source_layout, destination, destination_layout, options) + .ok() + .map(|t| (t, rendering_intent == RenderingIntent::Perceptual)) + }) +} + +/// PdfCraft patch (36): as [`transform_f32`], for bytes. +fn transform_u8( + source: &ColorProfile, + source_layout: Layout, + destination: &ColorProfile, + destination_layout: Layout, +) -> Option> { + [ + RenderingIntent::RelativeColorimetric, + RenderingIntent::Perceptual, + ] + .into_iter() + .find_map(|rendering_intent| { + let options = TransformOptions { + rendering_intent, + ..TransformOptions::default() + }; + source + .create_transform_8bit(source_layout, destination, destination_layout, options) + .ok() + }) +} + +static SRGB: LazyLock = LazyLock::new(ColorProfile::new_srgb); + +/// PdfCraft patch (36): the separation hub, the RGB that Lab and ICCBased colours pass through +/// on their way to a simulated CMYK: ROMM RGB (ProPhoto) primaries, D50 white, gamma 1.8. Its +/// gamut holds practically every surface colour, so nothing printable clips on the way, and +/// paper white and black land on exact grid points of the conversion's tables. (moxcms +/// converts CMYK to CMYK and gray to CMYK only through an intermediate.) +struct Hub { + profile: ColorProfile, + /// XYZ to linear hub RGB, row-major. + from_xyz: [f32; 9], + /// The XYZ of hub white, `(1, 1, 1)`. + white: [f32; 3], +} + +impl Hub { + const GAMMA: f32 = 1.8; + + fn new() -> Self { + let profile = ColorProfile::new_pro_photo_rgb(); + let to_xyz = profile.rgb_to_xyz_matrix(); + let from_xyz = to_xyz.inverse().v; + let white = to_xyz.v.map(|row| (row[0] + row[1] + row[2]) as f32); + Self { + profile, + from_xyz: [ + from_xyz[0][0] as f32, + from_xyz[0][1] as f32, + from_xyz[0][2] as f32, + from_xyz[1][0] as f32, + from_xyz[1][1] as f32, + from_xyz[1][2] as f32, + from_xyz[2][0] as f32, + from_xyz[2][1] as f32, + from_xyz[2][2] as f32, + ], + white, + } + } + + /// D50 XYZ (Y of white 1) as hub RGB, clipped to its gamut. + fn from_xyz(&self, xyz: &[f32; 3]) -> [f32; 3] { + CalRgb::matrix_product(&self.from_xyz, xyz).map(|v| unit(v).powf(1.0 / Self::GAMMA)) + } +} + +static HUB: LazyLock = LazyLock::new(Hub::new); + +impl ColorSpace { + /// PdfCraft patch (35): this space drawn as `ink`'s plate (for images and shadings, whose + /// colours are converted sample by sample), converting process colour through + /// `simulation` (patch 36). + pub(crate) fn plate(&self, ink: Ink, simulation: Option) -> Self { + Self(Arc::new(ColorSpaceType::Plate(PlateSpace { + inner: self.clone(), + ink, + simulation, + }))) + } + + /// PdfCraft patch (36): whether `simulation` converts this space's colours (see + /// [`CmykSimulation`]). + fn simulated_by(&self, simulation: &CmykSimulation) -> bool { + match self.0.as_ref() { + ColorSpaceType::DeviceRgb + | ColorSpaceType::CalRgb(_) + | ColorSpaceType::CalGray(_) + | ColorSpaceType::Lab(_) => true, + ColorSpaceType::ICCBased(icc) => { + icc.0.number_components != 4 || icc.0.digest != simulation.0.digest + } + _ => false, + } + } + + /// PdfCraft patch (36): the colours `input` (whole colours of this space's components; + /// `manual_scale` as for [`ToRgb::convert_f32`]) in `simulation`'s CMYK, four values per + /// colour in `cmyk`. `None` when the space isn't [`simulated_by`](Self::simulated_by) + /// `simulation`, the lengths disagree, or a conversion fails. + fn simulate_cmyk( + &self, + simulation: &CmykSimulation, + input: &[f32], + manual_scale: bool, + cmyk: &mut [f32], + ) -> Option<()> { + let n = usize::from(self.num_components()).max(1); + let colours = input.len() / n; + if cmyk.len() != colours.checked_mul(4)? { + return None; + } + let mut rgb = [0.0_f32; SIMULATION_CHUNK * 3]; + let mut srgb = [0_u8; SIMULATION_CHUNK * 3]; + for (input, cmyk) in input + .chunks(SIMULATION_CHUNK * n) + .zip(cmyk.chunks_mut(SIMULATION_CHUNK * 4)) + { + let count = cmyk.len() / 4; + let input = input.get(..count.checked_mul(n)?)?; + let rgb = rgb.get_mut(..count * 3)?; + let to_cmyk = match self.0.as_ref() { + ColorSpaceType::DeviceRgb => { + for (out, v) in rgb.iter_mut().zip(input) { + *out = unit(*v); + } + &simulation.0.from_srgb + } + ColorSpaceType::CalRgb(_) | ColorSpaceType::CalGray(_) => { + let srgb = srgb.get_mut(..count * 3)?; + self.convert_f32(input, srgb, manual_scale)?; + for (out, v) in rgb.iter_mut().zip(srgb.iter()) { + *out = u8_to_f32(*v); + } + &simulation.0.from_srgb + } + ColorSpaceType::Lab(lab) => { + for (out, colour) in rgb.chunks_exact_mut(3).zip(input.chunks_exact(3)) { + out.copy_from_slice(&lab.to_hub(colour, manual_scale)); + } + &simulation.0.from_hub + } + ColorSpaceType::ICCBased(icc) if self.simulated_by(simulation) => { + icc.to_hub(input, manual_scale, rgb)?; + &simulation.0.from_hub + } + _ => return None, + }; + to_cmyk.transform(rgb, cmyk).ok()?; + } + Some(()) + } + + /// PdfCraft patch (35): DeviceCMYK itself (`CalCMYK` reads as it too), where the nonzero + /// overprint mode applies. + pub(crate) fn is_device_cmyk(&self) -> bool { + matches!(self.0.as_ref(), ColorSpaceType::DeviceCmyk) + } + + /// PdfCraft patch (35): spaces whose colours are converted to sRGB before separation + /// (DeviceRGB is separated from its components directly, without a conversion). + fn separates_through_srgb(&self) -> bool { + match self.0.as_ref() { + ColorSpaceType::CalRgb(_) | ColorSpaceType::Lab(_) => true, + ColorSpaceType::ICCBased(icc) => icc.0.number_components == 3, + _ => false, + } + } + + /// PdfCraft patch (35): how the space paints `ink`'s plate. Gray, RGB, CIE-based and ICC + /// spaces are process colour: they specify the four process inks and no spot ink. + pub(crate) fn ink_use(&self, ink: &Ink) -> InkUse { + match self.0.as_ref() { + ColorSpaceType::DeviceCmyk + | ColorSpaceType::DeviceGray + | ColorSpaceType::DeviceRgb + | ColorSpaceType::ICCBased(_) + | ColorSpaceType::CalGray(_) + | ColorSpaceType::CalRgb(_) + | ColorSpaceType::Lab(_) => { + if ink.process_index().is_some() { + InkUse::Paints + } else { + InkUse::Unspecified + } + } + ColorSpaceType::Indexed(i) => i.base.ink_use(ink), + ColorSpaceType::Separation(s) => match &s.colorant { + Colorant::None => InkUse::Nothing, + Colorant::All => InkUse::Paints, + Colorant::Ink(i) if i == ink => InkUse::Paints, + Colorant::Ink(_) => InkUse::Unspecified, + }, + ColorSpaceType::DeviceN(d) => { + if d.is_none { + InkUse::Nothing + } else if d + .colorants + .iter() + .any(|c| matches!(c, Colorant::Ink(i) if i == ink)) + { + InkUse::Paints + } else { + InkUse::Unspecified + } + } + // A pattern is separated through what it paints. + ColorSpaceType::Pattern(_) => InkUse::Unspecified, + ColorSpaceType::Plate(p) => p.inner.ink_use(ink), + } + } + + /// PdfCraft patch (35): the tint, `0.0` (no ink) to `1.0` (solid), that the colour + /// `components` puts on `ink`'s plate; `0.0` when the space doesn't specify the ink. + /// Process colour converts through `simulation` when there is one (patch 36). + /// `manual_scale` as for [`ToRgb::convert_f32`] (components normalised to `0.0..=1.0`, as + /// an Indexed palette gives them). + pub(crate) fn ink_tint( + &self, + components: &[f32], + ink: &Ink, + simulation: Option<&CmykSimulation>, + manual_scale: bool, + ) -> f32 { + let tint = match self.0.as_ref() { + ColorSpaceType::Separation(s) => match &s.colorant { + Colorant::All => components.first().copied().unwrap_or(0.0), + Colorant::Ink(i) if i == ink => components.first().copied().unwrap_or(0.0), + _ => 0.0, + }, + ColorSpaceType::DeviceN(d) => d + .colorants + .iter() + .position(|c| matches!(c, Colorant::Ink(i) if i == ink)) + .and_then(|k| components.get(k)) + .copied() + .unwrap_or(0.0), + ColorSpaceType::Indexed(i) => { + let index = components.first().copied().unwrap_or(0.0); + let index = (clamp_component(index, 0.0, f32::from(i.hival)) + 0.5) as usize; + match i.values.get(index) { + Some(values) => i.base.ink_tint(values, ink, simulation, true), + None => 0.0, + } + } + ColorSpaceType::Pattern(_) => 0.0, + ColorSpaceType::Plate(p) => p.inner.ink_tint(components, ink, simulation, manual_scale), + _ => match ( + self.process_cmyk(components, simulation, manual_scale), + ink.process_index(), + ) { + (Some(cmyk), Some(k)) => cmyk.get(k).copied().unwrap_or(0.0), + _ => 0.0, + }, + }; + unit(tint) + } + + /// PdfCraft patch (35): a process colour as DeviceCMYK: CMYK spaces (DeviceCMYK, ICC with + /// four components) as they are, gray as black only (`k = 1 − gray`, §10.4.2.2), and RGB, + /// CIE-based and three-component ICC spaces through sRGB by [`rgb_to_cmyk`]. Patch 32: + /// the spaces `simulation` converts go through it instead, and only fall back to those + /// formulas if the conversion fails. + fn process_cmyk( + &self, + components: &[f32], + simulation: Option<&CmykSimulation>, + manual_scale: bool, + ) -> Option<[f32; 4]> { + if let Some(simulation) = simulation.filter(|s| self.simulated_by(s)) { + let n = usize::from(self.num_components()).max(1); + let mut colour: ColorComponents = components.iter().copied().take(n).collect(); + colour.resize(n, 0.0); + let mut cmyk = [0.0; 4]; + if self + .simulate_cmyk(simulation, &colour, manual_scale, &mut cmyk) + .is_some() + { + return Some(cmyk.map(unit)); + } + } + let get = |k: usize| unit(components.get(k).copied().unwrap_or(0.0)); + match self.0.as_ref() { + ColorSpaceType::DeviceCmyk => Some([get(0), get(1), get(2), get(3)]), + ColorSpaceType::ICCBased(icc) if icc.0.number_components == 4 => { + Some([get(0), get(1), get(2), get(3)]) + } + ColorSpaceType::ICCBased(icc) if icc.0.number_components == 1 => { + Some([0.0, 0.0, 0.0, 1.0 - get(0)]) + } + ColorSpaceType::DeviceGray | ColorSpaceType::CalGray(_) => { + Some([0.0, 0.0, 0.0, 1.0 - get(0)]) + } + ColorSpaceType::DeviceRgb => Some(rgb_to_cmyk([get(0), get(1), get(2)])), + _ if self.separates_through_srgb() => { + let mut rgb = [0_u8; 3]; + self.convert_sample(components, &mut rgb, manual_scale)?; + Some(rgb_to_cmyk(rgb.map(u8_to_f32))) + } + _ => None, + } + } + + /// PdfCraft patch (35): tell `sink` about every spot ink the space names, with the ink's + /// appearance (the space's colour with only that component set). + pub(crate) fn report_spots(&self, sink: &InkSinkFn) { + match self.0.as_ref() { + ColorSpaceType::Separation(s) => { + if let Colorant::Ink(ink @ Ink::Spot(_)) = &s.colorant { + sink(ink, &|tint| self.appearance(&[tint])); + } + } + ColorSpaceType::DeviceN(d) => { + for (k, colorant) in d.colorants.iter().enumerate() { + if let Colorant::Ink(ink @ Ink::Spot(_)) = colorant { + sink(ink, &|tint| { + let mut components: ColorComponents = smallvec![0.0; d.colorants.len()]; + if let Some(c) = components.get_mut(k) { + *c = tint; + } + self.appearance(&components) + }); + } + } + } + ColorSpaceType::Indexed(i) => i.base.report_spots(sink), + ColorSpaceType::Pattern(cs) => cs.report_spots(sink), + ColorSpaceType::Plate(p) => p.inner.report_spots(sink), + _ => {} + } + } + + /// The sRGB colour of `components` (the `None` colorant's invisibility aside). + fn appearance(&self, components: &[f32]) -> [u8; 3] { + let [r, g, b, _] = self.to_rgba(components, 1.0, false).to_rgba8(); + [r, g, b] + } +} + +/// PdfCraft patch (35): a colour space drawn as one ink's plate: each colour becomes the gray +/// film of that ink's tint (see [`Plate`]). +#[derive(Debug, Clone)] +pub(crate) struct PlateSpace { + inner: ColorSpace, + ink: Ink, + /// Patch 32: the printing condition process colour converts to, if any. + simulation: Option, +} + +impl PlateSpace { + fn samples(&self) -> usize { + usize::from(self.inner.num_components()).max(1) + } + + /// The film of the tint the colour `sample` puts on the plate. + fn film(&self, sample: &[f32], manual_scale: bool) -> u8 { + let tint = self + .inner + .ink_tint(sample, &self.ink, self.simulation.as_ref(), manual_scale); + f32_to_u8(1.0 - tint) + } + + /// PdfCraft patch (36): the inner space's colours `input` converted through the + /// simulation, as film; `None` when the space isn't simulated or a conversion fails. + fn film_through_simulation( + &self, + input: &[f32], + output: &mut [u8], + manual_scale: bool, + ) -> Option<()> { + let simulation = self + .simulation + .as_ref() + .filter(|s| self.inner.simulated_by(s))?; + let Some(k) = self.ink.process_index() else { + output.fill(255); + return Some(()); + }; + let n = self.samples(); + let mut cmyk = [0.0_f32; SIMULATION_CHUNK * 4]; + for (input, rgb) in input + .chunks(SIMULATION_CHUNK * n) + .zip(output.chunks_mut(SIMULATION_CHUNK * 3)) + { + let count = (input.len() / n).min(rgb.len() / 3); + let cmyk = cmyk.get_mut(..count * 4)?; + self.inner + .simulate_cmyk(simulation, input.get(..count * n)?, manual_scale, cmyk)?; + for (px, colour) in rgb.chunks_exact_mut(3).zip(cmyk.chunks_exact(4)) { + px.fill(f32_to_u8(1.0 - unit(colour.get(k).copied().unwrap_or(0.0)))); + } + } + Some(()) + } + + /// The film of every entry of an Indexed inner space's palette, worked out once for an + /// image's `samples` rather than once per sample; `None` for other spaces, and when there + /// are no more samples than palette entries. + fn palette_films(&self, samples: usize) -> Option> { + let ColorSpaceType::Indexed(indexed) = self.inner.0.as_ref() else { + return None; + }; + if samples <= usize::from(indexed.hival) + 1 { + return None; + } + Some( + (0..=indexed.hival) + .map(|index| self.film(&[f32::from(index)], false)) + .collect(), + ) + } + + /// Turn sRGB pixels, converted from the inner space, into film in place. + fn film_from_srgb(&self, output: &mut [u8]) { + let Some(k) = self.ink.process_index() else { + output.fill(255); + return; + }; + for rgb in output.chunks_exact_mut(3) { + let cmyk = rgb_to_cmyk([u8_to_f32(rgb[0]), u8_to_f32(rgb[1]), u8_to_f32(rgb[2])]); + let film = f32_to_u8(1.0 - cmyk.get(k).copied().unwrap_or(0.0)); + rgb.copy_from_slice(&[film; 3]); + } + } +} + +impl ToRgb for PlateSpace { + fn convert_f32(&self, input: &[f32], output: &mut [u8], manual_scale: bool) -> Option<()> { + if self + .film_through_simulation(input, output, manual_scale) + .is_some() + { + return Some(()); + } + if self.inner.separates_through_srgb() { + self.inner.convert_f32(input, output, manual_scale)?; + self.film_from_srgb(output); + return Some(()); + } + if let Some(films) = self.palette_films(input.len()) { + // As `ink_tint` reads an Indexed sample: the index, clamped and rounded. + let hival = films.len().saturating_sub(1) as f32; + for (index, rgb) in input.iter().zip(output.chunks_exact_mut(3)) { + let index = (clamp_component(*index, 0.0, hival) + 0.5) as usize; + rgb.fill(films.get(index).copied().unwrap_or(255)); + } + return Some(()); + } + for (sample, rgb) in input + .chunks_exact(self.samples()) + .zip(output.chunks_exact_mut(3)) + { + rgb.fill(self.film(sample, manual_scale)); + } + Some(()) + } + + // The spaces that take bytes (device and ICC spaces) read them as component × 255. + fn supports_u8(&self) -> bool { + self.inner.supports_u8() + } + + fn convert_u8(&self, input: &[u8], output: &mut [u8]) -> Option<()> { + if self + .simulation + .as_ref() + .is_some_and(|s| self.inner.simulated_by(s)) + { + // Bytes are the components' encoding scaled to 0–255 (an ICC L*a*b* colour's too, + // so they arrive as `manual_scale` components). + let n = self.samples(); + let mut floats = [0.0_f32; SIMULATION_CHUNK * 4]; + let mut done = Some(()); + for (bytes, rgb) in input + .chunks(SIMULATION_CHUNK * n) + .zip(output.chunks_mut(SIMULATION_CHUNK * 3)) + { + let floats = floats.get_mut(..bytes.len())?; + for (f, b) in floats.iter_mut().zip(bytes) { + *f = u8_to_f32(*b); + } + done = done.and(self.film_through_simulation(floats, rgb, true)); + } + if done.is_some() { + return Some(()); + } + } + if self.inner.separates_through_srgb() { + self.inner.convert_u8(input, output)?; + self.film_from_srgb(output); + return Some(()); + } + let mut sample: ColorComponents = SmallVec::new(); + for (bytes, rgb) in input + .chunks_exact(self.samples()) + .zip(output.chunks_exact_mut(3)) + { + sample.clear(); + sample.extend(bytes.iter().copied().map(u8_to_f32)); + rgb.fill(self.film(&sample, false)); + } + Some(()) + } + + fn is_none(&self) -> bool { + self.inner.is_none() + } } static CMYK_TRANSFORM: LazyLock = LazyLock::new(|| { diff --git a/vendor/hayro-interpret/src/interpret/mod.rs b/vendor/hayro-interpret/src/interpret/mod.rs index b389b6b3d..99e21f7dc 100644 --- a/vendor/hayro-interpret/src/interpret/mod.rs +++ b/vendor/hayro-interpret/src/interpret/mod.rs @@ -120,6 +120,14 @@ pub struct InterpreterSettings { /// costs a decode and a resample each for pixels nobody can see. Never set it for a final /// render (tiles, whole pages, print, export). pub preview: bool, + /// PdfCraft patch (35): draw one ink's separation instead of the composite page (see + /// [`Plate`](crate::color::Plate)). Soft masks still draw in colour: a mask's luminosity + /// comes from its group's colours, not from any plate. Patch 32: the plate's `simulation` + /// converts process colour to an output intent's CMYK. + pub plate: Option, + /// PdfCraft patch (35): told about each spot ink a paint uses (colours, images, shadings + /// and uncoloured patterns), whether or not `plate` is set. + pub ink_sink: Option, } impl Default for InterpreterSettings { @@ -142,6 +150,8 @@ impl Default for InterpreterSettings { ocg_overrides: Arc::new(Vec::new()), cancelled: None, preview: false, + plate: None, + ink_sink: None, } } } diff --git a/vendor/hayro-interpret/src/interpret/path.rs b/vendor/hayro-interpret/src/interpret/path.rs index 838ea099f..6c75c4648 100644 --- a/vendor/hayro-interpret/src/interpret/path.rs +++ b/vendor/hayro-interpret/src/interpret/path.rs @@ -1,6 +1,8 @@ -use crate::color::{Color, ColorSpace}; +use crate::color::{Color, ColorSpace, InkUse, Plate}; use crate::context::{Context, path_as_rect}; use crate::device::Device; +use crate::interpret::state::PaintData; +use crate::pattern::Pattern; use crate::util::{BezPathExt, Float32Ext}; use crate::{FillRule, Paint, PathDrawMode, StrokeProps}; use kurbo::{BezPath, Cap, Join, PathEl}; @@ -153,6 +155,23 @@ pub(crate) fn get_paint<'a>(context: &Context<'a>, is_stroke: bool) -> Paint<'a> context.get().non_stroke_data() }; + // PdfCraft patch (35): report spot inks, and draw separations. + if let Some(sink) = &context.settings.ink_sink { + data.color_space.report_spots(sink); + if let Some(Pattern::Shading(s)) = &data.pattern { + s.shading.color_space.report_spots(sink); + } + } + if let Some(plate) = &context.settings.plate { + let state = &context.get().graphics_state; + let overprint = if is_stroke { + state.overprint_stroke + } else { + state.overprint_fill + }; + return plate_paint(context, data, plate, overprint, state.overprint_mode); + } + if data.color_space.is_pattern() || data.pattern.is_some() { if let Some(mut pattern) = data.pattern { if let Some(tf) = &data.transfer_function { @@ -176,3 +195,39 @@ pub(crate) fn get_paint<'a>(context: &Context<'a>, is_stroke: bool) -> Paint<'a> } } } + +/// PdfCraft patch (35): the paint `data` as drawn on `plate`: a colour becomes its film, a +/// shading is converted through the plate, and a paint that leaves the plate as it is (an +/// overprinting paint that doesn't specify the plate's ink, or the `None` colorant) becomes +/// transparent. Transfer functions are left out: they act on device colorants, which the +/// film doesn't model. +fn plate_paint<'a>( + context: &Context<'a>, + data: PaintData<'a>, + plate: &Plate, + overprint: bool, + overprint_mode: u8, +) -> Paint<'a> { + let untouched = || Paint::Color(Color::film(0.0, 0.0)); + if !(data.color_space.is_pattern() || data.pattern.is_some()) { + let color = Color::new(data.color_space, data.color, data.alpha); + return Paint::Color(color.for_plate(plate, overprint, overprint_mode)); + } + let Some(mut pattern) = data.pattern else { + // Pattern was likely invalid, use transparent paint. + return untouched(); + }; + match &mut pattern { + Pattern::Shading(s) => { + match s.shading.color_space.ink_use(&plate.ink) { + InkUse::Nothing => return untouched(), + InkUse::Unspecified if plate.overprint && overprint => return untouched(), + InkUse::Paints | InkUse::Unspecified => {} + } + std::sync::Arc::make_mut(&mut s.shading).for_plate(plate); + } + Pattern::Tiling(t) => t.for_plate(plate, overprint, overprint_mode), + } + pattern.pre_concat_transform(context.root_transform()); + Paint::Pattern(Box::new(pattern)) +} diff --git a/vendor/hayro-interpret/src/interpret/state.rs b/vendor/hayro-interpret/src/interpret/state.rs index 95b773fb5..de8f24e2f 100644 --- a/vendor/hayro-interpret/src/interpret/state.rs +++ b/vendor/hayro-interpret/src/interpret/state.rs @@ -269,6 +269,12 @@ pub(crate) struct GraphicsState<'a> { pub(crate) soft_mask: Option>, pub(crate) transfer_function: Option, pub(crate) blend_mode: BlendMode, + + // PdfCraft patch (35): the overprint parameters (ISO 32000-2 §8.6.7, `OP`, `op` and `OPM` + // in a graphics state parameter dictionary). They only matter when drawing separations. + pub(crate) overprint_stroke: bool, + pub(crate) overprint_fill: bool, + pub(crate) overprint_mode: u8, } impl Default for GraphicsState<'_> { @@ -286,6 +292,9 @@ impl Default for GraphicsState<'_> { soft_mask: None, transfer_function: None, blend_mode: BlendMode::default(), + overprint_stroke: false, + overprint_fill: false, + overprint_mode: 0, } } } @@ -408,6 +417,21 @@ pub(crate) fn handle_gs_single<'a>( .map(|n| if n == 0.0 { 0.01 } else { n }) .collect(); } + // PdfCraft patch (35): `OP` sets stroking overprint, and non-stroking overprint too when + // the dictionary has no `op` of its own; `OPM` is 0 or 1 (§8.6.7). + "OP" => { + let overprint = dict.get::(key)?; + let state = &mut context.get_mut().graphics_state; + state.overprint_stroke = overprint; + if !dict.contains_key("op") { + state.overprint_fill = overprint; + } + } + "op" => context.get_mut().graphics_state.overprint_fill = dict.get::(key)?, + "OPM" => { + let mode = dict.get::(key)?; + context.get_mut().graphics_state.overprint_mode = u8::from(mode == 1); + } "Type" => {} _ => {} } diff --git a/vendor/hayro-interpret/src/pattern.rs b/vendor/hayro-interpret/src/pattern.rs index 3d6d22293..b916a3818 100644 --- a/vendor/hayro-interpret/src/pattern.rs +++ b/vendor/hayro-interpret/src/pattern.rs @@ -1,7 +1,7 @@ //! PDF patterns. use crate::cache::Cache; -use crate::color::{Color, ColorSpace}; +use crate::color::{Color, ColorSpace, Plate}; use crate::context::{Context, InterpreterCache}; use crate::device::Device; use crate::font::Glyph; @@ -147,6 +147,30 @@ pub struct TilingPattern<'a> { nesting_depth: u32, } +impl TilingPattern<'_> { + /// PdfCraft patch (35): an uncoloured pattern draws its cell in the colour it is used + /// with, so on a plate it draws that colour's film. A coloured pattern's cell is separated + /// as it is drawn. + pub(crate) fn for_plate(&mut self, plate: &Plate, overprint: bool, overprint_mode: u8) { + if !self.is_color { + self.stroke_paint = self + .stroke_paint + .for_plate(plate, overprint, overprint_mode); + self.non_stroking_paint = + self.non_stroking_paint + .for_plate(plate, overprint, overprint_mode); + } + let simulation = plate.simulation.as_ref().map(|s| s.digest()); + self.cache_key = hash128(&( + self.cache_key, + &plate.ink, + plate.overprint, + overprint, + simulation, + )); + } +} + impl Debug for TilingPattern<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str("TilingPattern") diff --git a/vendor/hayro-interpret/src/shading.rs b/vendor/hayro-interpret/src/shading.rs index 2e619e47f..0c4ad1e78 100644 --- a/vendor/hayro-interpret/src/shading.rs +++ b/vendor/hayro-interpret/src/shading.rs @@ -139,6 +139,16 @@ pub struct Shading { } impl Shading { + /// PdfCraft patch (35): the shading drawn as `plate`'s plate, through its simulation + /// (patch 36). + pub(crate) fn for_plate(&mut self, plate: &crate::color::Plate) { + self.color_space = self + .color_space + .plate(plate.ink.clone(), plate.simulation.clone()); + let simulation = plate.simulation.as_ref().map(|s| s.digest()); + self.cache_key = crate::util::hash128(&(self.cache_key, &plate.ink, simulation)); + } + pub(crate) fn new(dict: &Dict<'_>, stream: Option<&Stream<'_>>, cache: &Cache) -> Option { let cache_key = dict.cache_key(); diff --git a/vendor/hayro-interpret/src/soft_mask.rs b/vendor/hayro-interpret/src/soft_mask.rs index 92cab551b..657d6bbff 100644 --- a/vendor/hayro-interpret/src/soft_mask.rs +++ b/vendor/hayro-interpret/src/soft_mask.rs @@ -169,7 +169,13 @@ impl<'a> SoftMask<'a> { transfer_function, bbox: context.bbox(), interpreter_cache: context.interpreter_cache.clone(), - settings: context.settings.clone(), + // PdfCraft patch (35): a mask's luminosity comes from its group's colours, never + // from a plate, and the inks it uses are never printed. + settings: InterpreterSettings { + plate: None, + ink_sink: None, + ..context.settings.clone() + }, xref: context.xref, background, parent_resources, diff --git a/vendor/hayro-interpret/src/x_object.rs b/vendor/hayro-interpret/src/x_object.rs index d7d19dce7..6a846148f 100644 --- a/vendor/hayro-interpret/src/x_object.rs +++ b/vendor/hayro-interpret/src/x_object.rs @@ -1,5 +1,5 @@ use crate::cache::{Cache, DecodedImageCache, DecodedImageKey}; -use crate::color::{ColorComponents, ColorSpace, ToRgb}; +use crate::color::{ColorComponents, ColorSpace, InkUse, Plate, ToRgb}; use crate::context::Context; use crate::device::Device; use crate::function::{Function, interpolate}; @@ -227,6 +227,37 @@ pub(crate) fn draw_image_xobject<'a, 'b>( return; } + // PdfCraft patch (35): report the image's spot inks, and draw it on a plate. An image + // without a colour space takes one from its data (JPEG, JPEG 2000): gray, RGB or CMYK, + // all process colour. Images paint with the non-stroking overprint parameter. + let raster_cs = if x_object.is_mask { + None + } else { + x_object.color_space.as_ref() + }; + if let (Some(sink), Some(cs)) = (&context.settings.ink_sink, raster_cs) { + cs.report_spots(sink); + } + let mut on_plate = None; + if let Some(plate) = &context.settings.plate + && !x_object.is_mask + { + let ink_use = match raster_cs { + Some(cs) => cs.ink_use(&plate.ink), + None if plate.ink.process_index().is_some() => InkUse::Paints, + None => InkUse::Unspecified, + }; + let overprint = plate.overprint && context.get().graphics_state.overprint_fill; + if ink_use == InkUse::Nothing || (ink_use == InkUse::Unspecified && overprint) { + if has_oc { + context.ocg_state.end_marked_content(); + } + return; + } + on_plate = Some(x_object.for_plate(plate)); + } + let x_object = on_plate.as_ref().unwrap_or(x_object); + let width = x_object.width as f64; let height = x_object.height as f64; @@ -308,9 +339,22 @@ pub(crate) struct ImageXObject<'a> { stream: Stream<'a>, transfer_function: Option, warning_sink: WarningSinkFn, + /// PdfCraft patch (35): the plate the image is drawn on, if any. + plate: Option, } impl<'a> ImageXObject<'a> { + /// PdfCraft patch (35): the image drawn on `plate`. Not cached (the cache holds colour + /// decodes), and without a transfer function (see `get_paint`). + fn for_plate(&self, plate: &Plate) -> Self { + Self { + plate: Some(plate.clone()), + decoded_cache: None, + transfer_function: None, + ..self.clone() + } + } + pub(crate) fn new( stream: &Stream<'a>, resolve_cs: impl FnOnce(&Name<'_>) -> Option, @@ -371,6 +415,7 @@ impl<'a> ImageXObject<'a> { stream: stream.clone(), is_mask, is_stencil_mask, + plate: None, }) } @@ -594,6 +639,11 @@ fn decode_context<'a>( }) }) .unwrap_or(ColorSpace::device_gray()); + // PdfCraft patch (35): on a plate, every sample converts to the ink's film. + let color_space = match &obj.plate { + Some(plate) => color_space.plate(plate.ink.clone(), plate.simulation.clone()), + None => color_space, + }; let fallback_bpc = if obj.is_stencil_mask { 1 } else { 8 };