mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-10-31 15:49:36 +00:00
M2: tiling pattern cells sit at their XStep/YStep multiples at every scale (ISO 32000-2 8.7.3.1) (#4421)
The cell pixmap was round(scale x step) pixels and repeated, but the cell was drawn, and the paint transform mapped back, at the unrounded scale. So the pixmap repeated a fraction of a pixel too far at every step (31 px for a 30.56 px step at 110 dpi), and cells drifted further from their place with every step from the pattern's origin. Vendored hayro patch (25), `tiling_cell_pixels`: the cell is drawn at round(scale x step) / step, so one step is exactly the pixmap's side, and the paint transform uses that same scale. The side stays within 1 and the existing 3000 px cap; a non-finite product keeps the scale and a bounded side. Tests: crates/render/tests/it/tiling_cell_placement.rs (fill, turned and scaled matrix, stroke, all at 110 dpi far from the origin; the helper's bounds). Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4047e9aaa5
commit
a08ec799f5
6 files changed
+235
-15
No files matched your search
@@ -6,3 +6,4 @@ mod jbig2_invariants;
|
||||
mod named_form_properties;
|
||||
mod search;
|
||||
mod substitute_widths;
|
||||
mod tiling_cell_placement;
|
||||
@@ -0,0 +1,191 @@
|
||||
//! Tiling pattern cells sit at whole multiples of `/XStep` and `/YStep` in pattern space
|
||||
//! (ISO 32000-2 8.7.3.1, Table 74), at any rendering scale, however far they are from the
|
||||
//! pattern's origin.
|
||||
//!
|
||||
//! Each page is filled (or stroked) with a pattern whose 20 × 20 cell holds one 6 × 6 blue square
|
||||
//! at (7, 7). At 110 dpi a step is 30.56 device pixels; every probe finds the blue square in a
|
||||
//! disc around where the pattern matrix puts it and checks that its centroid is within one
|
||||
//! device pixel of that place.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RequestKind};
|
||||
|
||||
/// The rendering scale for 110 dpi: a step of 20 points is 30.56 pixels, not a whole number.
|
||||
const SCALE: f64 = 110.0 / 72.0;
|
||||
/// The page is `SIDE` × `SIDE` points.
|
||||
const SIDE: f64 = 400.0;
|
||||
|
||||
/// One page `SIDE` points square whose content `content` paints with `/P1`: the 20-point cell
|
||||
/// with its blue square, `/XStep` and `/YStep` 20, under pattern matrix `matrix`.
|
||||
fn page_pdf(content: &str, matrix: [f64; 6]) -> Vec<u8> {
|
||||
let cell = "0 0 1 rg 7 7 6 6 re f";
|
||||
let m = matrix.map(|v| format!("{v}")).join(" ");
|
||||
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 {SIDE} {SIDE}] /Contents 4 0 R /Resources << /Pattern << /P1 5 0 R >> >> >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
5 0 obj << /Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 20 20] /XStep 20 /YStep 20 /Matrix [{m}] /Length {} >> stream
|
||||
{cell}
|
||||
endstream endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len(),
|
||||
cell.len()
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
struct Page {
|
||||
rgba: Vec<u8>,
|
||||
width: usize,
|
||||
height: usize,
|
||||
}
|
||||
|
||||
fn render(content: &str, matrix: [f64; 6]) -> Page {
|
||||
let mut r = PageRenderer::new(Arc::new(page_pdf(content, matrix)), RenderConfig::default());
|
||||
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: SCALE as f32, tag: 0, ..Default::default() });
|
||||
assert!(page.error.is_none(), "{:?}", page.error);
|
||||
Page { rgba: page.rgba.to_vec(), width: page.width as usize, height: page.height as usize }
|
||||
}
|
||||
|
||||
/// The device position of pattern-space point `(x, y)`: the pattern matrix to page space, then
|
||||
/// page space to device pixels (y down).
|
||||
fn device(matrix: [f64; 6], x: f64, y: f64) -> (f64, f64) {
|
||||
let [a, b, c, d, e, f] = matrix;
|
||||
let (px, py) = (a * x + c * y + e, b * x + d * y + f);
|
||||
(px * SCALE, (SIDE - py) * SCALE)
|
||||
}
|
||||
|
||||
/// The centroid of blue (weighted by how far each pixel is from white) in the disc of `radius`
|
||||
/// pixels around `(cx, cy)`, and the total weight. `None` when the disc leaves the page.
|
||||
fn blue_centroid(page: &Page, cx: f64, cy: f64, radius: f64) -> Option<((f64, f64), f64)> {
|
||||
let (x0, x1) = ((cx - radius).floor(), (cx + radius).ceil());
|
||||
let (y0, y1) = ((cy - radius).floor(), (cy + radius).ceil());
|
||||
if x0 < 0.0 || y0 < 0.0 || x1 >= page.width as f64 || y1 >= page.height as f64 {
|
||||
return None;
|
||||
}
|
||||
let (mut sum, mut sx, mut sy) = (0.0, 0.0, 0.0);
|
||||
for j in (y0 as usize)..=(y1 as usize) {
|
||||
for i in (x0 as usize)..=(x1 as usize) {
|
||||
let (px, py) = (i as f64 + 0.5, j as f64 + 0.5);
|
||||
if (px - cx).powi(2) + (py - cy).powi(2) > radius * radius {
|
||||
continue;
|
||||
}
|
||||
let red = *page.rgba.get((j * page.width + i) * 4)?;
|
||||
let w = f64::from(255 - red) / 255.0;
|
||||
sum += w;
|
||||
sx += w * px;
|
||||
sy += w * py;
|
||||
}
|
||||
}
|
||||
(sum > 0.0).then(|| ((sx / sum, sy / sum), sum))
|
||||
}
|
||||
|
||||
/// Checks every cell `(k, m)` whose blue square's centre falls in the page rectangle `area`
|
||||
/// (points: x0, y0, x1, y1): its square is found where the matrix puts it, within one pixel.
|
||||
/// Returns how many cells were checked.
|
||||
fn assert_cells_in_place(page: &Page, matrix: [f64; 6], area: [f64; 4], what: &str) -> usize {
|
||||
let [a, b, c, d, _, _] = matrix;
|
||||
// The square is 6 × 6 at (7, 7); its centre is (10, 10) in the cell. A disc of 6 cell
|
||||
// units around it holds the whole square (half-diagonal 4.24) and no neighbour (7 away).
|
||||
let units = (a * a + b * b).sqrt().min((c * c + d * d).sqrt());
|
||||
let radius = 6.0 * units * SCALE;
|
||||
let area_px = 36.0 * units * units * SCALE * SCALE;
|
||||
let mut checked = 0;
|
||||
for k in -60..60 {
|
||||
for m in -60..60 {
|
||||
let (cx_cell, cy_cell) = (20.0 * f64::from(k) + 10.0, 20.0 * f64::from(m) + 10.0);
|
||||
let [ea, eb, ec, ed, ee, ef] = matrix;
|
||||
let (px, py) = (ea * cx_cell + ec * cy_cell + ee, eb * cx_cell + ed * cy_cell + ef);
|
||||
if px < area[0] || px > area[2] || py < area[1] || py > area[3] {
|
||||
continue;
|
||||
}
|
||||
let (cx, cy) = device(matrix, cx_cell, cy_cell);
|
||||
let Some(((gx, gy), weight)) = blue_centroid(page, cx, cy, radius) else { continue };
|
||||
assert!(weight > 0.8 * area_px, "{what}: cell ({k}, {m}) at ({cx:.1}, {cy:.1}) only partly there: {weight:.1} of {area_px:.1}");
|
||||
assert!(
|
||||
(gx - cx).abs() <= 1.0 && (gy - cy).abs() <= 1.0,
|
||||
"{what}: cell ({k}, {m}) should be centred at ({cx:.2}, {cy:.2}) px, found at ({gx:.2}, {gy:.2})"
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
checked
|
||||
}
|
||||
|
||||
const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// A fill far from the pattern's origin: the cells 300 to 400 points away (15 to 19 steps) are
|
||||
/// where 15 to 19 steps put them, not 0.44 pixel further for every step.
|
||||
#[test]
|
||||
fn far_cells_of_a_fill_sit_at_whole_steps() {
|
||||
let page = render("/Pattern cs /P1 scn 0 0 400 400 re f", IDENTITY);
|
||||
let near = assert_cells_in_place(&page, IDENTITY, [0.0, 0.0, 100.0, 100.0], "near the origin");
|
||||
let far = assert_cells_in_place(&page, IDENTITY, [290.0, 290.0, 400.0, 400.0], "far from the origin");
|
||||
assert!(near >= 16 && far >= 16, "{near} near, {far} far");
|
||||
}
|
||||
|
||||
/// The same under a pattern matrix that scales by 1.49 and turns by 30 degrees: a step is
|
||||
/// 45.5 pixels along each turned axis.
|
||||
#[test]
|
||||
fn far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix() {
|
||||
let (scale, turn) = (1.49_f64, 30_f64.to_radians());
|
||||
let matrix = [scale * turn.cos(), scale * turn.sin(), -scale * turn.sin(), scale * turn.cos(), 3.0, 5.0];
|
||||
let page = render("/Pattern cs /P1 scn 0 0 400 400 re f", matrix);
|
||||
let far = assert_cells_in_place(&page, matrix, [250.0, 250.0, 390.0, 390.0], "turned and scaled");
|
||||
assert!(far >= 6, "{far} cells checked");
|
||||
}
|
||||
|
||||
/// A stroke painted with the pattern: the cells under a wide border far from the origin are
|
||||
/// in place on every side of it.
|
||||
#[test]
|
||||
fn far_cells_of_a_stroke_sit_at_whole_steps() {
|
||||
let page = render("/Pattern CS /P1 SCN 40 w 200 200 180 180 re S", IDENTITY);
|
||||
let mut checked = 0;
|
||||
// The border is 40 points wide around the square from (200, 200) to (380, 380).
|
||||
for band in [[180.0, 180.0, 400.0, 220.0], [180.0, 360.0, 400.0, 400.0], [180.0, 180.0, 220.0, 400.0], [360.0, 180.0, 400.0, 400.0]] {
|
||||
checked += assert_cells_in_place(&page, IDENTITY, band, "stroke");
|
||||
}
|
||||
assert!(checked >= 20, "{checked} cells checked");
|
||||
// Inside the border nothing is painted.
|
||||
let (cx, cy) = device(IDENTITY, 290.0, 290.0);
|
||||
let at = ((cy as usize) * page.width + cx as usize) * 4;
|
||||
assert_eq!(page.rgba.get(at..at + 3), Some(&[255, 255, 255][..]), "inside the stroked square");
|
||||
}
|
||||
|
||||
/// The cell pixmap's side and the scale its cell is drawn at: one step is exactly the side, the
|
||||
/// side stays within 1 and the cap whatever the step, and nothing odd reaches the cast.
|
||||
#[test]
|
||||
fn a_cell_pixmap_spans_exactly_one_step() {
|
||||
// 110 dpi, a step of 20: 30.56 pixels, drawn at 31 / 20.
|
||||
assert_eq!(hayro::tiling_cell_pixels(110.0 / 72.0, 20.0, 3000.0), (31, 31.0 / 20.0));
|
||||
assert_eq!(hayro::tiling_cell_pixels(110.0 / 72.0, -20.0, 3000.0), (31, 31.0 / 20.0), "a negative step");
|
||||
for (scale, step) in [(1.0_f32, 7.3_f32), (2.37, 0.9), (0.013, 1234.5), (3.0, 999.9), (1.0, 2.0e9)] {
|
||||
let (side, drawn) = hayro::tiling_cell_pixels(scale, step, 3000.0);
|
||||
assert!((1..=3000).contains(&side), "{scale} {step}: {side}");
|
||||
let span = drawn * f64::from(step);
|
||||
assert!((span - f64::from(side)).abs() < 1e-9 * f64::from(side), "{scale} {step}: a step spans {span}, not {side}");
|
||||
if f64::from(scale) * f64::from(step) <= 3000.0 {
|
||||
assert!((span - f64::from(scale) * f64::from(step)).abs() <= 0.5 + 1e-9, "{scale} {step}: drawn {drawn}");
|
||||
}
|
||||
}
|
||||
// A step under half a pixel still gets one pixel (a 0 × N pixmap can't be sampled).
|
||||
assert_eq!(hayro::tiling_cell_pixels(0.03, 10.0, 3000.0), (1, 0.1));
|
||||
// Steps and scales that aren't finite and positive: the side is bounded, the scale kept.
|
||||
assert_eq!(hayro::tiling_cell_pixels(2.0, f32::INFINITY, 3000.0), (3000, 2.0));
|
||||
assert_eq!(hayro::tiling_cell_pixels(2.0, 0.0, 3000.0), (1, 2.0));
|
||||
let (side, drawn) = hayro::tiling_cell_pixels(f32::NAN, 20.0, 3000.0);
|
||||
assert!(side == 1 && drawn.is_nan());
|
||||
// A cap past u16::MAX is lowered to it, and the scale follows the side the pixmap gets.
|
||||
let (side, drawn) = hayro::tiling_cell_pixels(2.0, 1.0e6, 1.0e9);
|
||||
assert_eq!(side, u16::MAX, "the cap is at most u16::MAX");
|
||||
assert!((drawn * 1.0e6 - f64::from(u16::MAX)).abs() < 1e-6, "a step spans the side: {drawn}");
|
||||
// A cap that is not a whole number, or not a number, is a whole number of pixels.
|
||||
assert_eq!(hayro::tiling_cell_pixels(1.0, 100.0, 30.7), (30, 0.3));
|
||||
assert_eq!(hayro::tiling_cell_pixels(1.0, 100.0, f32::NAN), (1, 0.01));
|
||||
}
|
||||
@@ -746,8 +746,8 @@ milestone = "M2"
|
||||
status = "partial"
|
||||
commands = []
|
||||
tools = []
|
||||
evidence = ["crates/render/src/raster.rs::self_referencing_tiling_pattern_terminates"]
|
||||
notes = "via hayro bootstrap"
|
||||
evidence = ["crates/render/src/raster.rs::self_referencing_tiling_pattern_terminates", "crates/render/tests/it/tiling_cell_placement.rs::far_cells_of_a_fill_sit_at_whole_steps", "crates/render/tests/it/tiling_cell_placement.rs::far_cells_sit_at_whole_steps_under_a_turned_scaled_matrix", "crates/render/tests/it/tiling_cell_placement.rs::far_cells_of_a_stroke_sit_at_whole_steps"]
|
||||
notes = "via hayro bootstrap. Tiling pattern cells sit at whole multiples of /XStep and /YStep at any zoom, filled or stroked, under any pattern matrix. Missing: a cell is cut at its step, so content reaching past the step into the next cell is lost; a cell pixmap is capped at 3000 pixels a side, so very large steps draw at reduced resolution"
|
||||
|
||||
[[feature]]
|
||||
id = "view.render-transparency"
|
||||
|
||||
Vendored
+1
-1
@@ -18,7 +18,7 @@ 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 | 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
|
||||
|
||||
Vendored
+1
-1
@@ -61,7 +61,7 @@ use vello_cpu::{Level, Pixmap, RenderMode};
|
||||
|
||||
mod renderer;
|
||||
/// PdfCraft patch: exported for its regression test.
|
||||
pub use renderer::{image_resampling_size, tiling_cell_scale, usable_cell_scale};
|
||||
pub use renderer::{image_resampling_size, tiling_cell_pixels, tiling_cell_scale, usable_cell_scale};
|
||||
/// PdfCraft patch: exported for its regression test.
|
||||
#[doc(hidden)]
|
||||
pub use renderer::set_skip_offscreen_paths;
|
||||
|
||||
Vendored
+39
-11
@@ -1302,13 +1302,18 @@ impl Renderer {
|
||||
xs = tiling_cell_scale(xs, t.x_step, MAX_PIXMAP_SIZE);
|
||||
ys = tiling_cell_scale(ys, t.y_step, MAX_PIXMAP_SIZE);
|
||||
|
||||
let x_step = xs * t.x_step;
|
||||
let y_step = ys * t.y_step;
|
||||
// PdfCraft patch (25): the cell pixmap repeats every `pix_width` pixels,
|
||||
// so one step must be exactly that many pixels. The cell is drawn at the
|
||||
// scale that makes it so, and the paint transform below maps the pixmap
|
||||
// back onto pattern space: cells sit at whole multiples of the step at
|
||||
// any device scale. Drawing at the unrounded scale repeated the cell a
|
||||
// fraction of a pixel too early or late, and the error grew with every
|
||||
// step away from the pattern's origin.
|
||||
let (pix_width, xs) = tiling_cell_pixels(xs, t.x_step, MAX_PIXMAP_SIZE);
|
||||
let (pix_height, ys) = tiling_cell_pixels(ys, t.y_step, MAX_PIXMAP_SIZE);
|
||||
|
||||
let scaled_width = bbox.width() as f32 * xs;
|
||||
let scaled_height = bbox.height() as f32 * ys;
|
||||
let pix_width = x_step.abs().round() as u16;
|
||||
let pix_height = y_step.abs().round() as u16;
|
||||
let scaled_width = bbox.width() * xs;
|
||||
let scaled_height = bbox.height() * ys;
|
||||
|
||||
let mut renderer = Self {
|
||||
ctx: RenderContext::new_with(
|
||||
@@ -1332,7 +1337,7 @@ impl Renderer {
|
||||
preview: self.preview,
|
||||
image_transparency_stack: Vec::new(),
|
||||
};
|
||||
let mut initial_transform = Affine::scale_non_uniform(xs as f64, ys as f64)
|
||||
let mut initial_transform = Affine::scale_non_uniform(xs, ys)
|
||||
* Affine::translate((-bbox.x0, -bbox.y0));
|
||||
t.interpret(&mut renderer, initial_transform, is_stroke);
|
||||
let mut pix = Pixmap::new(pix_width, pix_height);
|
||||
@@ -1341,14 +1346,14 @@ impl Renderer {
|
||||
renderer.ctx.render_to_pixmap(&mut resources, &mut pix);
|
||||
|
||||
// TODO: Fix these
|
||||
if x_step < 0.0 {
|
||||
if t.x_step < 0.0 {
|
||||
initial_transform *=
|
||||
Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width as f64, 0.0]);
|
||||
Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width, 0.0]);
|
||||
}
|
||||
|
||||
if y_step < 0.0 {
|
||||
if t.y_step < 0.0 {
|
||||
initial_transform *=
|
||||
Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height as f64]);
|
||||
Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height]);
|
||||
}
|
||||
|
||||
paint_transform =
|
||||
@@ -2186,3 +2191,26 @@ pub fn tiling_cell_scale(scale: f32, step: f32, max_pixels: f32) -> f32 {
|
||||
scale
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (25): the side of a tiling cell pixmap in pixels, and the scale to draw the
|
||||
/// cell at so that one `step` spans exactly that many pixels. The pixmap repeats every whole
|
||||
/// number of pixels; drawing the cell at `scale` itself would repeat it at `round(scale × step)`
|
||||
/// instead of `scale × step`, a fraction of a pixel off at every step (ISO 32000-2 8.7.3.1: cells
|
||||
/// are displaced by multiples of `/XStep` and `/YStep`). The side is kept within 1 and
|
||||
/// `max_pixels` (itself at most `u16::MAX`). When `scale × step` isn't finite and positive,
|
||||
/// `scale` is kept and the side is `max_pixels` for an infinite product, 1 otherwise.
|
||||
pub fn tiling_cell_pixels(scale: f32, step: f32, max_pixels: f32) -> (u16, f64) {
|
||||
// A whole number of pixels; `max` and `min` (not `clamp`, which panics on NaN) make a NaN cap 1.
|
||||
let max = f64::from(max_pixels).floor().max(1.0).min(f64::from(u16::MAX));
|
||||
let (scale, step) = (f64::from(scale), f64::from(step.abs()));
|
||||
let exact = scale * step;
|
||||
if !(exact.is_finite() && exact > 0.0) {
|
||||
let pixels = if exact == f64::INFINITY { max } else { 1.0 };
|
||||
// In 1..=u16::MAX, so the cast is exact.
|
||||
return (pixels as u16, scale);
|
||||
}
|
||||
let pixels = exact.round().max(1.0).min(max);
|
||||
// `pixels` is in 1..=u16::MAX, so the cast is exact; `step` is positive and finite here
|
||||
// (`exact` is), so the division is too.
|
||||
(pixels as u16, pixels / step)
|
||||
}
|
||||
Reference in new issue
Block a user