mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-10 13:01:29 +00:00
M2: degenerate subpaths, all-zero dash arrays and negative line widths stroke as ISO 32000-2 8.5.3.2 / 8.4.3 say
Vendored hayro-interpret patch 61. - A degenerate subpath (a single-point closed path, or points that all coincide) is stroked as a dot of the line width with round caps and not at all with butt or projecting square caps (8.5.3.2). The zero-length `l` is no longer nudged a ten-thousandth of a point (which gave square caps a direction to draw a square in), and `x y m h` keeps its `h` (kurbo's `is_empty` counts only segments, so it was dropped and the subpath painted nothing). Other subpaths and zero-length dashes are untouched. - A dash array that is all zero, or has a negative or non-finite entry, is kept as `[]`, a solid line (8.4.3.6). `[0 0]` used to become `[0.01 0.01]`, a faint half-covered line. - A negative or non-finite line width from `w` or `/LW` is kept as 0, the thinnest line (8.4.3.2), so no device sees a width below zero. The renderer already drew it as a one-pixel line in the stroke colour. Tests: crates/render/tests/it/stroke_geometry.rs (pixel checks and a recording device). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC
This commit is contained in:
1 parent
3517d05b47
commit
e5051ca139
7 files changed
+400
-23
No files matched your search
@@ -12,6 +12,7 @@ mod search;
|
||||
mod separation_all;
|
||||
mod stray_q_in_a_form;
|
||||
mod stroke_degenerate_cubic;
|
||||
mod stroke_geometry;
|
||||
mod substitute_widths;
|
||||
mod tiling_cell_placement;
|
||||
mod type3_text_clip;
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Stroke geometry the renderer gets from the graphics state: degenerate subpaths and their line
|
||||
//! caps (ISO 32000-2 §8.5.3.2), dash arrays that are all zero or otherwise invalid (§8.4.3.6) and
|
||||
//! line widths below zero (§8.4.3.2). Vendored hayro-interpret patch 61.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use hayro::hayro_interpret::font::Glyph;
|
||||
use hayro::hayro_interpret::hayro_syntax::Pdf;
|
||||
use hayro::hayro_interpret::{
|
||||
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, StrokeProps,
|
||||
TransformExt, interpret_page,
|
||||
};
|
||||
use kurbo::{Affine, BezPath, Rect};
|
||||
use pdfcraft_render::{PageRenderer, RenderConfig, RenderRequest, RenderedPage, RequestKind};
|
||||
|
||||
const WHITE: [u8; 4] = [255, 255, 255, 255];
|
||||
const BLUE: [u8; 4] = [0, 0, 255, 255];
|
||||
|
||||
/// Renders `content` on a 40 × 40 pt page at 1 px per pt, with `gs1` as the ExtGState `/GS1`.
|
||||
fn render(content: &str, gs1: &str) -> RenderedPage {
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /ExtGState << /GS1 {gs1} >> >> >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len()
|
||||
);
|
||||
let mut r = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default());
|
||||
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, ..Default::default() });
|
||||
assert!(page.error.is_none(), "{:?}", page.error);
|
||||
assert_eq!((page.width, page.height), (40, 40));
|
||||
page
|
||||
}
|
||||
|
||||
/// The pixel at device (x, y), y down.
|
||||
fn px(page: &RenderedPage, x: usize, y: usize) -> [u8; 4] {
|
||||
let i = (y * 40 + x) * 4;
|
||||
let mut out = [0; 4];
|
||||
out.copy_from_slice(&page.rgba[i..i + 4]);
|
||||
out
|
||||
}
|
||||
|
||||
/// How many pixels are not white.
|
||||
fn inked(page: &RenderedPage) -> usize {
|
||||
page.rgba.as_chunks::<4>().0.iter().filter(|p| **p != WHITE).count()
|
||||
}
|
||||
|
||||
/// §8.5.3.2: a degenerate subpath (a single-point closed path, or points that all coincide) is
|
||||
/// painted as a filled circle of the line width when the caps are round, and not at all with butt
|
||||
/// or projecting square caps. User-space point (20, 20) is device pixel (20, 20); a 10 pt round
|
||||
/// dot covers (20 ± 4, 20) and (20, 20 ± 4) but not the square's corner (24, 24).
|
||||
#[test]
|
||||
fn degenerate_subpaths_draw_a_round_dot_or_nothing() {
|
||||
let round = [
|
||||
("m l to the same point", "0 0 1 RG 10 w 1 J 20 20 m 20 20 l S"),
|
||||
("m h, a single-point closed path", "0 0 1 RG 10 w 1 J 20 20 m h S"),
|
||||
("m h by s", "0 0 1 RG 10 w 1 J 20 20 m s"),
|
||||
("m c with every point the same", "0 0 1 RG 10 w 1 J 20 20 m 20 20 20 20 20 20 c S"),
|
||||
("m l l h at one point", "0 0 1 RG 10 w 1 J 20 20 m 20 20 l 20 20 l h S"),
|
||||
("a 0 × 0 re", "0 0 1 RG 10 w 1 J 20 20 0 0 re S"),
|
||||
];
|
||||
for (what, content) in round {
|
||||
let page = render(content, "<< >>");
|
||||
for (x, y) in [(20, 20), (16, 20), (23, 20), (20, 16), (20, 23)] {
|
||||
assert_eq!(px(&page, x, y), BLUE, "{what}, round caps: ({x}, {y}) is inside the dot");
|
||||
}
|
||||
assert_eq!(px(&page, 24, 24), WHITE, "{what}, round caps: the dot is round, not square");
|
||||
assert_eq!(px(&page, 27, 20), WHITE, "{what}, round caps: the dot is the line width across");
|
||||
}
|
||||
for cap in ["0 J", "2 J"] {
|
||||
for (what, content) in round {
|
||||
let content = content.replace("1 J", cap);
|
||||
assert_eq!(inked(&render(&content, "<< >>")), 0, "{what} with {cap}: nothing is painted");
|
||||
}
|
||||
}
|
||||
// A single-point open subpath (a trailing m) paints nothing whatever the cap.
|
||||
assert_eq!(inked(&render("0 0 1 RG 10 w 1 J 20 20 m S", "<< >>")), 0, "a lone m");
|
||||
}
|
||||
|
||||
/// Only the degenerate subpaths of a path change: the line drawn with them keeps its caps, and a
|
||||
/// line whose ends differ by a hair is not degenerate.
|
||||
#[test]
|
||||
fn degenerate_subpaths_leave_the_rest_of_the_path_alone() {
|
||||
// Projecting square caps: the line from x 10 to 30 at y 10 reaches x 7 and x 33; the
|
||||
// degenerate subpath at (20, 30) is dropped.
|
||||
let page = render("0 0 1 RG 6 w 2 J 10 30 m 30 30 l 20 10 m h S", "<< >>");
|
||||
for x in [8, 20, 32] {
|
||||
assert_eq!(px(&page, x, 10), BLUE, "({x}, 10) on the line with its square caps");
|
||||
}
|
||||
assert_eq!(px(&page, 20, 30), WHITE, "the degenerate subpath is dropped");
|
||||
// Round caps: the degenerate subpath becomes a dot beside the line.
|
||||
let page = render("0 0 1 RG 6 w 1 J 10 30 m 30 30 l 20 10 m h S", "<< >>");
|
||||
assert_eq!(px(&page, 20, 10), BLUE, "the line");
|
||||
assert_eq!(px(&page, 20, 30), BLUE, "the dot");
|
||||
// `b` (close, fill and stroke) of a single point strokes the dot too.
|
||||
let page = render("0 0 1 RG 1 0 0 rg 6 w 1 J 20 20 m b", "<< >>");
|
||||
assert_eq!(px(&page, 20, 20), BLUE, "b of one point strokes a round dot");
|
||||
// A curve back to its start through other control points is a loop, not a point.
|
||||
let page = render("0 0 1 RG 2 w 2 J 20 10 m 35 35 5 35 20 10 c S", "<< >>");
|
||||
assert!(inked(&page) > 20, "a curve that returns to its start is stroked");
|
||||
// A hairline dot is still drawn, about a device pixel across.
|
||||
let page = render("0 0 1 RG 0 w 1 J 20 20 m h S", "<< >>");
|
||||
assert!((1..=9).contains(&inked(&page)), "a 0 w round dot: {} pixels", inked(&page));
|
||||
// Not degenerate: the ends differ, so the square caps are drawn along the hairline segment.
|
||||
let page = render("0 0 1 RG 10 w 2 J 20 20 m 20.01 20 l S", "<< >>");
|
||||
assert_eq!(px(&page, 20, 20), BLUE, "a segment a hundredth of a point long is stroked with its caps");
|
||||
}
|
||||
|
||||
/// §8.4.3.6 asks for dash numbers that are nonnegative and not all zero, but not how to recover
|
||||
/// from others. They draw a solid line, as an empty dash array does; before, `[0 0]` was cut into
|
||||
/// hundredth-of-a-point dashes and came out a faint, half-covered line.
|
||||
#[test]
|
||||
fn all_zero_dash_arrays_draw_a_solid_line() {
|
||||
for (what, content, gs1) in [
|
||||
("[0 0]", "0 0 1 RG 4 w [0 0] 0 d 10 20 m 30 20 l S", "<< >>"),
|
||||
("[0]", "0 0 1 RG 4 w [0] 0 d 10 20 m 30 20 l S", "<< >>"),
|
||||
("[0 0 0] with a phase", "0 0 1 RG 4 w [0 0 0] 3 d 10 20 m 30 20 l S", "<< >>"),
|
||||
("[0 0] from an ExtGState", "0 0 1 RG 4 w /GS1 gs 10 20 m 30 20 l S", "<< /D [[0 0] 0] >>"),
|
||||
("[0 -1], negative", "0 0 1 RG 4 w [0 -1] 0 d 10 20 m 30 20 l S", "<< >>"),
|
||||
("[3 -1] from an ExtGState", "0 0 1 RG 4 w /GS1 gs 10 20 m 30 20 l S", "<< /D [[3 -1] 0] >>"),
|
||||
] {
|
||||
let page = render(content, gs1);
|
||||
for x in 11..30 {
|
||||
assert_eq!(px(&page, x, 20), BLUE, "{what}: ({x}, 20) is solid and opaque");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Patterns that are valid keep their dashes: `[0 12]` with round caps is a row of dots, `[4 4]`
|
||||
/// leaves gaps, an odd `[4]` repeats as `[4 4]`.
|
||||
#[test]
|
||||
fn valid_dash_patterns_still_dash() {
|
||||
let page = render("0 0 1 RG 4 w 1 J [0 12] 0 d 4 20 m 36 20 l S", "<< >>");
|
||||
for x in [4, 16, 28] {
|
||||
assert_eq!(px(&page, x, 20), BLUE, "[0 12] round caps: a dot at x {x}");
|
||||
}
|
||||
for x in [10, 22, 34] {
|
||||
assert_eq!(px(&page, x, 20), WHITE, "[0 12] round caps: a gap at x {x}");
|
||||
}
|
||||
for (what, content) in [("[4 4]", "0 0 1 RG 4 w [4 4] 0 d 0 20 m 40 20 l S"), ("[4]", "0 0 1 RG 4 w [4] 0 d 0 20 m 40 20 l S")] {
|
||||
let page = render(content, "<< >>");
|
||||
assert_eq!(px(&page, 2, 20), BLUE, "{what}: the first dash");
|
||||
assert_eq!(px(&page, 6, 20), WHITE, "{what}: the first gap");
|
||||
assert_eq!(px(&page, 10, 20), BLUE, "{what}: the second dash");
|
||||
}
|
||||
}
|
||||
|
||||
/// The stroke properties and paints every `draw_path` of `content` reaches a device with.
|
||||
fn strokes(content: &str, gs1: &str) -> Vec<(StrokeProps, Paint<'static>)> {
|
||||
#[derive(Default)]
|
||||
struct Strokes(Vec<(StrokeProps, Paint<'static>)>);
|
||||
impl<'a> Device<'a> for Strokes {
|
||||
fn set_soft_mask(&mut self, _: Option<SoftMask<'a>>) {}
|
||||
fn set_blend_mode(&mut self, _: BlendMode) {}
|
||||
fn draw_path(&mut self, _: &BezPath, _: Affine, paint: &Paint<'a>, mode: &PathDrawMode) {
|
||||
if let (PathDrawMode::Stroke(props), Paint::Color(colour)) = (mode, paint) {
|
||||
self.0.push((props.clone(), Paint::Color(colour.clone())));
|
||||
}
|
||||
}
|
||||
fn push_clip_path(&mut self, _: &ClipPath) {}
|
||||
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
|
||||
fn draw_glyph(&mut self, _: &Glyph<'a>, _: Affine, _: Affine, _: &Paint<'a>, _: &GlyphDrawMode) {}
|
||||
fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {}
|
||||
fn pop_clip_path(&mut self) {}
|
||||
fn pop_transparency_group(&mut self) {}
|
||||
}
|
||||
let pdf = format!(
|
||||
"%PDF-1.7
|
||||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||||
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||||
3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << /ExtGState << /GS1 {gs1} >> >> >> endobj
|
||||
4 0 obj << /Length {} >> stream
|
||||
{content}
|
||||
endstream endobj
|
||||
trailer << /Root 1 0 R >>
|
||||
%%EOF",
|
||||
content.len()
|
||||
);
|
||||
let parsed = Pdf::new(Arc::new(pdf.into_bytes())).expect("parses");
|
||||
let page = &parsed.pages()[0];
|
||||
let cache = InterpreterCache::new();
|
||||
let mut ctx =
|
||||
Context::new(page.initial_transform(true).to_kurbo(), Rect::new(0.0, 0.0, 40.0, 40.0), &cache, page.xref(), InterpreterSettings::default());
|
||||
let mut device = Strokes::default();
|
||||
interpret_page(page, &mut ctx, &mut device);
|
||||
device.0
|
||||
}
|
||||
|
||||
/// §8.4.3.2: a line width of 0 is the thinnest line the device can draw. A negative or
|
||||
/// non-finite one is invalid and kept as 0, so no device sees a width below zero; the stroke
|
||||
/// keeps the current stroke colour.
|
||||
#[test]
|
||||
fn negative_line_widths_reach_a_device_as_zero() {
|
||||
for (what, content, gs1, width) in [
|
||||
("-6 w", "0 0 1 RG -6 w 10 20 m 30 20 l S", "<< >>", 0.0),
|
||||
("/LW -6", "0 0 1 RG /GS1 gs 10 20 m 30 20 l S", "<< /LW -6 >>", 0.0),
|
||||
("/LW 1e40, beyond f32", "0 0 1 RG /GS1 gs 10 20 m 30 20 l S", "<< /LW 10000000000000000000000000000000000000000 >>", 0.0),
|
||||
("2.5 w", "0 0 1 RG 2.5 w 10 20 m 30 20 l S", "<< >>", 2.5),
|
||||
("0 w", "0 0 1 RG 0 w 10 20 m 30 20 l S", "<< >>", 0.0),
|
||||
] {
|
||||
let seen = strokes(content, gs1);
|
||||
assert_eq!(seen.len(), 1, "{what}: one stroke");
|
||||
let (props, paint) = &seen[0];
|
||||
assert_eq!(props.line_width, width, "{what}: line width");
|
||||
let Paint::Color(colour) = paint else { unreachable!() };
|
||||
assert_eq!(colour.to_rgba().to_rgba8(), [0, 0, 255, 255], "{what}: the stroke colour");
|
||||
}
|
||||
}
|
||||
|
||||
/// The dash array a device is given: `[]` (solid) for one that is all zero or has a negative or
|
||||
/// non-finite entry, from `d` or from `/D`; a valid one keeps its entries, a zero entry turned
|
||||
/// into a hundredth of a point, as before.
|
||||
#[test]
|
||||
fn invalid_dash_arrays_reach_a_device_as_solid() {
|
||||
let line = "10 20 m 30 20 l S";
|
||||
for (what, setup, gs1, dashes) in [
|
||||
("[0 0]", "[0 0] 0 d", "<< >>", &[][..]),
|
||||
("[0]", "[0] 0 d", "<< >>", &[]),
|
||||
("[0 0 0] with a phase", "[0 0 0] 4 d", "<< >>", &[]),
|
||||
("/D [[0 0] 0]", "/GS1 gs", "<< /D [[0 0] 0] >>", &[]),
|
||||
("[3 -1]", "[3 -1] 0 d", "<< >>", &[]),
|
||||
("/D [[0 -1] 0]", "/GS1 gs", "<< /D [[0 -1] 0] >>", &[]),
|
||||
("[3 1e40], beyond f32", "[3 10000000000000000000000000000000000000000] 0 d", "<< >>", &[]),
|
||||
("[]", "[] 0 d", "<< >>", &[]),
|
||||
("[0 12]", "[0 12] 0 d", "<< >>", &[0.01, 12.0]),
|
||||
("/D [[0 12] 0]", "/GS1 gs", "<< /D [[0 12] 0] >>", &[0.01, 12.0]),
|
||||
("[20 10]", "[20 10] 5 d", "<< >>", &[20.0, 10.0]),
|
||||
("[10]", "[10] 0 d", "<< >>", &[10.0]),
|
||||
] {
|
||||
let seen = strokes(&format!("{setup} {line}"), gs1);
|
||||
assert_eq!(seen.len(), 1, "{what}: one stroke");
|
||||
assert_eq!(seen[0].0.dash_array.as_slice(), dashes, "{what}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The renderer already drew a negative width as its thinnest line (it widens anything under a
|
||||
/// device pixel); that stays so, in the stroke colour.
|
||||
#[test]
|
||||
fn negative_line_widths_draw_the_thinnest_line_in_the_stroke_colour() {
|
||||
for (what, content, gs1, reference) in [
|
||||
("-6 w", "0 0 1 RG -6 w 10 20 m 30 20 l S", "<< >>", "0 0 1 RG 0 w 10 20 m 30 20 l S"),
|
||||
("/LW -6", "0 0 1 RG /GS1 gs 10 20 m 30 20 l S", "<< /LW -6 >>", "0 0 1 RG 0 w 10 20 m 30 20 l S"),
|
||||
("-6 w with round caps", "0 0 1 RG 1 J -6 w 10 20 m 30 20 l S", "<< >>", "0 0 1 RG 1 J 0 w 10 20 m 30 20 l S"),
|
||||
] {
|
||||
let hairline = render(reference, "<< >>");
|
||||
let page = render(content, gs1);
|
||||
assert!(page.rgba[..] == hairline.rgba[..], "{what}: drawn as 0 w");
|
||||
let ink: Vec<[u8; 4]> = page.rgba.as_chunks::<4>().0.iter().filter(|p| **p != WHITE).copied().collect();
|
||||
assert!(!ink.is_empty(), "{what}: the line is drawn");
|
||||
assert!(ink.iter().all(|p| p[2] == 255 && p[0] == p[1]), "{what}: every inked pixel is a tint of the blue stroke colour: {ink:?}");
|
||||
assert!(ink.len() <= 2 * 22, "{what}: about one pixel thick, {} pixels inked", ink.len());
|
||||
}
|
||||
}
|
||||
Vendored
+1
-1
@@ -39,7 +39,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-interpret | 0.7.0 | Apache-2.0 OR MIT | (1) select `/AP /N` appearance states via `/AS` (checkboxes, radios, stateful icons) and honour the NoView flag; (2) Type3 Unicode fallback to `/Encoding` glyph names, then printable ASCII; (3) `Type3Glyph::advance_width`; (4) `InterpreterSettings::ocg_overrides` for viewer layer toggles; (5) soft masks whose group lacks `/CS` were dropped (Chrome gradient text); (6) paint nesting cap `MAX_PAINT_NESTING` for tiling patterns and Type 3 glyphs (self-referencing content overflowed the stack); (7) CID width ranges in `/W` and `/W2` clamped to `MAX_CID` (a `0 4294967295 w` range hung); (8) `InterpreterSettings::hide_comments` skips markup annotations but keeps widgets and links (View ▸ Hide all comments); (9) `image_size_ok`: images and masks over 2^28 pixels are not decoded (a fuzzed `/W 4294967295` stencil mask allocated 4 GiB); (10) `MAX_NESTED_PAINTS`: nested paints (forms, Type 3 glyphs and tiling patterns inside one another) share a per-page budget of 50,000 (a glyph showing eight glyphs of its own font, sixteen deep, hung); (11) depends on skrifa 0.47 instead of 0.42 (upstream read-fonts fixed a Type 1 tokenizer that recursed through runs of numbers: a fuzzed font hung or overflowed the stack), with the one API change (`Charset::glyph_id` returns `Option`); (12) annotation appearances whose `/BBox` or `/Matrix` collapses to a line or a point are skipped (mapping them onto `/Rect` divided by zero and handed the device infinite or NaN matrices); (13) a Highlight annotation without a usable normal appearance is drawn from its `/QuadPoints`, `/C` and `/CA` with Multiply blending, as pdfcraft-annot draws highlights (it was not drawn at all); (14) simple-font `/Widths` (`read_widths`): entries only for codes 0–255 (one entry per code below `/FirstChar` was allocated: `4294967295` asked for 34 GB), an entry that isn't a number leaves its code missing instead of ending the array, and a `/LastChar` below `/FirstChar` gives no widths instead of discarding the font for a standard one; (15) the appearance box is mapped onto `/Rect` corner to corner: the translation now accounts for the scale (an appearance whose box didn't start at the origin and differed in size from `/Rect` was drawn shifted); (16) a clip set by `W`/`W*` takes effect after whichever path-painting operator ends the path (`S`, `f`, `B`, … as well as `n`; ISO 32000-2 §8.5.4): it was applied only on `n`, so `re W* S` clipped nothing and the clip stayed pending for a later, unrelated `n`; (17) `InterpreterSettings::cancelled`: once set, interpretation stops before the next content operator (a render pool sets it for every worker when dropped, after an edit or on closing, and for one worker when the watchdog gives up on its render, so renders whose answers nobody can receive stop instead of running to the end); (18) `MAX_PAGE_CONTENT`: the content a page holds at once (its contents, and the forms, tiling patterns and Type 3 glyph procedures being painted) stays within 512 MiB (`decode_content`; once it runs out, `InterpreterWarning::ContentTruncated` is reported (once per page by pdfcraft-render) so a truncated page is not a clean render; each level gives its bytes back when it finishes): forms nest fifty deep and each level kept its content while the next ran, so a form painting itself around a stream inflating to 256 MiB would have held over 12 GB; and Type 0 sampled functions take at most `MAX_SAMPLE_ENTRIES` (2^21) table points and `MAX_SAMPLE_VALUES` (2^23) samples, read no further than `/Size` asks (256 MiB of 1-bit samples asked for over 8 GB); (19) mesh shadings (types 4–7) are sampled only inside the area being drawn (`ShadingPattern::encode_within`, which the vendored hayro renderer calls with that area plus a pixel), within 8 visits per pixel of it plus 4 per triangle (`TriangleSampler`), and patches are triangulated one at a time: points far off the page were sampled over their whole bounding box, up to 65536 × 65536 entries (a fuzzed 147-byte patch stream; a synthetic page passed 6 GB in six seconds), ten thousand overlapping triangles ran for minutes, and every patch became 722 triangles before any limit; meshes hold at most `MAX_MESH_PATCHES` (2^16) patches and `MAX_MESH_TRIANGLES` (2^20) triangles, a lattice needs two to 2^19 vertices per row (`/VerticesPerRow 0` pushed empty rows for ever; one huge row read the whole stream), and a page samples at most `MAX_PAGE_MESH_TRIANGLES` (2^25) mesh triangles in all (a mesh painted a thousand times was triangulated a thousand times); each cut logs a warning; (20) PDF function construction is limited to 64 levels and 10,000 total nodes with cycle detection; calculator parsing and evaluation share procedure depth/work budgets, integer division/bitshift/rotation/index are panic-free, and fixed-size stack errors propagate; (21) a Type 0 font drawn with a substitute that isn't CID-keyed (it isn't embedded, or its program doesn't load) draws `.nLine truncated
|
||||
| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour, planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk, interpolated, axis-aligned image is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 at the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat); (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#2128): vello_cpu 0.0.8 copies an opaque gradient over fully covered tiles without the mask or blend mode, so PowerPoint's faded gradient fills came out solid; (17) the renderer keeps annotation paints out of the reading-colours mapping between `begin_annotations` and `end_annotations` (#1548); (18) the page renders as one transparency group; under reading colours its background is painted inside it as the initial backdrop, so a Multiply highlight blends with the dark background instead of staying an opaque block, and otherwise the background stays outside, so a blend mode over an empty part of thLine truncated
|
||||
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap, page bitmap, halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176) | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) |
|
||||
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
|
||||
|
||||
+30
@@ -28,3 +28,33 @@ pub(crate) fn convert_line_join(lc: LineJoin) -> kurbo::Join {
|
||||
_ => kurbo::Join::Miter,
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (61): the line width to keep for a `w` operand or an ExtGState `/LW`. ISO
|
||||
/// 32000-2 §8.4.3.2 makes 0 "the thinnest line that can be rendered at device resolution" but
|
||||
/// says nothing of a negative width; it is drawn as 0, as is one that isn't finite, so no device
|
||||
/// sees a width below zero.
|
||||
pub(crate) fn convert_line_width(width: f32) -> f32 {
|
||||
if width.is_finite() && width > 0.0 {
|
||||
width
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (61): the dash array to keep for a `d` operator or an ExtGState `/D`. ISO
|
||||
/// 32000-2 §8.4.3.6 requires numbers that "shall be nonnegative and not all zero". A pattern that
|
||||
/// breaks that (all zero, a negative or a non-finite entry) is kept as `[]`, a solid line, rather
|
||||
/// than cut into dashes the zero-entry workaround below would make a hundredth of a point long.
|
||||
pub(crate) fn convert_dash_array(
|
||||
dashes: impl Iterator<Item = f32>,
|
||||
) -> smallvec::SmallVec<[f32; 4]> {
|
||||
let dashes: smallvec::SmallVec<[f32; 4]> = dashes.collect();
|
||||
if dashes.iter().any(|d| !d.is_finite() || *d < 0.0) || dashes.iter().all(|d| *d == 0.0) {
|
||||
return smallvec::SmallVec::new();
|
||||
}
|
||||
// kurbo apparently cannot properly deal with dashes that are exactly 0.
|
||||
dashes
|
||||
.into_iter()
|
||||
.map(|d| if d == 0.0 { 0.01 } else { d })
|
||||
.collect()
|
||||
}
|
||||
+11
-12
@@ -1,7 +1,7 @@
|
||||
use crate::{BlendMode, FillRule};
|
||||
use crate::color::{ColorSpace, DefaultColorSpaces, DeviceFamily};
|
||||
use crate::context::Context;
|
||||
use crate::convert::{convert_line_cap, convert_line_join};
|
||||
use crate::convert::{convert_dash_array, convert_line_cap, convert_line_join, convert_line_width};
|
||||
use crate::device::Device;
|
||||
use crate::font::{Font, FontData, FontQuery, StandardFont};
|
||||
use crate::interpret::path::{
|
||||
@@ -487,7 +487,9 @@ fn interpret_window<'a>(
|
||||
context.get_mut().graphics_state.stroke_pattern = None;
|
||||
}
|
||||
TypedInstruction::LineWidth(w) => {
|
||||
context.get_mut().graphics_state.stroke_props.line_width = w.0.as_f32();
|
||||
// PdfCraft patch (61): see `convert_line_width`.
|
||||
context.get_mut().graphics_state.stroke_props.line_width =
|
||||
convert_line_width(w.0.as_f32());
|
||||
}
|
||||
TypedInstruction::LineCap(c) => {
|
||||
context.get_mut().graphics_state.stroke_props.line_cap = convert_line_cap(c);
|
||||
@@ -566,13 +568,12 @@ fn interpret_window<'a>(
|
||||
}
|
||||
TypedInstruction::LineTo(m) => {
|
||||
if !context.path().elements().is_empty() {
|
||||
let last_point = *context.last_point();
|
||||
let mut p = Point::new(m.0.as_f64(), m.1.as_f64());
|
||||
// PdfCraft patch (61): a segment to the point it starts from is kept as it
|
||||
// is. Upstream nudged its end a ten-thousandth of a point to the right so
|
||||
// round caps drew a dot, which also gave butt and square caps a direction
|
||||
// to draw in; `stroke_path_impl` now handles degenerate subpaths.
|
||||
let p = Point::new(m.0.as_f64(), m.1.as_f64());
|
||||
*(context.last_point_mut()) = p;
|
||||
if last_point == p {
|
||||
// Add a small delta so that zero width lines can still have a round stroke.
|
||||
p.x += 0.0001;
|
||||
}
|
||||
|
||||
context.path_mut().line_to(p);
|
||||
}
|
||||
@@ -681,11 +682,9 @@ fn interpret_window<'a>(
|
||||
}
|
||||
TypedInstruction::DashPattern(p) => {
|
||||
context.get_mut().graphics_state.stroke_props.dash_offset = p.1.as_f32();
|
||||
// kurbo apparently cannot properly deal with offsets that are exactly 0.
|
||||
// PdfCraft patch (61): see `convert_dash_array`.
|
||||
context.get_mut().graphics_state.stroke_props.dash_array =
|
||||
p.0.iter::<f32>()
|
||||
.map(|n| if n == 0.0 { 0.01 } else { n })
|
||||
.collect();
|
||||
convert_dash_array(p.0.iter::<f32>());
|
||||
}
|
||||
TypedInstruction::RenderingIntent(_) => {
|
||||
// Ignore for now.
|
||||
|
||||
+90
-3
@@ -3,8 +3,9 @@ use crate::context::{Context, path_as_rect};
|
||||
use crate::device::Device;
|
||||
use crate::util::{BezPathExt, Float32Ext};
|
||||
use crate::{FillRule, Paint, PathDrawMode, StrokeProps};
|
||||
use kurbo::{BezPath, Cap, Join, PathEl};
|
||||
use kurbo::{BezPath, Cap, Join, PathEl, Point};
|
||||
use smallvec::smallvec;
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub(crate) fn fill_path<'a>(
|
||||
context: &mut Context<'a>,
|
||||
@@ -52,7 +53,14 @@ pub(crate) fn close_path(context: &mut Context<'_>) {
|
||||
// This is necessary to prevent artifacts (see for example issue 157),
|
||||
// but it does cause some weird lines (maybe conflation artifacts) in
|
||||
// pdftc_900k_0907.
|
||||
if context.path().elements().last() != Some(&PathEl::ClosePath) && !context.path().is_empty() {
|
||||
//
|
||||
// PdfCraft patch (61): a path that is a single `m` is closed too. kurbo's `is_empty` counts
|
||||
// only segments, so upstream dropped the `h` of `x y m h`, and the single-point closed
|
||||
// subpath a round cap paints as a dot (ISO 32000-2 §8.5.3.2) became a trailing `m`, which
|
||||
// paints nothing.
|
||||
if context.path().elements().last() != Some(&PathEl::ClosePath)
|
||||
&& !context.path().elements().is_empty()
|
||||
{
|
||||
context.path_mut().close_path();
|
||||
|
||||
*(context.last_point_mut()) = *context.sub_path_start();
|
||||
@@ -136,7 +144,16 @@ pub(crate) fn stroke_path_impl<'a>(
|
||||
device.set_blend_mode(context.get().graphics_state.blend_mode);
|
||||
let paint = get_paint(context, true);
|
||||
|
||||
let path = path.unwrap_or(context.path());
|
||||
// PdfCraft patch (61): see `resolve_degenerate_subpaths`.
|
||||
let path = resolve_degenerate_subpaths(
|
||||
path.unwrap_or(context.path()),
|
||||
stroke_props.line_cap,
|
||||
stroke_props.line_width,
|
||||
);
|
||||
let path = path.as_ref();
|
||||
if path.elements().is_empty() {
|
||||
return;
|
||||
}
|
||||
let draw_mode = PathDrawMode::Stroke(stroke_props);
|
||||
|
||||
if let Some(rect) = path_as_rect(path) {
|
||||
@@ -146,6 +163,76 @@ pub(crate) fn stroke_path_impl<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
/// PdfCraft patch (61): `path` as `S` strokes it, by ISO 32000-2 §8.5.3.2: "If a subpath is
|
||||
/// degenerate (consists of a single-point closed path or of two or more points at the same
|
||||
/// coordinates), the S operator shall paint it only if round line caps have been specified,
|
||||
/// producing a filled circle centred at the single point." With butt or projecting square caps
|
||||
/// it "shall produce no output". So with round caps a degenerate subpath becomes a segment
|
||||
/// centred on its point, a thousandth of the line width long (kurbo draws no cap on a segment of
|
||||
/// length zero), and is left out for the other caps. The other subpaths, and zero-length dashes
|
||||
/// of them, are not touched. Borrowed when nothing changes.
|
||||
pub(crate) fn resolve_degenerate_subpaths(
|
||||
path: &BezPath,
|
||||
cap: Cap,
|
||||
line_width: f32,
|
||||
) -> Cow<'_, BezPath> {
|
||||
let elements = path.elements();
|
||||
if !subpaths(elements).any(|sub| degenerate_point(sub).is_some()) {
|
||||
return Cow::Borrowed(path);
|
||||
}
|
||||
let mut out = BezPath::new();
|
||||
for sub in subpaths(elements) {
|
||||
match degenerate_point(sub) {
|
||||
Some(p) if cap == Cap::Round => {
|
||||
// A hairline (width 0) is widened by the device, so it keeps a length kurbo still
|
||||
// caps; an enormous width keeps the segment within half a unit.
|
||||
let half = (f64::from(line_width) * 5e-4).max(5e-5).min(0.5);
|
||||
out.move_to((p.x - half, p.y));
|
||||
out.line_to((p.x + half, p.y));
|
||||
}
|
||||
Some(_) => {}
|
||||
None => sub.iter().for_each(|el| out.push(*el)),
|
||||
}
|
||||
}
|
||||
Cow::Owned(out)
|
||||
}
|
||||
|
||||
/// The subpaths of `elements`: each starts at a `MoveTo`, except perhaps the first.
|
||||
fn subpaths(elements: &[PathEl]) -> impl Iterator<Item = &[PathEl]> {
|
||||
let mut rest = elements;
|
||||
std::iter::from_fn(move || {
|
||||
if rest.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let end = rest
|
||||
.iter()
|
||||
.skip(1)
|
||||
.position(|el| matches!(el, PathEl::MoveTo(_)))
|
||||
.map_or(rest.len(), |i| i.saturating_add(1));
|
||||
let (sub, tail) = rest.split_at_checked(end).unwrap_or((rest, &[]));
|
||||
rest = tail;
|
||||
Some(sub)
|
||||
})
|
||||
}
|
||||
|
||||
/// The point a degenerate subpath stays at: one that starts with a `MoveTo` and has at least one
|
||||
/// segment or a `ClosePath`, every point of which (control points too) is the start point. A lone
|
||||
/// `MoveTo` (a trailing `m`) is not one: it paints nothing whatever the caps.
|
||||
fn degenerate_point(sub: &[PathEl]) -> Option<Point> {
|
||||
let (PathEl::MoveTo(start), rest) = sub.split_first()? else {
|
||||
return None;
|
||||
};
|
||||
let at = |p: &Point| p == start;
|
||||
let degenerate = !rest.is_empty()
|
||||
&& rest.iter().all(|el| match el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) => at(p),
|
||||
PathEl::QuadTo(a, b) => at(a) && at(b),
|
||||
PathEl::CurveTo(a, b, c) => at(a) && at(b) && at(c),
|
||||
PathEl::ClosePath => true,
|
||||
});
|
||||
degenerate.then_some(*start)
|
||||
}
|
||||
|
||||
pub(crate) fn get_paint<'a>(context: &Context<'a>, is_stroke: bool) -> Paint<'a> {
|
||||
let data = if is_stroke {
|
||||
context.get().stroke_data()
|
||||
|
||||
+9
-7
@@ -1,7 +1,7 @@
|
||||
use crate::StrokeProps;
|
||||
use crate::color::{AlphaColor, ColorComponents, ColorSpace};
|
||||
use crate::context::Context;
|
||||
use crate::convert::{convert_line_cap, convert_line_join};
|
||||
use crate::convert::{convert_dash_array, convert_line_cap, convert_line_join, convert_line_width};
|
||||
use crate::font::{Font, UNITS_PER_EM};
|
||||
use crate::function::Function;
|
||||
use crate::interpret::text::TextRenderingMode;
|
||||
@@ -319,7 +319,11 @@ pub(crate) fn handle_gs_single<'a>(
|
||||
) -> Option<()> {
|
||||
// TODO Can we use constants here somehow?
|
||||
match key.as_str() {
|
||||
"LW" => context.get_mut().graphics_state.stroke_props.line_width = dict.get::<f32>(key)?,
|
||||
// PdfCraft patch (61): see `convert_line_width`.
|
||||
"LW" => {
|
||||
context.get_mut().graphics_state.stroke_props.line_width =
|
||||
convert_line_width(dict.get::<f32>(key)?);
|
||||
}
|
||||
"LC" => {
|
||||
context.get_mut().graphics_state.stroke_props.line_cap =
|
||||
convert_line_cap(LineCap(dict.get::<Number>(key)?));
|
||||
@@ -402,11 +406,9 @@ pub(crate) fn handle_gs_single<'a>(
|
||||
let dash_phase = iter.next()?.into_number()?.as_f32();
|
||||
|
||||
context.get_mut().graphics_state.stroke_props.dash_offset = dash_phase;
|
||||
context.get_mut().graphics_state.stroke_props.dash_array = dash_array
|
||||
.iter::<f32>()
|
||||
// kurbo apparently cannot properly deal with offsets that are exactly 0.
|
||||
.map(|n| if n == 0.0 { 0.01 } else { n })
|
||||
.collect();
|
||||
// PdfCraft patch (61): see `convert_dash_array`.
|
||||
context.get_mut().graphics_state.stroke_props.dash_array =
|
||||
convert_dash_array(dash_array.iter::<f32>());
|
||||
}
|
||||
"Type" => {}
|
||||
_ => {}
|
||||
|
||||
Reference in new issue
Block a user