Merge pull request #2619 from dotCooCoo/fix/hayro-softmask-self-draw

hayro-interpret: a tiling pattern or Type 3 glyph set outside a form draws that form
This commit is contained in:
BFlat authored and GitHub committed 2026-11-30 10:15:22 +07:00
commit 19805ced1e
7 files changed
+391 -13

No files matched your search

+9
View File
@@ -95,6 +95,15 @@ colorants paint through their alternate space (`Plate::spots_as_process`) and no
overprints. Masks in other color spaces are unchanged. A test in
`crates/pdf/tests/plates.rs` checks process, spot, RGB and backdrop colors.
The self-draw check of hayro-interpret patch 89 runs a soft mask's group, a tiling pattern's
cell and a Type 3 glyph's procedure inside the forms being drawn where the mask or pattern was
set or the glyph was shown (`context::forms_drawing`, `context::drawing_within`), not inside the
forms the device is drawing when it calls `SoftMask::interpret`, `SoftMask::interpret_plate`,
`TilingPattern::interpret` or `Type3Glyph::interpret`. A tiling pattern or Type 3 glyph set on
the page and interpreted by a device while it draws a form draws that form; before, its copy of
the form was skipped. A form that draws itself through a soft mask, tiling pattern or Type 3
glyph set inside it is still skipped. Tests: `self_draw_tests.rs` in hayro-interpret.
The output-intent conversion of patch 36 goes through a `color::CmykConversion` trait, so
that callers can convert with their own color management. `CmykSimulation::new` keeps
#2770's moxcms conversion as the default, and `CmykSimulation::with_conversion` takes a
+10 -4
View File
@@ -188,7 +188,7 @@
"path": "src/context.rs",
"source_sha256": "dc2be553958ee3f5e5e644a77a0301723bae9ca027a352c13b9caaf549cc0e56",
"source_git_blob": "d6772baa15ebb95d3ba2d1f54ce5c250ad1e8137",
"sha256": "b8c530ff091a231fba36af17c89e38705b848e5c614a3f3888def871ffb5b597"
"sha256": "af6fd93f8b8b271e88ed254970dc789c0b7dff914b5e51bffcf4fdd7b47978b2"
},
{
"path": "src/convert.rs",
@@ -290,7 +290,7 @@
"path": "src/font/mod.rs",
"source_sha256": "7e6411927d91205ca76c6b59f9d737cd1104d066f8cfcc0a87f481016ef30313",
"source_git_blob": "7c8c8d086d59139df791cdb6952506473ec4b5a7",
"sha256": "b58ee45b8c4a4d1de36eadc11363a8620ac56202646c937c1a012539372883bc"
"sha256": "e239a2def9915d4df38eaed4deccc0ffc57ccfb6a3c9d5955a02f50db681d155"
},
{
"path": "src/font/outline.rs",
@@ -386,7 +386,7 @@
"path": "src/lib.rs",
"source_sha256": "ea3fa23b74f99b5382798f90b7e9f0e3edca354ee26ea92fe26a91ee5c0195c9",
"source_git_blob": "24c3be295783d7a53ac6bc39d93e539883480cd4",
"sha256": "3473d9640da637f95252611d1edb601efa9327c117d5580913c670dda696dd6e"
"sha256": "777f78daa1c2dbcb945bc2061bfd5748f3ee07a0efbe53de7fa7de29d2880f5f"
},
{
"path": "src/log.rs",
@@ -404,7 +404,13 @@
"path": "src/pattern.rs",
"source_sha256": "17b49a465275c20e6645dea9443f2cb3a64c594925fd860e74b80b44d5344e37",
"source_git_blob": "9295f51709f8915951d7b9afca9411651d65a1f8",
"sha256": "1ee9705afa285ddeb4c287e83e86906bdcc525a738b41d17164d1f751e2c01b6"
"sha256": "4621fe8b85f472e731e2c01d0f92ec1662c7d9d0f0e20f520fd9c926201af8d5"
},
{
"path": "src/self_draw_tests.rs",
"source_sha256": null,
"source_git_blob": null,
"sha256": "1f0a93fb387d3ba51c1348ed69fe567fdb2be88ee57506400cd66644dadadb85"
},
{
"path": "src/shading.rs",
+10 -6
View File
@@ -38,10 +38,11 @@ std::thread_local! {
// `InterpreterWarning::ContentTruncated`.
static CONTENT_TRUNCATED: core::cell::Cell<bool> = const { core::cell::Cell::new(false) };
// PdfCraft patch (89): the form XObjects being drawn on this page, outermost first, across
// the contexts of the tiling patterns, Type 3 glyphs and groups painted while they draw; a
// soft mask's group draws within the forms where the mask was set (`drawing_within`). A form
// already on it draws itself and is skipped. Its length is bounded by the nesting limits:
// every form on it is nested in the ones before it.
// the contexts of the groups painted while they draw; a soft mask's group, a tiling pattern's
// cell and a Type 3 glyph's procedure draw within the forms where the mask or pattern was set
// or the glyph was shown (`drawing_within`). A form already on it draws itself and is
// skipped. Its length is bounded by the nesting limits: every form on it is nested in the
// ones before it.
static FORMS_DRAWING: RefCell<Vec<hayro_syntax::object::ObjectIdentifier>> =
const { RefCell::new(Vec::new()) };
}
@@ -146,7 +147,9 @@ pub(crate) fn forms_drawing() -> Vec<hayro_syntax::object::ObjectIdentifier> {
/// PdfCraft patch (89): runs `draw` with `forms` as the forms being drawn, then puts back the
/// ones it replaced. A soft mask draws its group where the masked content paints, inside forms
/// that only use the mask; it is nested in the forms drawing where it was set.
/// that only use the mask; it is nested in the forms drawing where it was set. A tiling pattern's
/// cell and a Type 3 glyph's procedure are likewise nested in the forms drawing where the pattern
/// was set or the glyph was shown, wherever the device interprets them.
pub(crate) fn drawing_within<R>(
forms: &[hayro_syntax::object::ObjectIdentifier],
draw: impl FnOnce() -> R,
@@ -402,7 +405,8 @@ impl<'a> Context<'a> {
/// The forms being drawn are those of this page's context and of every context painting
/// inside it (a tiling pattern, a Type 3 glyph, a soft mask or a group), so a form that
/// reaches itself through one of those is skipped too, while a form drawn again after it
/// has finished draws as usual.
/// has finished draws as usual. A soft mask, tiling pattern or Type 3 glyph draws inside
/// the forms it was set in, wherever the device interprets it ([`drawing_within`]).
pub(crate) fn enter_form(
&mut self,
id: Option<hayro_syntax::object::ObjectIdentifier>,
+12 -2
View File
@@ -14,6 +14,7 @@ use crate::interpret::state::State;
use crate::{CMapResolverFn, CacheKey, FontResolverFn, InterpreterSettings, Paint};
use bitflags::bitflags;
use hayro_syntax::object::Name;
use hayro_syntax::object::ObjectIdentifier;
use hayro_syntax::object::dict::keys::SUBTYPE;
use hayro_syntax::object::dict::keys::*;
use hayro_syntax::object::{Dict, Stream};
@@ -222,11 +223,17 @@ pub struct Type3Glyph<'a> {
pub(crate) settings: InterpreterSettings,
pub(crate) nesting_depth: u32,
pub(crate) char_code: u32,
/// PdfCraft patch (89): the forms being drawn where the glyph was shown; its procedure is
/// drawn nested in them, not in the forms the device is drawing when it interprets it.
pub(crate) forms_drawing: Vec<ObjectIdentifier>,
}
/// A glyph defined by PDF drawing instructions.
impl<'a> Type3Glyph<'a> {
/// Draw the type3 glyph to the given device.
///
/// PdfCraft patch (89): the glyph procedure draws inside the forms the glyph was shown in,
/// wherever the device interprets it.
pub fn interpret(
&self,
device: &mut impl Device<'a>,
@@ -234,8 +241,10 @@ impl<'a> Type3Glyph<'a> {
glyph_transform: Affine,
paint: &Paint<'a>,
) {
self.font
.render_glyph(self, transform, glyph_transform, paint, device);
crate::context::drawing_within(&self.forms_drawing, || {
self.font
.render_glyph(self, transform, glyph_transform, paint, device)
});
}
/// Returns the Unicode code point for this glyph, if available: the `ToUnicode` cmap, then
@@ -386,6 +395,7 @@ impl<'a> Font<'a> {
settings: ctx.settings.clone(),
nesting_depth,
char_code,
forms_drawing: crate::context::forms_drawing(),
};
Glyph::Type3(Box::new(shape_glyph))
+2
View File
@@ -40,6 +40,8 @@ mod device;
mod function;
mod interpret;
mod ocg;
#[cfg(test)]
mod self_draw_tests;
mod soft_mask;
mod types;
mod x_object;
+20 -1
View File
@@ -2,7 +2,7 @@
use crate::cache::Cache;
use crate::color::{Color, ColorSpace, DefaultColorSpaces, Plate};
use crate::context::{Context, InterpreterCache};
use crate::context::{Context, InterpreterCache, drawing_within, forms_drawing};
use crate::device::Device;
use crate::font::Glyph;
use crate::interpret::state::{ActiveTransferFunction, State};
@@ -13,6 +13,7 @@ use crate::{BlendMode, CacheKey, ClipPath, GlyphDrawMode, Image, PathDrawMode};
use crate::{FillRule, InterpreterSettings, Paint, interpret};
use hayro_syntax::content::TypedIter;
use hayro_syntax::object::Dict;
use hayro_syntax::object::ObjectIdentifier;
use hayro_syntax::object::Stream;
use hayro_syntax::object::dict::keys::{
BBOX, EXT_G_STATE, MATRIX, PAINT_TYPE, RESOURCES, SHADING, X_STEP, Y_STEP,
@@ -182,6 +183,9 @@ pub struct TilingPattern<'a> {
pub(crate) settings: InterpreterSettings,
pub(crate) xref: &'a XRef,
nesting_depth: u32,
/// PdfCraft patch (89): the forms being drawn where the pattern was set; its cell is drawn
/// nested in them, not in the forms that paint with it.
forms_drawing: Vec<ObjectIdentifier>,
}
impl TilingPattern<'_> {
@@ -280,15 +284,30 @@ impl<'a> TilingPattern<'a> {
cache: ctx.interpreter_cache.clone(),
xref: ctx.xref,
nesting_depth,
forms_drawing: forms_drawing(),
})
}
/// Interpret the contents of the pattern into the given device.
///
/// PdfCraft patch (89): the cell draws inside the forms the pattern was set in, wherever the
/// device interprets it.
pub fn interpret(
&self,
device: &mut impl Device<'a>,
initial_transform: Affine,
is_stroke: bool,
) -> Option<()> {
drawing_within(&self.forms_drawing, || {
self.interpret_cell(device, initial_transform, is_stroke)
})
}
fn interpret_cell(
&self,
device: &mut impl Device<'a>,
initial_transform: Affine,
is_stroke: bool,
) -> Option<()> {
// PdfCraft patch: a tiling pattern can paint itself (directly, or through resources it
// inherits when its own are missing), which recursed until the stack overflowed. Bound
+328
View File
@@ -0,0 +1,328 @@
//! PdfCraft patch (89) tests: a form that draws itself through a soft mask, a tiling pattern or
//! a Type 3 glyph set inside it is skipped, and the page is not reported truncated. A soft mask,
//! tiling pattern or Type 3 glyph set outside a form draws that form in full when the device
//! interprets it while drawing the form. The tests of a form that draws itself directly or
//! through another form are in `context.rs`.
use crate::context::content_was_truncated;
use crate::font::{Glyph, Type3Glyph};
use crate::pattern::Pattern;
use crate::{
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache,
InterpreterSettings, InterpreterWarning, Paint, PathDrawMode, SoftMask, interpret_page,
};
use hayro_syntax::Pdf;
use kurbo::{Affine, BezPath, Rect};
use std::sync::{Arc, Mutex};
/// A PDF with one 100 by 100 page whose resources are `resources` and whose content is
/// `content`, followed by `objects` as objects 5, 6 and so on.
fn pdf(resources: &str, content: &str, objects: &[String]) -> Pdf {
let mut bodies = vec![
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
"<< /Type /Pages /Count 1 /Kids [3 0 R] >>".to_string(),
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources {resources} >>"
),
stream("", content),
];
bodies.extend_from_slice(objects);
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, body) in bodies.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{body}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(
format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes(),
);
for offset in offsets {
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
bodies.len() + 1
)
.as_bytes(),
);
Pdf::new(out).expect("synthetic pdf")
}
fn stream(entries: &str, content: &str) -> String {
format!(
"<< /Length {} {entries} >>\nstream\n{content}\nendstream",
content.len()
)
}
/// A form 10 by 10 that draws `content` with the resources of whatever draws it.
fn form(content: &str) -> String {
stream("/Type /XObject /Subtype /Form /BBox [0 0 10 10]", content)
}
/// A soft mask group that draws `content` with `resources`.
fn mask_group(resources: &str, content: &str) -> String {
stream(
&format!(
"/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency >> /Resources {resources}"
),
content,
)
}
/// A colored tiling pattern whose cell draws `content` with `resources`.
fn tiling(resources: &str, content: &str) -> String {
stream(
&format!(
"/Type /Pattern /PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10 /Resources {resources}"
),
content,
)
}
/// A Type 3 font whose glyph `a` is drawn by the procedure in object `proc`, with `resources`.
fn type3(resources: &str, proc: usize) -> String {
format!(
"<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a {proc} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a] >> /FirstChar 97 /LastChar 97 /Widths [1000] /Resources {resources} >>"
)
}
/// The paths a device was given, by where they were drawn.
#[derive(Default, Debug, PartialEq)]
struct Drawn {
paths: usize,
in_masks: usize,
in_patterns: usize,
in_glyphs: usize,
}
/// A device that interprets every soft mask it is given, every tiling pattern it fills with and
/// every Type 3 glyph it draws, each into a device of its own, at the time it is given them. With
/// `defer_glyphs`, it keeps the first Type 3 glyph and interprets it at the next path instead.
#[derive(Default)]
struct Recorder<'a> {
drawn: Drawn,
defer_glyphs: bool,
deferred: Option<Box<Type3Glyph<'a>>>,
}
impl Recorder<'_> {
fn absorb(&mut self, inner: &Recorder<'_>) -> usize {
let d = &inner.drawn;
self.drawn.in_masks += d.in_masks;
self.drawn.in_patterns += d.in_patterns;
self.drawn.in_glyphs += d.in_glyphs;
d.paths
}
}
impl<'a> Device<'a> for Recorder<'a> {
fn set_soft_mask(&mut self, mask: Option<SoftMask<'a>>) {
if let Some(mask) = mask {
let mut inner = Recorder::default();
mask.interpret(&mut inner);
self.drawn.in_masks += self.absorb(&inner);
}
}
fn set_blend_mode(&mut self, _: BlendMode) {}
fn draw_path(&mut self, _: &BezPath, transform: Affine, paint: &Paint<'a>, _: &PathDrawMode) {
self.drawn.paths += 1;
if let Paint::Pattern(pattern) = paint
&& let Pattern::Tiling(tiling) = &**pattern
{
let mut inner = Recorder::default();
tiling.interpret(&mut inner, transform, false);
self.drawn.in_patterns += self.absorb(&inner);
}
if let Some(glyph) = self.deferred.take() {
let mut inner = Recorder::default();
glyph.interpret(&mut inner, Affine::IDENTITY, Affine::IDENTITY, paint);
self.drawn.in_glyphs += self.absorb(&inner);
}
}
fn push_clip_path(&mut self, _: &ClipPath) {}
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'a>>, _: BlendMode) {}
fn draw_glyph(
&mut self,
glyph: &Glyph<'a>,
transform: Affine,
glyph_transform: Affine,
paint: &Paint<'a>,
_: &GlyphDrawMode,
) {
let Glyph::Type3(glyph) = glyph else {
return;
};
if self.defer_glyphs {
self.deferred = Some(glyph.clone());
return;
}
let mut inner = Recorder::default();
glyph.interpret(&mut inner, transform, glyph_transform, paint);
self.drawn.in_glyphs += self.absorb(&inner);
}
fn draw_image(&mut self, _: Image<'a, '_>, _: Affine) {}
fn pop_clip_path(&mut self) {}
fn pop_transparency_group(&mut self) {}
}
/// Draws the page of `pdf` and returns what was drawn and whether the page was reported
/// truncated.
fn draw(pdf: &Pdf, defer_glyphs: bool) -> (Drawn, bool) {
let cache = InterpreterCache::new();
let warnings = Arc::new(Mutex::new(Vec::new()));
let sink = warnings.clone();
let settings = InterpreterSettings {
warning_sink: Arc::new(move |warning| sink.lock().expect("warnings").push(warning)),
..InterpreterSettings::default()
};
let mut ctx = Context::new(
Affine::IDENTITY,
Rect::new(0.0, 0.0, 100.0, 100.0),
&cache,
pdf.xref(),
settings,
);
let mut device = Recorder {
defer_glyphs,
..Recorder::default()
};
let page = &pdf.pages()[0];
interpret_page(page, &mut ctx, &mut device);
let warnings = warnings.lock().expect("warnings");
let truncated = warnings
.iter()
.any(|w| matches!(w, InterpreterWarning::ContentTruncated));
assert_eq!(truncated, content_was_truncated());
(device.drawn, truncated)
}
const SQUARE: &str = "0 0 10 10 re f";
// A form that names itself in its own resources is a reference cycle, which hayro-syntax reads
// as a missing object. The forms below have no resources of their own and reach themselves
// through the page's.
#[test]
fn a_soft_mask_set_outside_a_form_draws_that_form() {
// The mask is set on the page and draws the form the page then draws; the device interprets
// it while it draws that form.
let pdf = pdf(
"<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>",
"/GS gs /F Do",
&[
form(SQUARE),
mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do"),
],
);
let (drawn, truncated) = draw(&pdf, false);
assert!(drawn.in_masks > 0, "{drawn:?}");
assert_eq!(drawn.paths, 1);
assert!(!truncated);
}
#[test]
fn a_soft_mask_set_inside_a_form_that_it_draws_skips_that_form() {
let pdf = pdf(
"<< /XObject << /F 5 0 R >> /ExtGState << /GS << /SMask << /S /Alpha /G 6 0 R >> >> >> >>",
"/F Do",
&[
form("/GS gs 0 0 10 10 re f"),
mask_group("<< /XObject << /F 5 0 R >> >>", "/F Do"),
],
);
let (drawn, truncated) = draw(&pdf, false);
assert_eq!(
drawn,
Drawn {
paths: 1,
..Drawn::default()
}
);
assert!(!truncated);
}
#[test]
fn a_tiling_pattern_set_outside_a_form_draws_that_form() {
let pdf = pdf(
"<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>",
"/Pattern cs /P scn /F Do",
&[
form(SQUARE),
tiling("<< /XObject << /F 5 0 R >> >>", "/F Do"),
],
);
let (drawn, truncated) = draw(&pdf, false);
assert!(drawn.in_patterns > 0, "{drawn:?}");
assert!(!truncated);
}
#[test]
fn a_tiling_pattern_set_inside_a_form_that_it_draws_skips_that_form() {
let pdf = pdf(
"<< /XObject << /F 5 0 R >> /Pattern << /P 6 0 R >> >>",
"/F Do",
&[
form("/Pattern cs /P scn 0 0 10 10 re f"),
tiling("<< /XObject << /F 5 0 R >> >>", "/F Do"),
],
);
let (drawn, truncated) = draw(&pdf, false);
assert_eq!(
drawn,
Drawn {
paths: 1,
..Drawn::default()
}
);
assert!(!truncated);
}
#[test]
fn a_type3_glyph_shown_outside_a_form_draws_that_form() {
// The device keeps the glyph shown on the page and interprets it while it draws the form.
let pdf = pdf(
"<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>",
"BT /T 10 Tf (a) Tj ET /F Do",
&[
form(SQUARE),
type3("<< /XObject << /F 5 0 R >> >>", 7),
stream("", "1000 0 d0 /F Do"),
],
);
let (drawn, truncated) = draw(&pdf, true);
assert!(drawn.in_glyphs > 0, "{drawn:?}");
assert!(!truncated);
}
#[test]
fn a_type3_glyph_shown_inside_a_form_that_it_draws_skips_that_form() {
let pdf = pdf(
"<< /XObject << /F 5 0 R >> /Font << /T 6 0 R >> >>",
"/F Do",
&[
form("BT /T 10 Tf (a) Tj ET 0 0 10 10 re f"),
type3("<< /XObject << /F 5 0 R >> >>", 7),
stream("", "1000 0 d0 /F Do"),
],
);
let (drawn, truncated) = draw(&pdf, false);
assert_eq!(
drawn,
Drawn {
paths: 1,
..Drawn::default()
}
);
assert!(!truncated);
}