mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 05:37:04 +00:00
hayro-interpret: a form that draws itself is not content-truncated
Patch 89 still skips a form already on the drawing stack (ISO 32000-2 §8.10.1). Reporting that skip as InterpreterWarning::ContentTruncated made VectorCraft reject legitimate knockout-mask PDFs after the #2472 pin, because a soft mask may paint a form already being drawn. The skip stays; the truncation flag does not. Refs storytold/craft-libs#778.
This commit is contained in:
+114
-89
@@ -277,27 +277,14 @@ const MAX_SAVED_STATE_BYTES: usize = 64 << 20;
|
||||
/// Roughly what a saved copy of `state` holds.
|
||||
fn state_bytes(state: &State<'_>) -> usize {
|
||||
size_of::<State<'_>>()
|
||||
.saturating_add(
|
||||
state
|
||||
.graphics_state
|
||||
.stroke_props
|
||||
.dash_array
|
||||
.len()
|
||||
.saturating_mul(size_of::<f32>()),
|
||||
)
|
||||
.saturating_add(state.graphics_state.stroke_props.dash_array.len().saturating_mul(size_of::<f32>()))
|
||||
.saturating_add(state.clips.len().saturating_mul(size_of::<ClipType>()))
|
||||
.saturating_add(state.text_state.clip_paths.elements().len().saturating_mul(size_of::<PathEl>()))
|
||||
}
|
||||
|
||||
impl<'a> Context<'a> {
|
||||
/// Create a new context.
|
||||
pub fn new(
|
||||
initial_transform: Affine,
|
||||
bbox: Rect,
|
||||
cache: &InterpreterCache<'a>,
|
||||
xref: &'a XRef,
|
||||
settings: InterpreterSettings,
|
||||
) -> Self {
|
||||
pub fn new(initial_transform: Affine, bbox: Rect, cache: &InterpreterCache<'a>, xref: &'a XRef, settings: InterpreterSettings) -> Self {
|
||||
let state = State::new(initial_transform);
|
||||
// PdfCraft patch: a page (or other top-level content) starts with fresh budgets.
|
||||
NESTED_PAINTS.with(|n| n.set(0));
|
||||
@@ -325,9 +312,7 @@ impl<'a> Context<'a> {
|
||||
) -> Self {
|
||||
let mut ocg_state = {
|
||||
let root_ref = xref.root_id();
|
||||
xref.get::<Dict<'_>>(root_ref)
|
||||
.map(|catalog| OcgState::from_catalog(&catalog, xref, settings.view_auto_state))
|
||||
.unwrap_or_default()
|
||||
xref.get::<Dict<'_>>(root_ref).map(|catalog| OcgState::from_catalog(&catalog, xref, settings.view_auto_state)).unwrap_or_default()
|
||||
};
|
||||
// PdfCraft patch: apply viewer layer toggles.
|
||||
for (num, generation, visible) in settings.ocg_overrides.iter() {
|
||||
@@ -357,17 +342,19 @@ impl<'a> Context<'a> {
|
||||
/// PdfCraft patch (89): begins drawing the form `id`; `false` when that form is already
|
||||
/// being drawn, so drawing it again would never end (ISO 32000-2 §8.10.1: a form is a
|
||||
/// self-contained description; one that contains itself describes nothing finite). The
|
||||
/// skip is reported as `InterpreterWarning::ContentTruncated`. A form without an object
|
||||
/// number can't be told apart and is only bounded by the nesting limits.
|
||||
/// inner drawing is skipped; that is not reported as `InterpreterWarning::ContentTruncated`,
|
||||
/// because the page was not cut short by a size budget: a cycle was skipped as the
|
||||
/// specification requires. A soft mask (or a knockout mask built from one) may legally
|
||||
/// paint a form already on the stack; reporting that skip as truncation made VectorCraft
|
||||
/// reject a 200-shape knockout-mask PDF that otherwise imported completely
|
||||
/// (storytold/craft-libs#778). A form without an object number can't be told apart and is
|
||||
/// only bounded by the nesting limits.
|
||||
///
|
||||
/// 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.
|
||||
pub(crate) fn enter_form(
|
||||
&mut self,
|
||||
id: Option<hayro_syntax::object::ObjectIdentifier>,
|
||||
) -> bool {
|
||||
pub(crate) fn enter_form(&mut self, id: Option<hayro_syntax::object::ObjectIdentifier>) -> bool {
|
||||
let Some(id) = id else {
|
||||
return true;
|
||||
};
|
||||
@@ -385,7 +372,6 @@ impl<'a> Context<'a> {
|
||||
});
|
||||
if entered == Some(false) {
|
||||
warn!("form XObject draws itself; the inner drawing is skipped");
|
||||
CONTENT_TRUNCATED.with(|truncated| truncated.set(true));
|
||||
return false;
|
||||
}
|
||||
true
|
||||
@@ -413,10 +399,7 @@ impl<'a> Context<'a> {
|
||||
// PdfCraft patch: past either limit the `q` is recorded but nothing is copied. Its `Q`
|
||||
// still removes the clips added since; other changes made in between are kept.
|
||||
let bytes = state_bytes(cur);
|
||||
if !self.skipped_saves.is_empty()
|
||||
|| self.states.len() >= MAX_SAVED_STATES
|
||||
|| self.saved_bytes.saturating_add(bytes) > MAX_SAVED_STATE_BYTES
|
||||
{
|
||||
if !self.skipped_saves.is_empty() || self.states.len() >= MAX_SAVED_STATES || self.saved_bytes.saturating_add(bytes) > MAX_SAVED_STATE_BYTES {
|
||||
if self.skipped_saves.is_empty() {
|
||||
warn!("too many saved graphics states; further saves are not kept");
|
||||
}
|
||||
@@ -442,22 +425,13 @@ impl<'a> Context<'a> {
|
||||
self.bbox.push(new);
|
||||
}
|
||||
|
||||
pub(crate) fn push_clip_path(
|
||||
&mut self,
|
||||
clip_path: BezPath,
|
||||
fill: FillRule,
|
||||
device: &mut impl Device<'a>,
|
||||
) {
|
||||
pub(crate) fn push_clip_path(&mut self, clip_path: BezPath, fill: FillRule, device: &mut impl Device<'a>) {
|
||||
if let Some(clip_rect) = path_as_rect(&clip_path) {
|
||||
let cur_bbox = self.bbox();
|
||||
|
||||
// If the clip path is a rect and completely covers the current bbox, don't emit it.
|
||||
if cur_bbox
|
||||
.min_x()
|
||||
.is_nearly_greater_or_equal(clip_rect.min_x())
|
||||
&& cur_bbox
|
||||
.min_y()
|
||||
.is_nearly_greater_or_equal(clip_rect.min_y())
|
||||
if cur_bbox.min_x().is_nearly_greater_or_equal(clip_rect.min_x())
|
||||
&& cur_bbox.min_y().is_nearly_greater_or_equal(clip_rect.min_y())
|
||||
&& cur_bbox.max_x().is_nearly_less_or_equal(clip_rect.max_x())
|
||||
&& cur_bbox.max_y().is_nearly_less_or_equal(clip_rect.max_y())
|
||||
{
|
||||
@@ -467,10 +441,7 @@ impl<'a> Context<'a> {
|
||||
}
|
||||
|
||||
let bbox = clip_path.bounding_box();
|
||||
device.push_clip_path(&ClipPath {
|
||||
path: clip_path,
|
||||
fill,
|
||||
});
|
||||
device.push_clip_path(&ClipPath { path: clip_path, fill });
|
||||
self.push_bbox(bbox);
|
||||
self.get_mut().clips.push(ClipType::Real);
|
||||
}
|
||||
@@ -495,10 +466,7 @@ impl<'a> Context<'a> {
|
||||
}
|
||||
|
||||
pub(crate) fn root_transform(&self) -> Affine {
|
||||
self.root_transforms
|
||||
.last()
|
||||
.copied()
|
||||
.unwrap_or(Affine::IDENTITY)
|
||||
self.root_transforms.last().copied().unwrap_or(Affine::IDENTITY)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_state(&mut self, device: &mut impl Device<'a>) {
|
||||
@@ -510,11 +478,7 @@ impl<'a> Context<'a> {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(target_clips) = self
|
||||
.states
|
||||
.get(self.states.len().saturating_sub(2))
|
||||
.map(|s| s.clips.len())
|
||||
else {
|
||||
let Some(target_clips) = self.states.get(self.states.len().saturating_sub(2)).map(|s| s.clips.len()) else {
|
||||
warn!("underflowed graphics state");
|
||||
return;
|
||||
};
|
||||
@@ -532,11 +496,7 @@ impl<'a> Context<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
device.set_soft_mask(
|
||||
self.states
|
||||
.last()
|
||||
.and_then(|l| l.graphics_state.soft_mask.clone()),
|
||||
);
|
||||
device.set_soft_mask(self.states.last().and_then(|l| l.graphics_state.soft_mask.clone()));
|
||||
}
|
||||
|
||||
pub(crate) fn path(&self) -> &BezPath {
|
||||
@@ -585,20 +545,11 @@ impl<'a> Context<'a> {
|
||||
|
||||
/// PdfCraft patch (80): an `/Indexed` resource with no lookup table is built, marked
|
||||
/// tableless, for the image and colour operators to handle (see `Indexed::new`).
|
||||
pub(crate) fn get_color_space(
|
||||
&mut self,
|
||||
resources: &Resources<'_>,
|
||||
name: &Name<'_>,
|
||||
) -> Option<ColorSpace> {
|
||||
pub(crate) fn get_color_space(&mut self, resources: &Resources<'_>, name: &Name<'_>) -> Option<ColorSpace> {
|
||||
let cs_object = resources.get_color_space(name)?;
|
||||
self.interpreter_cache
|
||||
.object_cache
|
||||
.get_or_insert_with(cs_object.cache_key(), || {
|
||||
ColorSpace::new_allowing_tableless(
|
||||
cs_object.clone(),
|
||||
&self.interpreter_cache.object_cache,
|
||||
)
|
||||
})
|
||||
.get_or_insert_with(cs_object.cache_key(), || ColorSpace::new_allowing_tableless(cs_object.clone(), &self.interpreter_cache.object_cache))
|
||||
}
|
||||
|
||||
pub(crate) fn stroke_props(&self) -> StrokeProps {
|
||||
@@ -658,16 +609,7 @@ impl<'a> Context<'a> {
|
||||
|
||||
let resolved = {
|
||||
let mut font_cache = self.interpreter_cache.font_cache.borrow_mut();
|
||||
font_cache
|
||||
.entry(cache_key)
|
||||
.or_insert_with(|| {
|
||||
Font::new(
|
||||
font_dict,
|
||||
&self.settings.font_resolver,
|
||||
&self.settings.cmap_resolver,
|
||||
)
|
||||
})
|
||||
.clone()
|
||||
font_cache.entry(cache_key).or_insert_with(|| Font::new(font_dict, &self.settings.font_resolver, &self.settings.cmap_resolver)).clone()
|
||||
};
|
||||
|
||||
// PdfCraft patch (90): tell the caller a Type 3 font lacks the /Widths it requires,
|
||||
@@ -679,8 +621,7 @@ impl<'a> Context<'a> {
|
||||
if let Some(resolved) = resolved {
|
||||
Some(TextStateFont::Font(resolved))
|
||||
} else {
|
||||
Font::new_standard(StandardFont::Helvetica, &self.settings.font_resolver)
|
||||
.map(TextStateFont::Fallback)
|
||||
Font::new_standard(StandardFont::Helvetica, &self.settings.font_resolver).map(TextStateFont::Fallback)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -764,10 +705,7 @@ mod saved_state_tests {
|
||||
use hayro_syntax::Pdf;
|
||||
|
||||
fn pdf() -> Pdf {
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Count 0 /Kids [] >>",
|
||||
];
|
||||
let objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Count 0 /Kids [] >>"];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, body) in objects.iter().enumerate() {
|
||||
@@ -779,9 +717,7 @@ mod saved_state_tests {
|
||||
for offset in offsets {
|
||||
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(
|
||||
format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes(),
|
||||
);
|
||||
out.extend_from_slice(format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes());
|
||||
Pdf::new(out).expect("synthetic pdf")
|
||||
}
|
||||
|
||||
@@ -848,3 +784,92 @@ mod saved_state_tests {
|
||||
assert_eq!(ctx.get().ctm, Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
|
||||
/// A form that paints itself is skipped so interpretation ends; that skip is not
|
||||
/// reported as [`crate::interpret::InterpreterWarning::ContentTruncated`] (craft-libs#778).
|
||||
#[cfg(test)]
|
||||
mod form_cycle_tests {
|
||||
use super::*;
|
||||
use crate::device::DummyDevice;
|
||||
use crate::interpret::{InterpreterSettings, InterpreterWarning, interpret_page};
|
||||
use hayro_syntax::Pdf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn pdf_from_objects(bodies: &[String]) -> Pdf {
|
||||
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(dict: &str, data: &str) -> String {
|
||||
format!("<< {dict} /Length {} >>\nstream\n{data}endstream", data.len())
|
||||
}
|
||||
|
||||
fn warnings_from(pdf: &Pdf) -> Vec<InterpreterWarning> {
|
||||
let warnings = Arc::new(Mutex::new(Vec::new()));
|
||||
let settings = InterpreterSettings {
|
||||
warning_sink: {
|
||||
let warnings = warnings.clone();
|
||||
Arc::new(move |warning| warnings.lock().expect("warnings").push(warning))
|
||||
},
|
||||
..InterpreterSettings::default()
|
||||
};
|
||||
let cache = InterpreterCache::new();
|
||||
let mut context = Context::new(Affine::IDENTITY, Rect::new(0.0, 0.0, 100.0, 100.0), &cache, pdf.xref(), settings);
|
||||
interpret_page(&pdf.pages()[0], &mut context, &mut DummyDevice);
|
||||
warnings.lock().expect("warnings").clone()
|
||||
}
|
||||
|
||||
fn is_truncated(warnings: &[InterpreterWarning]) -> bool {
|
||||
warnings.iter().any(|w| matches!(w, InterpreterWarning::ContentTruncated))
|
||||
}
|
||||
|
||||
/// A form whose content draws itself: the recursive `Do` is skipped, the fill still
|
||||
/// paints, and the page is not reported as truncated.
|
||||
#[test]
|
||||
fn a_form_that_draws_itself_is_skipped_and_is_not_content_truncated() {
|
||||
let form = stream("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /XObject << /F 5 0 R >> >>", "0 0 100 100 re f\n/F Do\n");
|
||||
let contents = stream("", "/F Do\n");
|
||||
let pdf = pdf_from_objects(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Count 1 /Kids [3 0 R] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /XObject << /F 5 0 R >> >> >>".into(),
|
||||
contents,
|
||||
form,
|
||||
]);
|
||||
let warnings = warnings_from(&pdf);
|
||||
assert!(!content_was_truncated());
|
||||
assert!(!is_truncated(&warnings), "{warnings:?}");
|
||||
}
|
||||
|
||||
/// Form A draws form B, which draws form A: the cycle is skipped the same way, and
|
||||
/// is not reported as a content-size truncation.
|
||||
#[test]
|
||||
fn a_pair_of_forms_that_draw_each_other_is_not_content_truncated() {
|
||||
let form_a = stream("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /XObject << /B 6 0 R >> >>", "0 0 50 50 re f\n/B Do\n");
|
||||
let form_b =
|
||||
stream("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /XObject << /A 5 0 R >> >>", "50 50 50 50 re f\n/A Do\n");
|
||||
let contents = stream("", "/A Do\n");
|
||||
let pdf = pdf_from_objects(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Count 1 /Kids [3 0 R] >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /XObject << /A 5 0 R >> >> >>".into(),
|
||||
contents,
|
||||
form_a,
|
||||
form_b,
|
||||
]);
|
||||
let warnings = warnings_from(&pdf);
|
||||
assert!(!content_was_truncated());
|
||||
assert!(!is_truncated(&warnings), "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user