fix(render): an isolated DeviceCMYK transparency group blends in CMYK

ISO 32000-2 §11.3.4: the elements of a transparency group blend in the
group's colour space. For a subtractive space, each component is
complemented before the blend function and again after it. §11.3.5.3:
the nonseparable modes blend C, M and Y as their complements R, G and B,
and K comes from the backdrop (Hue, Saturation, Color) or from the source
(Luminosity). PdfCraft converted each colour to RGB and blended in RGB.
A print test file's blend-mode patch then showed an X in almost every
cell: magenta under black with Difference stayed magenta, not green.

hayro-interpret patch (45): CmykGroup and Device::draw_isolated_cmyk_group
(default false) for isolated, non-knockout groups with /CS /DeviceCMYK.
interpret_form_contents is now a function of its own. Color::ink_tints
and color::cmyk_to_srgb8 are new.

hayro patch (21): the renderer draws such a group as a CMY pass and a K
pass of complemented tints. It converts the tints to RGB with the CMYK
profile and composites the result through the group's layer. The group
is drawn as before with reading colours, for contents without process
tints (RGB, spot colours, patterns, images) and above 2^24 pixels.

Test: raster::tests::isolated_groups_blend_in_device_cmyk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jpeskov
2026-10-28 18:20:28 -04:00
committed by KenM76
co-authored by Claude Opus 5.5
parent dc943eeb13
commit ba09e1aefc
9 changed files with 474 additions and 19 deletions
+4
View File
@@ -7004,6 +7004,10 @@ mod default_colour_spaces;
// (vendored hayro-syntax patch 28, hayro-interpret patch 55).
mod devicen_inks;
// #3776: isolated DeviceCMYK groups blend in CMYK (vendored hayro-interpret patch 45, hayro
// patch 21).
mod isolated_cmyk_groups;
/// #3109 / #3116: clipping-only text (`7 Tr`) installs a clip for subsequent painting
/// but draws no pixels itself.
#[test]
@@ -0,0 +1,97 @@
//! Isolated transparency groups whose colour space is `DeviceCMYK` blend in CMYK (ISO 32000-2
//! §11.3.4, §11.3.5.3).
use crate::{PageRenderer, RenderConfig, RenderRequest, RenderedPage, RequestKind};
use std::sync::Arc;
/// A print test file's patch of blend modes in isolated groups whose colour space is
/// `DeviceCMYK` drew an X in nearly every cell. The elements of a group blend in the
/// group's colour space, and a subtractive space's components are complemented before the
/// blend function and back after it (ISO 32000-2 §11.3.4); of the nonseparable modes,
/// §11.3.5.3 blends C, M and Y as complemented R, G and B and takes K from the backdrop
/// (from the source for Luminosity). PdfCraft blended the colours converted to RGB, so
/// magenta under black with Difference came out magenta instead of green. Vendored
/// hayro-interpret patch (45) and hayro patch (21): an isolated group (§11.4.7: its own
/// transparent backdrop) blending in DeviceCMYK is blended in CMYK.
///
/// Each cell is a square painted in the CMYK the blend should give, with a smaller isolated
/// group on it whose two elements are tint A and then tint B with the cell's blend mode:
/// drawn right, the group is the colour of the square around it.
#[test]
fn isolated_groups_blend_in_device_cmyk() {
// (blend mode, tint A, tint B, A then B blended in DeviceCMYK, worked out by hand)
type Cell = (&'static str, [f32; 4], [f32; 4], [f32; 4]);
let cells: [Cell; 7] = [
// |(1,0,1,1) − (1,1,1,0)| = (0,1,0,1), complemented back: green.
("Difference", [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 1.0, 0.0]),
("Exclusion", [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0], [1.0, 0.0, 1.0, 0.0]),
("Multiply", [0.0, 0.0, 1.0, 0.0], [0.0, 0.5, 0.0, 0.0], [0.0, 0.5, 1.0, 0.0]),
("Screen", [0.0, 1.0, 1.0, 0.0], [0.5, 0.5, 1.0, 0.0], [0.0, 0.5, 1.0, 0.0]),
("Darken", [0.0, 0.0, 1.0, 0.0], [0.0, 0.5, 0.0, 0.0], [0.0, 0.5, 1.0, 0.0]),
// Hue of (0,1,1) at the saturation and luminosity of (1,0.5,1): (0.355,0.855,0.855);
// K is the backdrop's.
("Hue", [0.0, 0.5, 0.0, 0.3], [1.0, 0.0, 0.0, 0.0], [0.645, 0.145, 0.145, 0.3]),
// (1,0,1) at the luminosity of (0,1,0), clipped: (1,0.3051,1); K is the source's.
("Luminosity", [0.0, 1.0, 0.0, 0.3], [1.0, 0.0, 1.0, 0.0], [0.0, 0.6949, 0.0, 0.0]),
];
let tint = |t: [f32; 4]| format!("{} {} {} {} k", t[0], t[1], t[2], t[3]);
// `group`: the cell group's /Group entries; `b`: what the second element paints.
let render = |group: &str, b: &dyn Fn([f32; 4]) -> String| {
let (mut page, mut objects, mut names) = (String::new(), String::new(), String::new());
for (i, (mode, ta, tb, expected)) in cells.iter().enumerate() {
let x = 10 + i * 50;
page += &format!("{} {x} 10 40 40 re f /G{i} Do\n", tint(*expected));
let rect = format!("{} 20 20 20 re f", x + 10);
let n = 10 + i * 3;
for (k, paint) in [(n, tint(*ta)), (n + 1, b(*tb))] {
let body = format!("{paint} {rect}");
objects += &format!(
"{k} 0 obj << /Type /XObject /Subtype /Form /BBox [{x} 10 {} 50] /Group << /S /Transparency /CS /DeviceCMYK >> /Length {} >> stream\n{body}\nendstream endobj\n",
x + 40,
body.len()
);
}
let body = "/E1 Do /BM gs /E2 Do";
objects += &format!(
"{} 0 obj << /Type /XObject /Subtype /Form /BBox [{x} 10 {} 50] /Group << /S /Transparency {group} >> /Resources << /XObject << /E1 {n} 0 R /E2 {} 0 R >> /ExtGState << /BM << /BM /{mode} >> >> >> /Length {} >> stream\n{body}\nendstream endobj\n",
n + 2,
x + 40,
n + 1,
body.len()
);
names += &format!("/G{i} {} 0 R ", n + 2);
}
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 370 60] /Group << /S /Transparency /CS /DeviceCMYK >> /Contents 4 0 R /Resources << /XObject << {names}>> >> >> endobj
4 0 obj << /Length {} >> stream
{page}
endstream endobj
{objects}trailer << /Root 1 0 R >>
%%EOF",
page.len()
);
let mut r = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default());
let p = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, ..Default::default() });
assert!(p.error.is_none(), "{group}: {:?}", p.error);
p
};
let px = |p: &RenderedPage, x: usize, y: u32| p.rgba[((y * p.width + x as u32) * 4) as usize..][..3].to_vec();
let distance = |a: &[u8], b: &[u8]| a.iter().zip(b).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
let p = render("/CS /DeviceCMYK /I true", &tint);
for (i, (mode, ..)) in cells.iter().enumerate() {
let (group, square) = (px(&p, 30 + i * 50, 30), px(&p, 14 + i * 50, 30));
// The square is a solid CMYK fill; the group lands within rounding of it.
assert!(distance(&group, &square) <= 3, "{mode}: group {group:?}, square {square:?}");
}
// A group whose contents have no ink tints (here the second element is RGB) is
// composited in RGB exactly as before: the same as a group blending in DeviceRGB.
let rgb = |_: [f32; 4]| "1 0 0 rg".to_string();
let cmyk_group = render("/CS /DeviceCMYK /I true", &rgb);
let rgb_group = render("/CS /DeviceRGB /I true", &rgb);
assert_eq!(cmyk_group.rgba, rgb_group.rgba, "contents without tints are drawn as before");
}
+2 -2
View File
File diff suppressed because one or more lines are too long
+95
View File
@@ -0,0 +1,95 @@
//! PdfCraft patch (45): an isolated transparency group that blends in `DeviceCMYK`.
//!
//! ISO 32000-2 §11.3.4: a group's elements blend in the group's colour space, and the
//! components of a subtractive space are complemented before the blend function and
//! complemented back after it. The renderer composites in RGB, which gives other colours
//! wherever a blend mode meets CMYK artwork: `0 1 0 0 k` (magenta) under `0 0 0 1 k` (black)
//! with `/BM /Difference` is green when blended in CMYK (`|(1,0,1,1) − (1,1,1,0)|`
//! complemented back is `1 0 1 0`) and magenta when blended in RGB.
//!
//! An *isolated* group starts from a transparent backdrop of its own (§11.4.7), so its
//! interior can be computed apart from the page and handed back as finished pixels. A device
//! that can blend in CMYK takes such a group through [`Device::draw_isolated_cmyk_group`] and
//! interprets it with [`CmykGroup::interpret`] as often as it needs; every other device, and a
//! device that declines, gets the group's contents as before.
use crate::InterpreterSettings;
use crate::context::{Context, InterpreterCache};
use crate::device::Device;
use crate::interpret::state::{ClipType, State};
use crate::x_object::{FormXObject, interpret_form_contents};
use hayro_syntax::object::dict::keys::{CS, GROUP};
use hayro_syntax::object::{Dict, Name};
use hayro_syntax::page::Resources;
use hayro_syntax::xref::XRef;
use kurbo::{Affine, Rect, Shape};
use std::ops::Deref;
/// An isolated, non-knockout transparency group whose blending colour space is `DeviceCMYK`,
/// captured where it is painted (PdfCraft patch (45); see the module documentation).
pub struct CmykGroup<'a, 'b> {
form: &'b FormXObject<'a>,
resources: &'b Resources<'a>,
/// The graphics state the group's contents start with: the state at `Do`, after the
/// form's `/Matrix`, with the group's own opacity, soft mask and blend mode already taken
/// by the layer the group is composited through.
state: State<'a>,
root_transform: Affine,
bbox: Rect,
interpreter_cache: InterpreterCache<'a>,
settings: InterpreterSettings,
xref: &'a XRef,
nesting_depth: u32,
}
impl<'a, 'b> CmykGroup<'a, 'b> {
pub(crate) fn new(form: &'b FormXObject<'a>, resources: &'b Resources<'a>, context: &Context<'a>) -> Self {
let mut state = context.get().clone();
// The clips in force belong to the device the group is composited onto; contents
// interpreted on their own push and pop only the clips they set themselves.
state.clips = Vec::<ClipType>::new();
Self {
form,
resources,
state,
root_transform: context.root_transform(),
bbox: context.bbox(),
interpreter_cache: context.interpreter_cache.clone(),
settings: context.settings.clone(),
xref: context.xref,
nesting_depth: context.nesting_depth(),
}
}
/// The device-space box the group can paint: its `/BBox` under the current transform,
/// within the area being drawn.
pub fn device_bbox(&self) -> Rect {
let [x0, y0, x1, y1] = self.form.bbox;
let user = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64);
let device = (self.state.ctm * user.to_path(0.1)).bounding_box();
device.intersect(self.bbox)
}
/// Interpret the group's contents into `device`, with device space moved by `offset`
/// (so a device covering only [`Self::device_bbox`] can start at its corner).
pub fn interpret(&self, device: &mut impl Device<'a>, offset: (f64, f64)) {
let shift = Affine::translate((-offset.0, -offset.1));
let mut state = self.state.clone();
state.ctm = shift * state.ctm;
let mut context = Context::new_with(
shift * self.root_transform,
shift.transform_rect_bbox(self.bbox),
&self.interpreter_cache,
self.xref,
self.settings.clone(),
state,
self.nesting_depth,
);
interpret_form_contents(self.resources, self.form, &mut context, device);
}
}
/// Whether `form`'s transparency group blends in `DeviceCMYK`: it says so in its `/CS`.
pub(crate) fn blends_in_device_cmyk(form: &Dict<'_>) -> bool {
form.get::<Dict<'_>>(GROUP).and_then(|g| g.get::<Name<'_>>(CS)).is_some_and(|cs| matches!(cs.deref(), b"DeviceCMYK" | b"CMYK"))
}
+36
View File
@@ -1399,6 +1399,32 @@ impl Color {
.to_rgba(&self.components, self.opacity, false)
}
/// PdfCraft patch (45): the colour as process ink tints `[C, M, Y, K]` (0 = no ink) and
/// its opacity, for blending in a `DeviceCMYK` transparency group (ISO 32000-2 §11.3.4).
///
/// `DeviceCMYK` gives its components. `DeviceGray` is black ink alone, `K = 1 − gray`
/// (§10.4.2.2). Four-component ICC colour is taken as the tints it names, unconverted.
/// `None` for every other space: such a colour has no tints without a colour conversion
/// this crate does not make, and the caller draws it as before.
pub fn ink_tints(&self) -> Option<([f32; 4], f32)> {
let c = |i: usize| {
self.components
.get(i)
.copied()
.unwrap_or(0.0)
.clamp(0.0, 1.0)
};
let tints = match self.color_space.0.as_ref() {
ColorSpaceType::DeviceCmyk => [c(0), c(1), c(2), c(3)],
ColorSpaceType::ICCBased(icc) if icc.0.number_components == 4 => {
[c(0), c(1), c(2), c(3)]
}
ColorSpaceType::DeviceGray => [0.0, 0.0, 0.0, 1.0 - c(0)],
_ => return None,
};
Some((tints, self.opacity.clamp(0.0, 1.0)))
}
/// Create a color from RGBA.
pub fn from_rgba(rgba: AlphaColor) -> Self {
let c = rgba.components();
@@ -1410,6 +1436,16 @@ impl Color {
}
}
/// PdfCraft patch (45): `input`, 8-bit `DeviceCMYK` pixels (four bytes each), converted to
/// 8-bit sRGB in `output` (three bytes each) through the CMYK profile pages are drawn with,
/// so a colour blended in CMYK lands where the same colour painted directly does.
pub fn cmyk_to_srgb8(input: &[u8], output: &mut [u8]) -> Option<()> {
if input.len() % 4 != 0 || output.len() != input.len() / 4 * 3 {
return None;
}
CMYK_TRANSFORM.convert_u8(input, output)
}
static CMYK_TRANSFORM: LazyLock<ICCProfile> = LazyLock::new(|| {
ICCProfile::new(include_bytes!("../assets/CGATS001Compat-v2-micro.icc"), 4).unwrap()
});
+8
View File
@@ -1,3 +1,4 @@
use crate::cmyk_group::CmykGroup;
use crate::font::Glyph;
use crate::soft_mask::SoftMask;
use crate::{BlendMode, ClipPath, Image};
@@ -107,6 +108,13 @@ pub trait Device<'a> {
fn begin_knockout_erase(&mut self) {}
/// PdfCraft patch (39): see `knockout_erase_wanted`.
fn end_knockout_erase(&mut self) {}
/// PdfCraft patch (45): draw the contents of an isolated transparency group that blends
/// in `DeviceCMYK` (ISO 32000-2 §11.3.4), already inside the layer it is composited
/// through. Return `true` when the device drew them; on `false` (the default) the
/// interpreter draws the contents into the device as for any other group.
fn draw_isolated_cmyk_group(&mut self, _group: &CmykGroup<'a, '_>) -> bool {
false
}
}
/// A device that discards all drawing operations.
+2
View File
@@ -32,6 +32,7 @@ This crate has one optional feature:
mod log;
mod cache;
mod cmyk_group;
mod context;
mod convert;
mod device;
@@ -53,6 +54,7 @@ pub mod shading;
pub mod util;
pub use cache::CacheKey;
pub use cmyk_group::CmykGroup;
pub use context::*;
pub use device::*;
pub use function::Function;
+42 -17
View File
@@ -1,4 +1,5 @@
use crate::cache::{Cache, DecodedImageCache, DecodedImageKey};
use crate::cmyk_group::{CmykGroup, blends_in_device_cmyk};
use crate::color::{ColorComponents, ColorSpace, DefaultColorSpaces, DeviceFamily, ToRgb};
use crate::context::Context;
use crate::device::Device;
@@ -138,8 +139,6 @@ pub(crate) fn draw_form_xobject<'a, 'b>(
return;
}
let iter = TypedIter::new(x_object.decoded.as_ref());
context.path_mut().truncate(0);
context.save_state();
context.pre_concat_affine(x_object.matrix);
@@ -210,6 +209,45 @@ pub(crate) fn draw_form_xobject<'a, 'b>(
}
}
let resources = Resources::for_form(x_object.resources.clone(), resources.clone());
// PdfCraft patch (45): an isolated group blending in DeviceCMYK starts from a backdrop of
// its own, so a device able to blend in CMYK computes its interior apart and composites the
// result through the layer pushed above (see `cmyk_group`). Knockout groups are left out:
// their elements composite with the group's initial backdrop, not with each other.
let blended_in_cmyk = own_layer
&& x_object.is_isolated
&& !x_object.is_knockout
&& blends_in_device_cmyk(&x_object.dict)
&& device.draw_isolated_cmyk_group(&CmykGroup::new(x_object, &resources, context));
if !blended_in_cmyk {
interpret_form_contents(&resources, x_object, context, device);
}
if own_layer {
device.pop_transparency_group();
}
context.pop_root_transform();
context.restore_state(device);
if has_oc {
context.ocg_state.end_marked_content();
}
context.end_nested_interpretation();
}
/// The contents of form `x_object`, in `context` as prepared for them (the form's `/Matrix`
/// applied, its root transform pushed), clipped to its `/BBox`. PdfCraft patch (45): shared by
/// [`draw_form_xobject`] and [`CmykGroup::interpret`].
pub(crate) fn interpret_form_contents<'a>(
resources: &Resources<'a>,
x_object: &FormXObject<'a>,
context: &mut Context<'a>,
device: &mut impl Device<'a>,
) {
device.set_soft_mask(context.get().graphics_state.soft_mask.clone());
device.set_blend_mode(context.get().graphics_state.blend_mode);
@@ -226,26 +264,13 @@ pub(crate) fn draw_form_xobject<'a, 'b>(
});
interpret(
iter,
&Resources::for_form(x_object.resources.clone(), resources.clone()),
TypedIter::new(x_object.decoded.as_ref()),
resources,
context,
device,
);
device.pop_clip_path();
if own_layer {
device.pop_transparency_group();
}
context.pop_root_transform();
context.restore_state(device);
if has_oc {
context.ocg_state.end_marked_content();
}
context.end_nested_interpretation();
}
pub(crate) fn draw_image_xobject<'a, 'b>(
+188
View File
@@ -436,6 +436,11 @@ enum PaintSetup {
Nothing,
}
/// PdfCraft patch (21): the largest group, in device pixels, blended in CMYK (2^24, a 4096 ×
/// 4096 square). Each pixel costs about 20 bytes more than drawing the group as before (two
/// pass canvases, its tints, their RGB and the result); a larger group is drawn as before.
const MAX_CMYK_GROUP_PIXELS: u64 = 1 << 24;
pub(crate) struct Renderer {
pub(crate) ctx: RenderContext,
/// PdfCraft patch: when set, solid text and line-art paint colours are remapped
@@ -464,6 +469,50 @@ pub(crate) struct Renderer {
pub(crate) preview: bool,
// TODO: Remove this once vello_cpu bug with non-transparent images is fixed
image_transparency_stack: Vec<bool>,
/// PdfCraft patch (21): set while this renderer draws one ink pass of a group blending
/// in `DeviceCMYK` (see [`Renderer::draw_isolated_cmyk_group`]).
ink: InkState,
}
/// PdfCraft patch (21): which inks a pass of a `DeviceCMYK` group draws, and whether the
/// group asked for something a pass can't draw.
///
/// A pass paints the complement of ink tints as colour — no ink is white — so the RGB blend
/// functions compute ISO 32000-2 §11.3.4's subtractive blend, `1 − B(1 − cb, 1 − cs)`, and
/// complementing the pixels back gives the tints. The cyan, magenta and yellow pass paints
/// them as red, green and blue, which is also how §11.3.5.3 has the nonseparable modes treat
/// them. The black pass paints black ink as a grey, so a separable mode blends it like any
/// tint, and of the nonseparable modes Hue, Saturation and Color keep the backdrop's grey
/// while Luminosity takes the source's: §11.3.5.3's rule for the K component.
#[derive(Clone, Copy, Default)]
struct InkState {
pass: Option<InkPass>,
/// Something in the group has no ink tints (an RGB colour, a pattern, an image): the
/// group is drawn as before instead.
unsupported: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum InkPass {
/// Cyan, magenta and yellow as red, green and blue.
Cmy,
/// Black as grey.
K,
}
impl InkState {
/// The colour a pass paints for `color`; transparent, with the group marked unsupported,
/// when the colour has no ink tints.
fn paint(&mut self, pass: InkPass, color: &Color) -> AlphaColor<Srgb> {
let Some(([c, m, y, k], alpha)) = color.ink_tints() else {
self.unsupported = true;
return AlphaColor::TRANSPARENT;
};
match pass {
InkPass::Cmy => AlphaColor::new([1.0 - c, 1.0 - m, 1.0 - y, alpha]),
InkPass::K => AlphaColor::new([1.0 - k, 1.0 - k, 1.0 - k, alpha]),
}
}
}
#[derive(Clone, Copy)]
@@ -502,6 +551,7 @@ impl Renderer {
scaler: Scaler::new(ResamplingFunction::CatmullRom),
preview,
image_transparency_stack: Vec::new(),
ink: InkState::default(),
}
}
@@ -606,6 +656,7 @@ impl Renderer {
scaler: self.scaler,
preview: self.preview,
image_transparency_stack: Vec::new(),
ink: InkState::default(),
};
let mut mask_pix = Pixmap::new(self.ctx.width(), self.ctx.height());
let rgb_data = ImageData::Rgb(RgbData {
@@ -1075,6 +1126,48 @@ impl Renderer {
.fill_rect(&Rect::new(0.0, 0.0, width as f64, height as f64));
}
/// PdfCraft patch (21): one ink pass of `group` (see [`InkState`]) on a `width` × `height`
/// canvas whose corner is device point `offset`; `None` when the group holds something the
/// pass has no tints for.
fn ink_pass(
&self,
group: &hayro_interpret::CmykGroup<'_, '_>,
pass: InkPass,
offset: (f64, f64),
width: u16,
height: u16,
) -> Option<Pixmap> {
let mut renderer = Self {
ctx: RenderContext::new_with(width, height, derive_settings(self.ctx.render_settings())),
color_replacement: None,
in_annotations: self.in_annotations,
inside_pattern: self.inside_pattern,
soft_mask_cache: HashMap::default(),
outline_cache: self.outline_cache.clone(),
cur_mask: None,
in_type3_glyph: false,
scaler: Scaler::new(ResamplingFunction::CatmullRom),
preview: self.preview,
image_transparency_stack: Vec::new(),
ink: InkState {
pass: Some(pass),
unsupported: false,
},
knockout: Vec::new(),
erasing: false,
erase_groups: 0,
};
group.interpret(&mut renderer, offset);
if renderer.ink.unsupported {
return None;
}
let mut pix = Pixmap::new(width, height);
renderer.ctx.flush();
let mut resources = vello_cpu::Resources::default();
renderer.ctx.render_to_pixmap(&mut resources, &mut pix);
Some(pix)
}
/// PdfCraft patch: remaps a solid paint colour through `color_replacement`, if one is
/// set. `Paint::Pattern` (images, shadings, tiling patterns) always passes through
/// untouched.
@@ -1121,6 +1214,20 @@ impl Renderer {
// covers its triangles alone and must not repeat outside them.
let mut extend = peniko::Extend::Repeat;
// PdfCraft patch (21): an ink pass paints tints, and has none for a pattern.
if let Some(pass) = self.ink.pass {
let color = match paint {
Paint::Color(c) => self.ink.paint(pass, c),
Paint::Pattern(_) => {
self.ink.unsupported = true;
AlphaColor::TRANSPARENT
}
};
self.ctx.set_paint_transform(Affine::IDENTITY);
self.ctx.set_paint(color);
return PaintSetup::Clip(None);
}
let paint: PaintType = match paint.clone() {
Paint::Color(c) => {
let c = c.to_rgba().to_rgba8();
@@ -1274,6 +1381,7 @@ impl Renderer {
scaler: self.scaler,
preview: self.preview,
image_transparency_stack: Vec::new(),
ink: InkState::default(),
};
let initial_transform = Affine::translate((BORDER, BORDER))
* Affine::scale_non_uniform(xs as f64, ys as f64)
@@ -1336,6 +1444,7 @@ impl Renderer {
scaler: self.scaler,
preview: self.preview,
image_transparency_stack: Vec::new(),
ink: InkState::default(),
};
let mut initial_transform = Affine::scale_non_uniform(xs, ys)
* Affine::translate((-bbox.x0, -bbox.y0));
@@ -1521,6 +1630,12 @@ impl Renderer {
impl<'a> Device<'a> for Renderer {
fn draw_image(&mut self, image: hayro_interpret::Image<'a, '_>, mut transform: Affine) {
// PdfCraft patch (21): an image's pixels are converted to RGB before they reach the
// device, so an ink pass has no tints for them; the group is drawn as before.
if self.ink.pass.is_some() {
self.ink.unsupported = true;
return;
}
// PdfCraft patch (22): an erase pass paints nothing; an unmasked image's rectangle was
// cleared by `knockout_shape`, and a masked image's shape is left alone.
if self.erasing {
@@ -1634,6 +1749,7 @@ impl<'a> Device<'a> for Renderer {
scaler: self.scaler,
preview: self.preview,
image_transparency_stack: Vec::new(),
ink: InkState::default(),
};
let mut sub_pix = Pixmap::new(width, height);
sub_renderer.ctx.set_transform(transform);
@@ -1697,6 +1813,77 @@ impl<'a> Device<'a> for Renderer {
self.push_clip_path_inner(&clip_path.path, clip_path.fill);
}
/// PdfCraft patch (21), with hayro-interpret patch (45): an isolated group that blends in
/// `DeviceCMYK` (ISO 32000-2 §11.3.4). Its contents are drawn twice on canvases of their own,
/// as cyan-magenta-yellow and as black (see [`InkState`]), and the tints those passes leave
/// are converted to RGB through the CMYK profile solid CMYK colour is drawn with. The
/// result goes into the layer the interpreter pushed for the group, which composites it
/// with the group's opacity, soft mask and blend mode as before. Declined (and so drawn as
/// before) under reading colours, inside a pass (a nested group then blends in the pass's
/// own CMYK), and for contents a pass has no tints for.
fn draw_isolated_cmyk_group(&mut self, group: &hayro_interpret::CmykGroup<'a, '_>) -> bool {
if self.color_replacement.is_some() || self.ink.pass.is_some() {
return false;
}
let canvas = Rect::new(0.0, 0.0, f64::from(self.ctx.width()), f64::from(self.ctx.height()));
let area = group.device_bbox().intersect(canvas);
if !(area.width() > 0.0 && area.height() > 0.0) {
// Nothing of the group is on the canvas (a NaN box lands here too).
return true;
}
let (x0, y0) = (area.x0.floor(), area.y0.floor());
// Within the canvas, so the sides fit its u16 ones.
let width = (area.x1.ceil() - x0) as u16;
let height = (area.y1.ceil() - y0) as u16;
if width == 0 || height == 0 {
return true;
}
if u64::from(width) * u64::from(height) > MAX_CMYK_GROUP_PIXELS {
return false;
}
let Some(cmy) = self.ink_pass(group, InkPass::Cmy, (x0, y0), width, height) else {
return false;
};
let Some(k) = self.ink_pass(group, InkPass::K, (x0, y0), width, height) else {
return false;
};
// A tint is a pass's premultiplied colour un-premultiplied and complemented.
let ink = |premul: u8, alpha: u8| {
if alpha == 0 {
return 0;
}
let straight = (u32::from(premul) * 255 + u32::from(alpha) / 2) / u32::from(alpha);
255 - straight.min(255) as u8
};
let pixels = usize::from(width) * usize::from(height);
let mut tints = Vec::with_capacity(pixels * 4);
for (p, q) in cmy.data().iter().zip(k.data()) {
// Both passes draw the same shapes at the same opacities, so they cover the same
// pixels by the same amounts; each pass's own alpha un-premultiplies its colour.
tints.extend_from_slice(&[ink(p.r, p.a), ink(p.g, p.a), ink(p.b, p.a), ink(q.r, q.a)]);
}
let mut rgb = vec![0u8; pixels * 3];
if hayro_interpret::color::cmyk_to_srgb8(&tints, &mut rgb).is_none() {
return false;
}
let mut result = Pixmap::new(width, height);
for ((px, rgb), coverage) in result.data_mut().iter_mut().zip(rgb.chunks_exact(3)).zip(cmy.data()) {
let a = u32::from(coverage.a);
let premul = |v: u8| ((u32::from(v) * a + 127) / 255) as u8;
*px = PremulRgba8 { r: premul(rgb[0]), g: premul(rgb[1]), b: premul(rgb[2]), a: coverage.a };
}
// The group's own soft mask and blend mode are on its layer; what the contents set
// must not apply to the finished pixels a second time.
self.set_soft_mask(None);
self.set_blend_mode(BlendMode::Normal);
self.draw_pixmap(Arc::new(result), ImageQuality::Low, Affine::translate((x0, y0)));
true
}
fn push_transparency_group(
&mut self,
opacity: f32,
@@ -2026,6 +2213,7 @@ fn draw_soft_mask(mask: &SoftMask<'_>, settings: RenderSettings, width: u16, hei
scaler: Scaler::new(ResamplingFunction::CatmullRom),
preview,
image_transparency_stack: Vec::new(),
ink: InkState::default(),
};
let bg_color = mask.background_color().to_rgba();