pdf: center short docs, restore dropped inline images (#321)
- Commit
691f5b85fb4ed464f293ea6bf1a8811d22cd6c08- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-05 19:16 UTC (1 month ago)
- Parents
57b39e0
Symptom: single-page/short PDFs pinned to the top of the viewport with dead space below, and inline (BI/ID/EI) images with abbreviated colorspaces, filters, or missing /BPC silently vanished from the page. Root cause (centering): SafePdfPageViewer pans with translationY = -scroll*zoom, which is 0 when content is shorter than the viewport (range clamps to 0), so short documents top-align. Root cause (images): lopdf 0.45 reports a successful strict parse while dropping any inline image it cannot fully decode (/CS /G, any /F, missing /BPC) as an operand-less BI op, so the lenient tokenizer never ran and the interpreter skipped the image without a diagnostic. The same lopdf drift broke the test target itself (hayro 0.8 API split, two self.gs typos, a moved kinds import, three stale assertions about lopdf behavior), hiding 22 failures. Fix: add a visual-only centering offset (half the viewport slack, zero when content overflows) in the viewer's graphicsLayer; treat a strict parse holding a stream-less BI as a parse failure so both page and nested-stream paths fall back to the lenient tokenizer; decode font/cmap streams through our own filter chain instead of trusting lopdf's Ok (which passes still-encoded bytes through on unresolvable filters); re-pin the wire-budget, page-clamp, and recovery tests to current file layouts and dependency behavior. User-visible effect: short documents render vertically centered; pages using inline images (logos, stamps, small figures) show them instead of blank gaps. No scrollbar or scroll-state code touched. Verification: cargo test -p pdf_render --lib 568 passed / 3 failed (was uncompilable before; the 3 remaining failures are encrypt save roundtrips failing identically with and without this change); issue321 harness renders all 13 fixtures plus Ishihara_Tests.pdf with no panics or interpret errors; :pdf:compileDevKotlin and :pdf:testDevUnitTest green.
Diff
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.ktindex 5e3ae560b2..e13cfdc393 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfPageViewer.kt@@ -144,7 +144,14 @@ internal fun SafePdfPageViewer( scaleX = zoom.zoom scaleY = zoom.zoom translationX = zoom.pan.x- translationY = -scroll.scrollPx * zoom.zoom+ // Issue #321: a document shorter than the viewport (e.g. a+ // single page) used to pin to the top with dead space below.+ // Center it vertically instead. This is purely visual: when+ // there is slack, range() is 0 so scroll stays 0 and every+ // scrollTo clamps to it; when content overflows, the slack+ // is <= 0 and the offset vanishes.+ val slack = size.height - scroll.contentHeightPx() * zoom.zoom+ translationY = -scroll.scrollPx * zoom.zoom + (slack / 2f).coerceAtLeast(0f) // Pivot on the top edge: keeps the first visible content anchored // to the top of the screen across zoom changes. transformOrigin = TransformOrigin(0.5f, 0f)
pdf/src/main/rust/src/annotations_part8.rs
diff --git a/pdf/src/main/rust/src/annotations_part8.rs b/pdf/src/main/rust/src/annotations_part8.rsindex 9badf0cc9c..633a954d52 100644--- a/pdf/src/main/rust/src/annotations_part8.rs+++ b/pdf/src/main/rust/src/annotations_part8.rs@@ -1,7 +1,7 @@ #[cfg(test)] mod synthesis_tests2 { use super::stamp_label;- use super::synthesis_tests::{annot, synth};+ use super::synthesis_tests::{annot, kinds, synth}; use crate::*; /// §12.5.4 Table 166: "/W ... If this value is 0, no border shall be drawn."
pdf/src/main/rust/src/content.rs
diff --git a/pdf/src/main/rust/src/content.rs b/pdf/src/main/rust/src/content.rsindex 50974d4613..199c4c6a8c 100644--- a/pdf/src/main/rust/src/content.rs+++ b/pdf/src/main/rust/src/content.rs@@ -177,12 +177,36 @@ fn nesting_is_too_deep(data: &[u8], max: u32) -> bool { /// Strict parse first, lenient tokenizer only if that fails, yields nothing, or is /// unsafe to attempt at all.+///+/// A strict parse that kept a `BI` without its image stream also counts as a+/// failure: lopdf 0.45's `inline_image_impl` skips any inline image it cannot+/// fully decode — an abbreviated `/CS /G`, any `/F` filter, a missing `/BPC` —+/// and still reports success with a bare operand-less `BI`. The interpreter+/// renders a `BI` only from an attached stream operand, so that "success" is a+/// silently dropped image, while the lenient tokenizer decodes all of those+/// shapes. Falling back keeps the image; both callers (`page_operations` and+/// `operations_from_bytes`) already treat `None` as "run lenient". pub(crate) fn strict_operations(bytes: &[u8]) -> Option<Vec<Operation>> { if nesting_is_too_deep(bytes, MAX_DEPTH) { return None; } match Content::decode(bytes) {- Ok(content) if !content.operations.is_empty() => Some(repair_d0_d1(content.operations)),+ Ok(content) if !content.operations.is_empty() => {+ let ops = repair_d0_d1(content.operations);+ // lopdf attaches the decoded image as a Stream operand; without one+ // the image was skipped and the lenient path must run instead.+ let dropped_image = ops.iter().any(|o| {+ o.operator == "BI"+ && !o+ .operands+ .iter()+ .any(|x| matches!(x, Object::Stream(_)))+ });+ if dropped_image {+ return None;+ }+ Some(ops)+ } _ => None, } }@@ -293,7 +317,7 @@ fn operations_from_bytes(bytes: &[u8]) -> Vec<Operation> { /// hand compressed data to the tokenizer to be parsed as operators. Our /// [`stream_data_with_doc`] handles the filter chain case-insensitively and yields /// nothing rather than ciphertext when every decoder fails.-fn page_content_bytes(doc: &Document, page_id: ObjectId) -> Vec<u8> {+pub(crate) fn page_content_bytes(doc: &Document, page_id: ObjectId) -> Vec<u8> { let mut out = Vec::new(); for id in doc.get_page_contents(page_id) { if let Ok(Object::Stream(s)) = doc.get_object(id) {
pdf/src/main/rust/src/content_part3.rs
diff --git a/pdf/src/main/rust/src/content_part3.rs b/pdf/src/main/rust/src/content_part3.rsindex 4da3cfbadc..23495c31cb 100644--- a/pdf/src/main/rust/src/content_part3.rs+++ b/pdf/src/main/rust/src/content_part3.rs@@ -381,10 +381,13 @@ mod tests { let (doc, page_id) = one_page_doc(&content); // Establish that this really is the P0 rather than a test that would pass- // anyway: lopdf must genuinely fail on this page.+ // anyway: the strict content parse must genuinely fail on this page (and,+ // since the BI fix, fail on the dropped image rather than succeed+ // without it). `get_and_decode_page_content` cannot establish this: it+ // only decodes the stream's own filters and never parses operators. assert!(- doc.get_and_decode_page_content(page_id).is_err(),- "precondition: lopdf is expected to reject this content stream"+ crate::content::strict_operations(&content).is_none(),+ "precondition: the strict content parse is expected to reject this page" ); let (ops, recovered) = page_operations(&doc, page_id);
pdf/src/main/rust/src/content_part4.rs
diff --git a/pdf/src/main/rust/src/content_part4.rs b/pdf/src/main/rust/src/content_part4.rsindex a43ee624d0..dea7daadb6 100644--- a/pdf/src/main/rust/src/content_part4.rs+++ b/pdf/src/main/rust/src/content_part4.rs@@ -60,9 +60,13 @@ mod tests_cont { content.extend_from_slice(b" EI\nQ 5 5 20 20 re f\n"); let stream = Stream::new(dictionary! { "Type" => "XObject", "Subtype" => "Form" }, content); + // lopdf's raw decoder succeeds here (it skips the undecodable image+ // and keeps the operators), so it cannot establish the P0. The strict+ // content parse — the path the app actually takes — must fail on the+ // dropped image instead of succeeding without it. assert!(- Content::decode(&stream.content).is_err(),- "precondition: lopdf is expected to reject this nested stream"+ crate::content::strict_operations(&stream.content).is_none(),+ "precondition: the strict content parse is expected to reject this nested stream" ); let ops = stream_operations(&doc, &stream);
pdf/src/main/rust/src/docedit_part4.rs
diff --git a/pdf/src/main/rust/src/docedit_part4.rs b/pdf/src/main/rust/src/docedit_part4.rsindex ea6449ef49..a290a7fef5 100644--- a/pdf/src/main/rust/src/docedit_part4.rs+++ b/pdf/src/main/rust/src/docedit_part4.rs@@ -9,7 +9,8 @@ mod redaction_tests_cont { /// the operation must refuse and leave the document exactly as it was. #[test] fn a_stream_only_the_lenient_tokenizer_can_read_is_not_redacted() {- // No /BPC, so lopdf's inline-image parser errors inside `cut(...)`.+ // No /BPC, so the strict content parse fails on the inline image and only+ // the lenient tokenizer can read this stream. let mut content = b"BT /F1 12 Tf 100 700 Td (secret) Tj ET\n".to_vec(); content.extend_from_slice(b"BI /W 2 /H 2 /CS /G ID "); content.extend_from_slice(&[0x00, 0x40, 0x80, 0xFF]);@@ -19,8 +20,11 @@ mod redaction_tests_cont { let reg = registry().lock().unwrap_or_else(|e| e.into_inner()); let doc = reg.get(&handle).expect("handle is registered"); assert!(- doc.get_and_decode_page_content(page_id).is_err(),- "precondition: lopdf is expected to reject this content stream"+ crate::content::strict_operations(&crate::content::page_content_bytes(+ doc, page_id+ ))+ .is_none(),+ "precondition: the strict content parse is expected to reject this stream" ); }
pdf/src/main/rust/src/geometry_part1.rs
diff --git a/pdf/src/main/rust/src/geometry_part1.rs b/pdf/src/main/rust/src/geometry_part1.rsindex 6424cd07c2..484d41fb94 100644--- a/pdf/src/main/rust/src/geometry_part1.rs+++ b/pdf/src/main/rust/src/geometry_part1.rs@@ -97,21 +97,41 @@ mod geometry_tests { ); let src = std::fs::read_to_string(path) .unwrap_or_else(|e| panic!("cannot read the page box's only consumer {path}: {e}"));- // `rawWidth.coerceAtMost(20000f)` and the same on height.- let bounds: Vec<f64> = src+ // `rawWidth.coerceAtMost(MAX_PAGE_DIM)` and the same on height: the+ // consumer hoisted the literal into a named constant, so resolve the+ // constant's value from the same file rather than matching a literal.+ // `private const val MAX_PAGE_DIM = 20000f`, with an optional comment.+ let max_page_dim: f64 = src .lines()- .filter(|l| l.contains("rawWidth") || l.contains("rawHeight"))- .filter_map(|l| l.split_once("coerceAtMost("))- .filter_map(|(_, rest)| rest.split(')').next())- .filter_map(|v| v.trim().trim_end_matches('f').parse::<f64>().ok())+ .find_map(|l| {+ let v = l.trim().strip_prefix("private const val MAX_PAGE_DIM = ")?;+ v.split_whitespace()+ .next()?+ .trim_end_matches('f')+ .parse()+ .ok()+ })+ .unwrap_or_else(|| panic!("{path} must declare `private const val MAX_PAGE_DIM = <n>f`"));+ // Both dimension clamps must go through the constant: a clamp arm that+ // stops mentioning it has drifted off the contract silently.+ let pinned: Vec<&str> = src+ .lines()+ .filter(|l| (l.contains("rawWidth") || l.contains("rawHeight")) && l.contains("coerceAtMost(")) .collect(); assert_eq!(- bounds.len(),+ pinned.len(), 2,- "expected a `coerceAtMost(<n>f)` on each of rawWidth and rawHeight in {path}; \- found {bounds:?}. If the consumer's clamp moved or was renamed, this contract \+ "expected a `coerceAtMost(...)` on each of rawWidth and rawHeight in {path}; \+ found {pinned:?}. If the consumer's clamp moved or was renamed, this contract \ needs re-pinning rather than deleting." );+ for l in &pinned {+ assert!(+ l.contains("coerceAtMost(MAX_PAGE_DIM)"),+ "{path} clamps a page dimension without MAX_PAGE_DIM: {l:?}."+ );+ }+ let bounds = [max_page_dim, max_page_dim]; for b in bounds { assert_eq!( b, super::MAX_PAGE_DIMENSION,
pdf/src/main/rust/src/interpret_part10.rs
diff --git a/pdf/src/main/rust/src/interpret_part10.rs b/pdf/src/main/rust/src/interpret_part10.rsindex 50114158ab..70fafd6bea 100644--- a/pdf/src/main/rust/src/interpret_part10.rs+++ b/pdf/src/main/rust/src/interpret_part10.rs@@ -230,7 +230,7 @@ mod refdiff_followup_tests_2 { let mut gs = GraphicsState::default(); gs.fill = red; let mut prims = Vec::new();- interpret_content(&doc, &ops, None, self.gs, &mut prims, 0, false);+ interpret_content(&doc, &ops, None, gs.clone(), &mut prims, 0, false); let fills: Vec<u32> = prims .iter() .filter_map(|p| match p {
pdf/src/main/rust/src/interpret_part9.rs
diff --git a/pdf/src/main/rust/src/interpret_part9.rs b/pdf/src/main/rust/src/interpret_part9.rsindex 318c5bbd19..3e99f7e929 100644--- a/pdf/src/main/rust/src/interpret_part9.rs+++ b/pdf/src/main/rust/src/interpret_part9.rs@@ -396,7 +396,7 @@ mod refdiff_followup_tests { let mut d0_glyph = glyph.clone(); d0_glyph[0] = op("d0", vec![0.into(), 0.into()]); let mut prims = Vec::new();- interpret_content(&doc, &d0_glyph, None, self.gs, &mut prims, 0, false);+ interpret_content(&doc, &d0_glyph, None, gs.clone(), &mut prims, 0, false); assert!( prims.iter().any(|p| matches!(p, Prim::Fill { argb, .. } if *argb == rgb_to_argb(1.0, 1.0, 1.0))), "d0 imposes no colour rule, so `1 1 1 rg` must take effect"
pdf/src/main/rust/src/objects.rs
diff --git a/pdf/src/main/rust/src/objects.rs b/pdf/src/main/rust/src/objects.rsindex 2e03327fa0..633a5c6d84 100644--- a/pdf/src/main/rust/src/objects.rs+++ b/pdf/src/main/rust/src/objects.rs@@ -21,32 +21,51 @@ pub(crate) fn deref<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a Object /// `/Filter` (lopdf's `decompressed_content` errors instead of returning raw). /// This version is legacy without Document context (used for ToUnicode cmap and font files). pub(crate) fn stream_data(s: &lopdf::Stream) -> Vec<u8> {- match s.decompressed_content() {- Ok(d) => d,- // With no /Filter the content is already plaintext and lopdf errors rather than- // returning it, so the raw fallback is correct. With a /Filter present a failure- // means we could not decode, and handing back the still-ENCODED bytes fed binary- // garbage to the cmap/font parser.- Err(_) if s.dict.get(b"Filter").is_err() => s.content.clone(),- Err(_) => {- // lopdf implements only Flate, LZW and ASCII85 (object.rs:690-693) and- // returns Unimplemented for anything else, so an ASCIIHex- or- // RunLength-encoded ToUnicode CMap or embedded font file decoded to- // nothing at all — silently no text, or no glyphs. `filters` implements- // both, so retry through our own chain.- //- // With no Document only DIRECT filter entries resolve. An indirect- // /Filter leaves `specs` empty, and `decode_stream_content` treats an- // empty chain as "already plaintext" and would hand back the still-- // ENCODED bytes, so that case must yield nothing instead.- let doc = Document::new();- let specs = filters::filter_specs_from_dict(&doc, &s.dict);- if specs.is_empty() {- return Vec::new();- }- decode_stream_content(&doc, &s.dict, &s.content)+ // With no /Filter the content is already plaintext and lopdf errors rather+ // than returning it, so the raw fallback is correct here and only here.+ if s.dict.get(b"Filter").is_err() {+ return s.content.clone();+ }+ // A /Filter is present. lopdf's `decompressed_content` can no longer be+ // trusted as the first resort: when the filter list itself cannot be+ // resolved (an indirect reference, a wrong-typed entry) it returns+ // Ok(content) — the still-ENCODED bytes — and for implemented filters it+ // has the predictor-blindness and ASCII85 hazards documented on+ // `decode_stream_content`. Resolve through our own chain instead, which+ // handles every direct filter we implement (including /DecodeParms+ // predictors) and yields nothing for unresolvable or unknown ones.+ //+ // With no Document only DIRECT filter entries resolve. An indirect /Filter+ // leaves `specs` empty, and must yield nothing: returning the raw bytes+ // would feed binary garbage to the cmap/font parser.+ let doc = Document::new();+ let specs = filters::filter_specs_from_dict(&doc, &s.dict);+ if specs.is_empty() {+ return Vec::new();+ }+ if let Some(d) = filters::decode_stream_chain(s.content.clone(), &specs, &doc) {+ return d;+ }+ // Our chain failed. lopdf as a last resort, and only for a filter we do+ // not implement (Unknown): on a filter we DO implement it already judged+ // the bytes corrupt, and it cannot do better than garbage. (Its Ok here is+ // genuine: `specs` is non-empty, so the filter list resolved to direct+ // names lopdf can see; an Unknown name makes it Err, which falls through+ // to nothing below.) Skipped whenever a predictor is involved, exactly as+ // in `decode_stream_content`: lopdf cannot see an indirect or array-form+ // /DecodeParms and would return predictor-garbled bytes as success.+ let has_unknown = specs+ .iter()+ .any(|(k, _)| matches!(k, filters::FilterKind::Unknown(_)));+ if has_unknown && !wants_predictor(&doc, &s.dict) {+ if let Ok(d) = s.decompressed_content() {+ return d; } }+ // Every decoder failed. Returning the raw bytes here handed the+ // still-ENCODED bytes to the cmap/font parser as if they were plaintext —+ // visible as missing text or missing glyphs. Render nothing instead.+ Vec::new() } /// Extended decoder that uses Document context to handle filter chains case-insensitively,@@ -149,18 +168,18 @@ pub(crate) fn stream_data_with_doc(doc: &Document, s: &Stream) -> Vec<u8> { mod tests { use super::*; - /// lopdf's `decompressed_content` handles only Flate/LZW/ASCII85, so these two- /// filters used to yield an empty ToUnicode CMap or font file — silently no text.+ /// lopdf 0.45 implements ASCIIHexDecode and RunLengthDecode itself, so these+ /// filters no longer reach the fallback through lopdf's failure — but+ /// `stream_data` decodes direct filters through our own chain first, which+ /// is what this exercises. (An ASCIIHex- or RunLength-encoded ToUnicode+ /// CMap or embedded font file that decoded to nothing was silently no+ /// text, or no glyphs.) #[test] fn stream_data_decodes_filters_lopdf_does_not_implement() { let s = Stream::new( dictionary! { "Filter" => "ASCIIHexDecode" }, b"48656C6C6F>".to_vec(), );- assert!(- s.decompressed_content().is_err(),- "precondition: lopdf is expected not to implement ASCIIHexDecode"- ); assert_eq!(stream_data(&s), b"Hello".to_vec()); // RunLength: literal run of 1 byte (0x00 => copy 1), then EOD (128).@@ -168,7 +187,6 @@ mod tests { dictionary! { "Filter" => "RunLengthDecode" }, vec![0x00, 0xAB, 128], );- assert!(s.decompressed_content().is_err(), "precondition"); assert_eq!(stream_data(&s), vec![0xAB]); }
pdf/src/main/rust/src/reference_diff_tests_part2.rs
diff --git a/pdf/src/main/rust/src/reference_diff_tests_part2.rs b/pdf/src/main/rust/src/reference_diff_tests_part2.rsindex 10349a6a18..0fce6af0c4 100644--- a/pdf/src/main/rust/src/reference_diff_tests_part2.rs+++ b/pdf/src/main/rust/src/reference_diff_tests_part2.rs@@ -78,7 +78,7 @@ fn clip_contours(r: &Rast, pts: &[(f32, f32)], path_ops: &Option<Vec<PathOp>>) - // --------------------------------------------------------------------------- fn hayro_rgb8(bytes: &[u8], scale: f32) -> (usize, usize, Vec<[u8; 3]>) {- use hayro::{render, RenderCache, RenderSettings};+ use hayro::{render, PixmapSettings, RenderCache, RenderSettings}; use hayro::hayro_interpret::InterpreterSettings; use hayro::hayro_syntax::Pdf; use hayro::vello_cpu::color::palette::css::WHITE;@@ -92,7 +92,8 @@ fn hayro_rgb8(bytes: &[u8], scale: f32) -> (usize, usize, Vec<[u8; 3]>) { &pages[0], &cache, &settings,- &RenderSettings { x_scale: scale, y_scale: scale, bg_color: WHITE, ..Default::default() },+ &RenderSettings::default(),+ &PixmapSettings { x_scale: scale, y_scale: scale, bg_color: WHITE, ..Default::default() }, ); let (w, h) = (pixmap.width() as usize, pixmap.height() as usize); let rgb = pixmap
pdf/src/main/rust/src/wire_part1.rs
diff --git a/pdf/src/main/rust/src/wire_part1.rs b/pdf/src/main/rust/src/wire_part1.rsindex 0f37c5585e..aa67af9243 100644--- a/pdf/src/main/rust/src/wire_part1.rs+++ b/pdf/src/main/rust/src/wire_part1.rs@@ -220,6 +220,18 @@ mod tests { .unwrap_or_else(|e| panic!("cannot read the wire format's only consumer {path}: {e}")) } + /// The image budgets moved out of the parser into `SafePdfImages` in the+ /// file split, so the budget assertion below reads them there rather than+ /// from the parser.+ fn kotlin_images_src() -> String {+ let path = concat!(+ env!("CARGO_MANIFEST_DIR"),+ "/../java/com/vayunmathur/pdf/util/SafePdfImages.kt"+ );+ std::fs::read_to_string(path)+ .unwrap_or_else(|e| panic!("cannot read the image-budget owner {path}: {e}"))+ }+ /// The text following `prefix` on the first line that starts with it. fn kotlin_decl(src: &str, prefix: &str) -> String { src.lines()@@ -247,7 +259,7 @@ mod tests { /// would train the next person to widen the assertion rather than think about it. #[test] fn the_kotlin_image_budgets_are_not_below_the_rust_ones() {- let src = kotlin_parser_src();+ let src = kotlin_images_src(); let int_after = |prefix: &str| -> u64 { kotlin_decl(&src, prefix) .split_whitespace()@@ -259,7 +271,7 @@ mod tests { let kotlin_dim = int_after("private const val MAX_IMAGE_DIM: Int = "); assert!( kotlin_pixels >= crate::MAX_IMAGE_PIXELS as u64,- "SafePdfParser.kt caps images at {kotlin_pixels} pixels but images.rs decimates \+ "SafePdfImages.kt caps images at {kotlin_pixels} pixels but images.rs decimates \ only to {}, so every image between the two is produced, passes every Rust \ guard, and is then dropped by the parser with no diagnostic on either side. \ Raise the Kotlin constant, or lower MAX_IMAGE_PIXELS in graphics_state.rs.",@@ -267,7 +279,7 @@ mod tests { ); assert!( kotlin_dim >= crate::MAX_IMAGE_DIM as u64,- "SafePdfParser.kt refuses images wider or taller than {kotlin_dim} but images.rs \+ "SafePdfImages.kt refuses images wider or taller than {kotlin_dim} but images.rs \ admits up to {}, so an image between the two is emitted and silently dropped.", crate::MAX_IMAGE_DIM );