mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-09 04:22:20 +00:00
M2: a page past the rasterizer's coverage renders what fitted instead of failing (view.render-error-isolation)
vello_cpu keeps every path's coverage (alpha) values in one buffer until
the scene is rasterized, and a strip packs its index into that buffer in
31 bits; Strip::new asserts it fits. A page that painted one form 2^22
times over (22 nested forms, each drawing the next twice) grew the
buffer past 2^31 values at about 7 GB and panicked, and the page failed.
- vello_common (2): StripStorage::room_for_path{,_within} says whether
one more path's coverage, at most the whole surface counted twice,
still fits below that limit or a smaller one.
- vello_cpu (1): the single-threaded dispatcher leaves out fills,
strokes, fast rectangles and layer clips once there is no room,
records it (RenderContext::coverage_full) and can be kept to fewer
values (set_max_coverage).
- hayro (31): RenderSettings::max_coverage passes that limit down, and
a page whose paths were left out reports
InterpreterWarning::ContentTruncated, which PdfCraft already shows as
content skipped past the page's safety budget.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Pq7HyDBXygTf7jcqdsjcfn
This commit is contained in:
1 parent
dc5cb122db
commit
0e75ad08c8
10 files changed
+220
-6
No files matched your search
@@ -408,6 +408,7 @@ fn render_page<'a>(
|
||||
y_offset: t.y as f32,
|
||||
bg_color,
|
||||
color_replacement,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
None => {
|
||||
|
||||
@@ -8196,6 +8196,9 @@ fn decoded_images_serve_every_size_they_are_drawn_at() {
|
||||
// ICC profiles whose stream dictionaries are the same (vendored hayro-interpret patch 48).
|
||||
mod icc_profile_cache;
|
||||
|
||||
// A page past its rasterizer coverage leaves the rest out and says so (vendored vello_cpu patch 1).
|
||||
mod coverage_budget;
|
||||
|
||||
// A symbolic TrueType font draws through its (3, 0) cmap subtable first (#4156).
|
||||
mod symbolic_truetype_cmap;
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! A page that paints the same content over and over runs out of rasterizer coverage: what is
|
||||
//! past it is left out and said to be, rather than panicking once a strip's alpha index no longer
|
||||
//! fits (PDFBOX-5415's map page drew one form 2^22 times and panicked at 7 GB).
|
||||
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// A page whose form `F0` draws `F1` twice, `F1` draws `F2` twice, and so on `levels` deep; the
|
||||
/// last form fills a circle. The page draws `F0` once, so the circle is filled 2^`levels` times.
|
||||
fn doubling_forms(levels: usize) -> Vec<u8> {
|
||||
let mut objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
// Object 4 is the page's content; forms start at 5.
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Contents 4 0 R /Resources << /XObject << /F0 5 0 R >> >> >>".into(),
|
||||
String::new(),
|
||||
];
|
||||
let content = "/F0 Do";
|
||||
objs[3] = format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len());
|
||||
let circle = "0 0 1 rg 100 160 m 133 160 160 133 160 100 c 160 67 133 40 100 40 c 67 40 40 67 40 100 c 40 133 67 160 100 160 c f";
|
||||
for level in 0..=levels {
|
||||
let (body, resources) = if level == levels {
|
||||
(circle.to_string(), String::new())
|
||||
} else {
|
||||
("/F Do /F Do".to_string(), format!("/Resources << /XObject << /F {} 0 R >> >>", 6 + level))
|
||||
};
|
||||
objs.push(format!("<< /Type /XObject /Subtype /Form /BBox [0 0 200 200] {resources} /Length {} >>\nstream\n{body}\nendstream", body.len()));
|
||||
}
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// Renders page 1 with the rasterizer kept to `max_coverage` values, returning its pixels and
|
||||
/// whether it said content was left out.
|
||||
fn render_kept_to(pdf: Vec<u8>, max_coverage: Option<usize>) -> (Vec<u8>, bool) {
|
||||
let parsed = Pdf::new(Arc::new(pdf)).unwrap();
|
||||
let truncated = Arc::new(Mutex::new(false));
|
||||
let seen = truncated.clone();
|
||||
let settings = InterpreterSettings {
|
||||
warning_sink: Arc::new(move |w| {
|
||||
if matches!(w, InterpreterWarning::ContentTruncated) {
|
||||
*seen.lock().unwrap() = true;
|
||||
}
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let pixmap =
|
||||
hayro::render(&parsed.pages()[0], &RenderCache::new(), &settings, &RenderSettings { bg_color: WHITE, max_coverage, ..Default::default() });
|
||||
let cut = *truncated.lock().unwrap();
|
||||
(pixmap.data_as_u8_slice().to_vec(), cut)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_past_its_coverage_leaves_the_rest_out_and_says_so() {
|
||||
// 2^10 circles, each storing its edge tiles' coverage.
|
||||
let pdf = doubling_forms(10);
|
||||
let (whole, whole_cut) = render_kept_to(pdf.clone(), None);
|
||||
assert!(!whole_cut, "within the limit nothing is left out");
|
||||
let blue = |px: &[u8]| px.as_chunks::<4>().0.iter().filter(|p| p[2] > 200 && p[0] < 50).count();
|
||||
assert!(blue(&whole) > 10_000, "the circle is drawn");
|
||||
|
||||
// Room for a few circles only: the rest are left out, the page still renders, and says so.
|
||||
let (kept, cut) = render_kept_to(pdf, Some(200_000));
|
||||
assert!(cut, "the page says content was left out");
|
||||
assert_eq!(kept.len(), whole.len());
|
||||
assert!(blue(&kept) > 10_000, "the circles drawn before the limit stay: {}", blue(&kept));
|
||||
}
|
||||
@@ -830,8 +830,8 @@ milestone = "M3"
|
||||
status = "shipped"
|
||||
commands = []
|
||||
tools = []
|
||||
evidence = ["crates/render/src/raster/tests.rs::missing_page_and_garbage_input_fail_gracefully", "crates/render/src/raster/tests.rs::scale_is_clamped_for_huge_pages", "crates/render/src/raster/tests.rs::watchdog_skips_a_stuck_page_and_keeps_rendering"]
|
||||
notes = ""
|
||||
evidence = ["crates/render/src/raster/tests.rs::missing_page_and_garbage_input_fail_gracefully", "crates/render/src/raster/tests.rs::scale_is_clamped_for_huge_pages", "crates/render/src/raster/tests.rs::watchdog_skips_a_stuck_page_and_keeps_rendering", "crates/render/src/raster/tests/coverage_budget.rs::a_page_past_its_coverage_leaves_the_rest_out_and_says_so"]
|
||||
notes = "A page that paints more coverage than the rasterizer can index (one form drawn millions of times over) renders what fitted and says content was left out, rather than failing the page."
|
||||
|
||||
[[feature]]
|
||||
id = "view.render-priority"
|
||||
|
||||
Vendored
+3
-2
@@ -40,13 +40,14 @@ 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 (since (21), only inside Type 3 glyphs), 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 image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from 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, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (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 stroLine 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 (since (21), only inside Type 3 glyphs), 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 image that is interpolated (or, since (21), area-averaged) and whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle (halves round up, so a tile snaps an edge where the whole page does) and drawn 1:1 from 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, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (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 stroLine truncated
|
||||
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (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); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (11) `Image::decode_within` spends from what a run of images may still do, starting with its page's pixels, and `charge_reading` charges reading a stream and its globals before anything is parsed, so an operation over a document can bound what `MAX_WORK` bounds for one image, and images that fail or decode nothing add up too: a file of thousands of images made to reach that limit took as many times as long; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change; (13) a bitmap filled with a default pixel of 1 (a page, or an intermediate text or halftone region) had 1s past its width in the last word of each row, and a refinement, which reads its reference a word at a time, read them as pixels where the standard has 0 (6.3.5.2): refining such a reference not a multiple of 32 wide decoded to other pixels than were coded, release builds too. `Bitmap::clear_padding` clears those bits when a bitmap is filled with 1s, as cutting symbols and patterns from a collective bitmap already did. Ghostscript reads the test's page and text streams as they decode now; (14) a region's location is unsigned (5.4.4), so one past `i32::MAX` is off the page, where the decoder took it for a signed one: a region there was drawn back onto the page from the left or the top (at 0xFFFFFFFC, four pixels left of it), and a refinement there, of the page or of a region at the same place (7.4.7.5), was refused as an overflow, and the page with it. `Bitmap::combine_region` keeps such a location past the page. A refinement of another region refines it where it is, as Table 35 has it (GRREFERENCEDX and GRREFERENCEDY 0), whatever the two locations say; a refinement of the page, see (16); (15) a refinement whose reference is offset right of it (GRREFERENCEDX above 0, which a refined text instance has from a wider bitmap, TaLine truncated
|
||||
| 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
|
||||
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, Line truncated
|
||||
| egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::vendor_provenance_egui_wgpu_surface_fit_identity`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::vendor_provenance_egui_wgpu_catch_errors_identity`, which keeps it around `add_surface`'s configure |
|
||||
| vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate |
|
||||
| vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical; (2) `StripStorage::room_for_path{,_within}`: whether one more path's coverage (at most the whole surface, counted twice) still fits below 2^31 values, the most a strip's packed alpha index reaches (`Strip::new` asserts it), or below a smaller limit | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate; (2) `strip_generator::pdfcraft_tests::strips_have_room_until_a_surface_short_of_the_limit` |
|
||||
| vello_cpu | 0.0.8 | Apache-2.0 OR MIT | (1) the single-threaded dispatcher leaves out a fill, stroke, fast rectangle or layer clip once the scene has no room for one more path's coverage (`StripStorage::room_for_path_within`, vello_common patch 2), records it (`RenderContext::coverage_full`, cleared by `reset`) and can be kept to fewer values (`RenderContext::set_max_coverage`, kept across `reset`). Every path's coverage stays in one buffer until the scene is rasterized, so a page that painted one form 2^22 times over (PDFBOX-5415) grew it past 2^31 values at about 7 GB and panicked in `Strip::new` (`alpha_idx` too large); it now renders what fitted. The multi-threaded dispatcher is unchanged (PdfCraft renders single-threaded); the backport of linebender/vello#2000 is recorded under the KenM76 integration patches (#5199) | (1) `raster::tests::coverage_budget::a_page_past_its_coverage_leaves_the_rest_out_and_says_so` renders a page that fills a circle 2^10 times with the rasterizer kept to 200,000 values, and fails without the dispatcher's check; vello_cpu's own tests need upstream assets that are not vendored |
|
||||
| hayro-cmap | 0.1.0 | Apache-2.0 OR MIT | (1) malformed parts of a CMap (bad bfchar/bfrange entries, unresolvable `usecmap`, unparseable tail) are skipped instead of discarding the whole map, so search and redaction find text the edit layer can read (#3177); (2) a binary CMap's `usecmap` counts against the 16-level nesting limit as a text one does, where it passed its own depth and a self-referencing binary CMap recursed until the stack overflowed (from storytold/craft-libs#254) | (1) `hayro-cmap::tests::bad_bfchar_entry_is_skipped`, `unresolvable_usecmap_is_skipped`; (2) `tests::self_referencing_binary_usecmap_stops_at_the_nesting_limit` |
|
||||
| hayro-postscript | 0.1.0 | Apache-2.0 OR MIT | (1) the token scanner's `object::read` skips `<<` and `>>` in a loop; it called itself once per delimiter, so a CMap stream holding a long run of `<` or `>` overflowed the stack and aborted the process (from storytold/craft-libs#263) | (1) `hayro-postscript::object::tests::long_open_dict_run_does_not_overflow`, `long_close_dict_run_does_not_overflow`, `dict_delimiters_are_skipped`, `nested_dict_delimiters_are_skipped` |
|
||||
|
||||
|
||||
Vendored
+14
@@ -157,6 +157,10 @@ pub struct RenderSettings {
|
||||
/// PdfCraft patch: when set, solid text and line-art paint colours are remapped while
|
||||
/// rendering; `None` renders exactly as without the patch.
|
||||
pub color_replacement: Option<ColorReplacement>,
|
||||
/// PdfCraft patch (31): the most coverage values the rasterizer keeps for the page; paths
|
||||
/// past it are left out, with `InterpreterWarning::ContentTruncated`. `None` keeps as many
|
||||
/// as a strip's index reaches (2^31).
|
||||
pub max_coverage: Option<usize>,
|
||||
}
|
||||
|
||||
impl Default for RenderSettings {
|
||||
@@ -170,6 +174,7 @@ impl Default for RenderSettings {
|
||||
x_offset: 0.0,
|
||||
y_offset: 0.0,
|
||||
color_replacement: None,
|
||||
max_coverage: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -254,6 +259,10 @@ pub fn render_into<'a>(
|
||||
interpreter_settings.preview,
|
||||
);
|
||||
|
||||
if let Some(max) = render_settings.max_coverage {
|
||||
device.ctx.set_max_coverage(max);
|
||||
}
|
||||
|
||||
// PdfCraft patch (18): the page renders as one transparency group (the page group). Its
|
||||
// objects composite with an initially transparent backdrop, and the group is then put on
|
||||
// the paper (ISO 32000-2, page group), so a blend mode only blends where something was
|
||||
@@ -284,6 +293,11 @@ pub fn render_into<'a>(
|
||||
}
|
||||
|
||||
interpret_page(page, &mut state, &mut device);
|
||||
// PdfCraft patch (31): what the rasterizer left out once its coverage was full (a page that
|
||||
// paints the same content millions of times over) is content left out, said as such.
|
||||
if device.ctx.coverage_full() {
|
||||
(interpreter_settings.warning_sink)(hayro_interpret::InterpreterWarning::ContentTruncated);
|
||||
}
|
||||
|
||||
if !backdrop_inside {
|
||||
device.pop_transparency_group();
|
||||
|
||||
+55
@@ -69,6 +69,21 @@ impl StripStorage {
|
||||
self.strips.is_empty() && self.alphas.is_empty()
|
||||
}
|
||||
|
||||
/// PdfCraft patch (2): whether these strips have room for the coverage of one more path on a
|
||||
/// `width` x `height` surface, which covers at most the whole surface (twice, to be safe). A
|
||||
/// strip packs its index into the alphas in 31 bits and [`Strip::new`] asserts that it fits:
|
||||
/// a scene that painted past it (a form drawn 2^22 times over) panicked.
|
||||
pub fn room_for_path(&self, width: u16, height: u16) -> bool {
|
||||
self.room_for_path_within(width, height, MAX_ALPHAS)
|
||||
}
|
||||
|
||||
/// [`room_for_path`](Self::room_for_path) with a scene kept to `max_alphas` coverage values
|
||||
/// (never more than a strip's index can reach).
|
||||
pub fn room_for_path_within(&self, width: u16, height: u16, max_alphas: usize) -> bool {
|
||||
let surface = usize::from(width) * usize::from(height);
|
||||
self.alphas.len().saturating_add(surface.saturating_mul(2)) < max_alphas.min(MAX_ALPHAS)
|
||||
}
|
||||
|
||||
/// Extend the current strip storage with the data from another storage.
|
||||
pub fn extend(&mut self, other: &Self) {
|
||||
self.strips.extend(&other.strips);
|
||||
@@ -76,6 +91,10 @@ impl StripStorage {
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (2): the most coverage (alpha) values a strip index can reach (31 bits; the
|
||||
/// top bit of [`Strip`]'s packed index is its fill-gap flag).
|
||||
const MAX_ALPHAS: usize = 1 << 31;
|
||||
|
||||
/// An object for easily generating strips for a filled/stroked path.
|
||||
#[derive(Debug)]
|
||||
pub struct StripGenerator {
|
||||
@@ -439,3 +458,39 @@ mod tests {
|
||||
assert_rect_fast_eq_path(Rect::new(18.0, 18.0, 2.0, 2.0), "inverted_both_axes");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pdfcraft_tests {
|
||||
use super::*;
|
||||
|
||||
/// PdfCraft patch (2): room runs out a whole surface's coverage before the limit, so the path
|
||||
/// that would cross it is never generated; at the real limit, an index of `MAX_ALPHAS` would
|
||||
/// not fit a strip.
|
||||
#[test]
|
||||
fn strips_have_room_until_a_surface_short_of_the_limit() {
|
||||
let mut storage = StripStorage::default();
|
||||
assert!(storage.room_for_path_within(10, 10, 1_000));
|
||||
storage.alphas.resize(799, 0);
|
||||
assert!(
|
||||
storage.room_for_path_within(10, 10, 1_000),
|
||||
"799 + 200 < 1000"
|
||||
);
|
||||
storage.alphas.push(0);
|
||||
assert!(
|
||||
!storage.room_for_path_within(10, 10, 1_000),
|
||||
"800 + 200 reaches the limit"
|
||||
);
|
||||
assert!(
|
||||
storage.room_for_path_within(8192, 8192, usize::MAX),
|
||||
"a large page's surface fits, a larger limit held to a strip's index"
|
||||
);
|
||||
assert!(
|
||||
!storage.room_for_path_within(u16::MAX, u16::MAX, usize::MAX),
|
||||
"the largest surface is counted without overflow, and cannot be promised room"
|
||||
);
|
||||
assert!(
|
||||
Strip::new(0, 0, (MAX_ALPHAS - 1) as u32, true).fill_gap(),
|
||||
"the last index below the limit fits"
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+8
@@ -70,6 +70,14 @@ pub(crate) trait Dispatcher: Debug + Send + Sync {
|
||||
fn pop_layer(&mut self);
|
||||
fn reset(&mut self);
|
||||
fn flush(&mut self, encoded_paints: &[EncodedPaint]);
|
||||
/// PdfCraft patch (1): whether a path was left out of this scene because its coverage was
|
||||
/// full (only the single-threaded dispatcher keeps count).
|
||||
fn coverage_full(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// PdfCraft patch (1): keep the scene to `max` coverage values (never more than a strip's
|
||||
/// index reaches); the single-threaded dispatcher leaves later paths out past it.
|
||||
fn set_max_coverage(&mut self, _max: usize) {}
|
||||
fn rasterize(
|
||||
&self,
|
||||
buffer: &mut [u8],
|
||||
|
||||
+42
-2
@@ -42,6 +42,11 @@ pub(crate) struct SingleThreadedDispatcher {
|
||||
layer_id_next: u32,
|
||||
/// Dependency graph tracking layer relationships and filter effects.
|
||||
render_graph: RenderGraph,
|
||||
/// PdfCraft patch (1): a path was left out because the scene's coverage was full.
|
||||
coverage_full: bool,
|
||||
/// PdfCraft patch (1): the most coverage values the scene keeps
|
||||
/// ([`Dispatcher::set_max_coverage`]).
|
||||
max_coverage: usize,
|
||||
}
|
||||
|
||||
impl SingleThreadedDispatcher {
|
||||
@@ -79,9 +84,25 @@ impl SingleThreadedDispatcher {
|
||||
level,
|
||||
layer_id_next: 0,
|
||||
render_graph,
|
||||
coverage_full: false,
|
||||
max_coverage: usize::MAX,
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (1): whether the scene has room for the coverage of one more path
|
||||
/// ([`StripStorage::room_for_path`]). Once it hasn't, the path and every later one are left
|
||||
/// out, and [`Dispatcher::coverage_full`] says so.
|
||||
fn room_for_path(&mut self) -> bool {
|
||||
let (width, height) = (self.strip_generator.width(), self.strip_generator.height());
|
||||
let room = self
|
||||
.strip_storage
|
||||
.room_for_path_within(width, height, self.max_coverage);
|
||||
if !room {
|
||||
self.coverage_full = true;
|
||||
}
|
||||
room
|
||||
}
|
||||
|
||||
/// Rasterizes the scene using f32 precision (high quality).
|
||||
///
|
||||
/// This dispatches to the appropriate SIMD implementation based on the
|
||||
@@ -539,6 +560,9 @@ impl Dispatcher for SingleThreadedDispatcher {
|
||||
mask: Option<Mask>,
|
||||
encoded_paints: &[EncodedPaint],
|
||||
) {
|
||||
if !self.room_for_path() {
|
||||
return;
|
||||
}
|
||||
let wide = &mut self.wide;
|
||||
|
||||
// Convert path to coverage strips.
|
||||
@@ -573,6 +597,9 @@ impl Dispatcher for SingleThreadedDispatcher {
|
||||
mask: Option<Mask>,
|
||||
encoded_paints: &[EncodedPaint],
|
||||
) {
|
||||
if !self.room_for_path() {
|
||||
return;
|
||||
}
|
||||
let wide = &mut self.wide;
|
||||
|
||||
// Convert stroked path to coverage strips.
|
||||
@@ -604,6 +631,9 @@ impl Dispatcher for SingleThreadedDispatcher {
|
||||
mask: Option<Mask>,
|
||||
encoded_paints: &[EncodedPaint],
|
||||
) {
|
||||
if !self.room_for_path() {
|
||||
return;
|
||||
}
|
||||
let wide = &mut self.wide;
|
||||
|
||||
// Generate strips directly for the rectangle (bypasses path processing).
|
||||
@@ -638,8 +668,9 @@ impl Dispatcher for SingleThreadedDispatcher {
|
||||
// Allocate a new unique layer ID.
|
||||
self.layer_id_next += 1;
|
||||
|
||||
// Generate clip coverage if a clip path is provided.
|
||||
let clip = if let Some(c) = clip_path {
|
||||
// Generate clip coverage if a clip path is provided. PdfCraft patch (1): without room for
|
||||
// it the layer goes unclipped, as nothing can be drawn into it any more either.
|
||||
let clip = if let Some(c) = clip_path.filter(|_| self.room_for_path()) {
|
||||
self.strip_generator.generate_filled_path(
|
||||
c,
|
||||
fill_rule,
|
||||
@@ -681,6 +712,7 @@ impl Dispatcher for SingleThreadedDispatcher {
|
||||
self.strip_storage.clear();
|
||||
self.render_graph.clear();
|
||||
self.layer_id_next = 0;
|
||||
self.coverage_full = false;
|
||||
|
||||
// Recreate root node as node 0 (required for proper execution order).
|
||||
let root_node = self.render_graph.add_node(RenderNodeKind::RootLayer {
|
||||
@@ -697,6 +729,14 @@ impl Dispatcher for SingleThreadedDispatcher {
|
||||
// No-op for single-threaded dispatcher (no work queue to flush).
|
||||
}
|
||||
|
||||
fn coverage_full(&self) -> bool {
|
||||
self.coverage_full
|
||||
}
|
||||
|
||||
fn set_max_coverage(&mut self, max: usize) {
|
||||
self.max_coverage = max;
|
||||
}
|
||||
|
||||
fn rasterize(
|
||||
&self,
|
||||
buffer: &mut [u8],
|
||||
|
||||
Vendored
+14
@@ -583,6 +583,20 @@ impl RenderContext {
|
||||
self.filter = None;
|
||||
}
|
||||
|
||||
/// PdfCraft patch (1): whether paths were left out of the scene because its coverage was
|
||||
/// full (a page that paints the same content millions of times over). Cleared by
|
||||
/// [`reset`](Self::reset).
|
||||
pub fn coverage_full(&self) -> bool {
|
||||
self.dispatcher.coverage_full()
|
||||
}
|
||||
|
||||
/// PdfCraft patch (1): keep the scene to `max` coverage (alpha) values, fewer than the
|
||||
/// 2^31 a strip's index reaches, after which [`coverage_full`](Self::coverage_full) says
|
||||
/// paths were left out. Kept across [`reset`](Self::reset).
|
||||
pub fn set_max_coverage(&mut self, max: usize) {
|
||||
self.dispatcher.set_max_coverage(max);
|
||||
}
|
||||
|
||||
/// Reset the render context.
|
||||
pub fn reset(&mut self) {
|
||||
self.dispatcher.reset();
|
||||
|
||||
Reference in new issue
Block a user