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:
jpeskovandClaude Opus 5.5 authored and KenM76 committed 2026-10-28 18:20:28 -04:00
1 parent dc943eeb13
commit ba09e1aefc
9 files changed
+474 -19

No files matched your search

+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
@@ -39,8 +39,8 @@ Other resource categories retain their existing parent-chain lookup.
| Crate | Version | Licence | Patches | Test |
|---|---|---|---|---|
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.nLine truncated
| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour, planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat); (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of thLine truncated
| hayro-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.nLine truncated
| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour, planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat); (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of thLine truncated
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap, page bitmap, halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176) | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) |
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwLine truncated
+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();