pdf_render: fix clippy warnings
- Commit
4d49d92fc25aa590a07f4e88bf9df59b5378942f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 14:14 UTC (18 days ago)
- Parents
28efeb8
Fix every cargo check and clippy warning reported for the pdf_render crate (136 lib + 60 additional test-target warnings at baseline, on top of the 13 check warnings), so that cargo check -p pdf_render --all-targets and cargo clippy -p pdf_render --all-targets now report zero crate warnings. What changed: - Started from cargo clippy --fix (let-unit-value, unused imports, redundant closures/guards, question-mark and similar mechanical lints) and reviewed the result; the remaining warnings were fixed by hand. - Deprecated JNI accessors replaced with the jni 0.22 array methods (JPrimitiveArray::len, JFloatArray::get_region), keeping the same length caps and exception handling. - too-many-arguments functions now take grouped inputs: AuthParams for password authentication, HandlerCtx for the content-operator handlers, SoftMaskWrap/PatternFill/ PatternStroke/TilingPattern for pattern and soft-mask painting, plus rect/point/size tuples for the annotation, shading, Type 1, image and JNI helper functions. Call sites (including the Kotlin-facing JNI wrappers, whose exported signatures are unchanged) updated accordingly. - Dead code removed: the never-constructed LzwParams, the unread Type3Info bbox field and its parsing, and three unused test helpers. Type-complexity warnings resolved with named type aliases. - MSRV-incompatible APIs (is_multiple_of, floor_char_boundary) rewritten in their pre-existing forms; manual checked divisions, range-index loops, same-item pushes, sort_by, constant assertions and doc-list formatting fixed in place without changing behaviour. One item-scoped allow remains: EncryptAlgo in decrypt_part1 carries #[allow(dead_code)] because only Aes128 is selected by the production save path while Rc4_128 and Aes256 are constructed by the encrypt/decrypt round-trip tests, which the non-test library build cannot see. No crate- or module-level allows were added, and no code outside pdf/src/main/rust was touched. Verification: - cargo check -p pdf_render --all-targets: 0 crate warnings - cargo clippy -p pdf_render --all-targets: 0 crate warnings - cargo test -p pdf_render: 597 passed, 0 failed, 20 ignored (including the Kotlin/Rust contract and reference-diff tests) - The only remaining lines are the pre-existing workspace 'profiles for the non root package will be ignored' notices from other packages, which are not crate warnings.
Diff
pdf/src/main/rust/src/annotations_part4.rs
diff --git a/pdf/src/main/rust/src/annotations_part4.rs b/pdf/src/main/rust/src/annotations_part4.rsindex a173d91d8b..ed316558a8 100644--- a/pdf/src/main/rust/src/annotations_part4.rs+++ b/pdf/src/main/rust/src/annotations_part4.rs@@ -139,14 +139,15 @@ pub(crate) fn add_note(handle: i64, page_index: i32, x: f64, y: f64, argb: u32, pub(crate) fn add_callout( handle: i64, page_index: i32,- ax: f64,- ay: f64,- bx: f64,- by: f64,+ // Leader anchor and text-box corner, in editor coordinates.+ anchor: (f64, f64),+ box_pt: (f64, f64), argb: u32, size: f64, text: &str, ) -> Option<i64> {+ let (ax, ay) = anchor;+ let (bx, by) = box_pt; let mut reg = registry().lock().unwrap_or_else(|e| e.into_inner()); let doc = reg.get_mut(&handle)?; let bw = 160.0;
pdf/src/main/rust/src/annotations_part7.rs
diff --git a/pdf/src/main/rust/src/annotations_part7.rs b/pdf/src/main/rust/src/annotations_part7.rsindex c550b08185..e8a47485bc 100644--- a/pdf/src/main/rust/src/annotations_part7.rs+++ b/pdf/src/main/rust/src/annotations_part7.rs@@ -1,6 +1,6 @@ #[cfg(test)] mod synthesis_tests {- use super::stamp_label;+ use crate::*; // A page index arrives from the JNI boundary as a `jint` and is not validated there,
pdf/src/main/rust/src/cff_part1.rs
diff --git a/pdf/src/main/rust/src/cff_part1.rs b/pdf/src/main/rust/src/cff_part1.rsindex e7a76789f5..0b0d0a807d 100644--- a/pdf/src/main/rust/src/cff_part1.rs+++ b/pdf/src/main/rust/src/cff_part1.rs@@ -357,7 +357,7 @@ mod tests { /// An INDEX whose `count` entries are all empty, with 1-byte offsets. fn empty_index(count: usize) -> Vec<u8> { let mut d = vec![(count >> 8) as u8, count as u8, 1u8];- d.extend(std::iter::repeat(1u8).take(count + 1));+ d.extend(std::iter::repeat_n(1u8, count + 1)); d }
pdf/src/main/rust/src/color_part1.rs
diff --git a/pdf/src/main/rust/src/color_part1.rs b/pdf/src/main/rust/src/color_part1.rsindex aa68ba2e55..2150f4ec62 100644--- a/pdf/src/main/rust/src/color_part1.rs+++ b/pdf/src/main/rust/src/color_part1.rs@@ -31,7 +31,7 @@ fn adapt_to_d65(x: f64, y: f64, z: f64, src_white: [f64; 3]) -> (f64, f64, f64) (out[0], out[1], out[2]) } -pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<u32> {+pub(crate) fn eval_cs_to_rgb(_doc: &Document, kind: &CsKind, comps: &[f64], _cs_resources: &HashMap<Vec<u8>, ObjectId>) -> Option<u32> { match kind { CsKind::DeviceGray => { let v = comps.first().copied().unwrap_or(0.0);@@ -167,7 +167,7 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re CsKind::ICCBased { n, alt } => { // Use alt if present — already handles Separation/DeviceN alt may be device (fast path) if let Some(alt_kind) = alt {- if let Some(rgb) = eval_cs_to_rgb(doc, alt_kind, comps, cs_resources) {+ if let Some(rgb) = eval_cs_to_rgb(_doc, alt_kind, comps, _cs_resources) { return Some(rgb); } }@@ -200,7 +200,7 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re let (lo, hi) = ranges.get(i).copied().unwrap_or((0.0, 1.0)); lo + (*b as f64 / 255.0) * (hi - lo) }).collect();- eval_cs_to_rgb(doc, base, &comps_f, cs_resources)+ eval_cs_to_rgb(_doc, base, &comps_f, _cs_resources) } else { None }@@ -219,7 +219,7 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re // back instead. (audit-e owns making well-formed Type 2/3 functions // return the full /Range arity; this is the backstop, not the fix.) if alt_comps.len() >= cs_kind_ncomp(alt).max(1) as usize {- if let Some(rgb) = eval_cs_to_rgb(doc, alt, &alt_comps, cs_resources) {+ if let Some(rgb) = eval_cs_to_rgb(_doc, alt, &alt_comps, _cs_resources) { return Some(rgb); } }@@ -249,7 +249,7 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re // and plain black for a Gray alternate. Falling through to the // subtractive ramp below at least keeps the ink polarity right. if alt_comps.len() >= cs_kind_ncomp(alt).max(1) as usize {- if let Some(rgb) = eval_cs_to_rgb(doc, alt, &alt_comps, cs_resources) {+ if let Some(rgb) = eval_cs_to_rgb(_doc, alt, &alt_comps, _cs_resources) { return Some(rgb); } }
pdf/src/main/rust/src/crypto.rs
diff --git a/pdf/src/main/rust/src/crypto.rs b/pdf/src/main/rust/src/crypto.rsindex a5c5367101..cc92917112 100644--- a/pdf/src/main/rust/src/crypto.rs+++ b/pdf/src/main/rust/src/crypto.rs@@ -132,17 +132,25 @@ pub fn object_key(key: &[u8], num: u32, gen: u16, n: usize) -> Vec<u8> { hash[..len].to_vec() } +/// The `/Encrypt` dictionary values needed to authenticate a password:+/// the candidate password, the `/O` and `/U` entries, `/P`, the first+/// trailer `/ID` element, the key length in bytes, the handler revision+/// and the `/EncryptMetadata` flag.+pub struct AuthParams<'a> {+ pub pw: &'a [u8],+ pub o: &'a [u8],+ pub u: &'a [u8],+ pub p: i32,+ pub id0: &'a [u8],+ pub n: usize,+ pub rev: u8,+ pub encrypt_metadata: bool,+}+ /// Verify a password: returns the file key if it matches the `/U` entry.-pub fn authenticate(- pw: &[u8],- o: &[u8],- u: &[u8],- p: i32,- id0: &[u8],- n: usize,- rev: u8,- encrypt_metadata: bool,-) -> Option<Vec<u8>> {+pub fn authenticate(params: &AuthParams<'_>) -> Option<Vec<u8>> {+ let (pw, o, u, p, id0, n, rev, encrypt_metadata) =+ (params.pw, params.o, params.u, params.p, params.id0, params.n, params.rev, params.encrypt_metadata); let key = compute_key(pw, o, p, id0, n, rev, encrypt_metadata); let computed = compute_u(&key, id0, rev); let cmp_len = if rev == 2 { 32 } else { 16 };@@ -156,16 +164,9 @@ pub fn authenticate( /// Owner-password fallback for R2-R4: per PDF spec algorithm 5 reverse, /// try to decrypt O with owner password to recover user password, then /// authenticate. Returns file key if owner password valid.-pub fn authenticate_owner_fallback(- pw: &[u8],- o: &[u8],- u: &[u8],- p: i32,- id0: &[u8],- n: usize,- rev: u8,- encrypt_metadata: bool,-) -> Option<Vec<u8>> {+pub fn authenticate_owner_fallback(params: &AuthParams<'_>) -> Option<Vec<u8>> {+ let (pw, o, u, p, id0, n, rev, encrypt_metadata) =+ (params.pw, params.o, params.u, params.p, params.id0, params.n, params.rev, params.encrypt_metadata); // Derive owner key from owner pw let mut hash = md5(&pad_pw(pw)); if rev >= 3 {@@ -200,7 +201,7 @@ pub fn authenticate_owner_fallback( return Some(key_candidate); } // Also try using owner pw directly as user pw (owner may equal user)- authenticate(pw, o, u, p, id0, n, rev, encrypt_metadata)+ authenticate(params) } /// AES-256-CBC encrypt without padding, IV = zeros (used to build /UE and /OE).
pdf/src/main/rust/src/crypto_part1.rs
diff --git a/pdf/src/main/rust/src/crypto_part1.rs b/pdf/src/main/rust/src/crypto_part1.rsindex a118ae1fb2..5c05403399 100644--- a/pdf/src/main/rust/src/crypto_part1.rs+++ b/pdf/src/main/rust/src/crypto_part1.rs@@ -21,9 +21,9 @@ mod tests { let key = compute_key(b"", &o, p, id0, n, rev, true); let u = compute_u(&key, id0, rev); let got =- authenticate(b"", &o, &u, p, id0, n, rev, true).expect("empty user pw authenticates");+ authenticate(&AuthParams { pw: b"", o: &o, u: &u, p, id0, n, rev, encrypt_metadata: true }).expect("empty user pw authenticates"); assert_eq!(got, key);- assert!(authenticate(b"wrong", &o, &u, p, id0, n, rev, true).is_none());+ assert!(authenticate(&AuthParams { pw: b"wrong", o: &o, u: &u, p, id0, n, rev, encrypt_metadata: true }).is_none()); } #[test]
pdf/src/main/rust/src/decrypt.rs
diff --git a/pdf/src/main/rust/src/decrypt.rs b/pdf/src/main/rust/src/decrypt.rsindex 269eac8fc1..1eee134933 100644--- a/pdf/src/main/rust/src/decrypt.rs+++ b/pdf/src/main/rust/src/decrypt.rs@@ -48,13 +48,16 @@ pub(crate) fn crypt_object(obj: &mut Object, apply: &dyn Fn(&[u8]) -> Vec<u8>) { /// Apply `strings` to every string and `streams` to every stream body inside `obj`. ///+/// A byte transform applied to strings or stream bodies during (de)cryption.+type ByteTransform<'a> = &'a dyn Fn(&[u8]) -> Vec<u8>;+ /// §7.6.5 gives streams and strings SEPARATE crypt filters (`/StmF`, `/StrF`), and /// either may be `/Identity`, so the two cannot share one transform. `None` leaves /// that class of data untouched. fn crypt_object_split( obj: &mut Object,- strings: Option<&dyn Fn(&[u8]) -> Vec<u8>>,- streams: Option<&dyn Fn(&[u8]) -> Vec<u8>>,+ strings: Option<ByteTransform<'_>>,+ streams: Option<ByteTransform<'_>>, ) { match obj { Object::String(s, fmt) => {@@ -376,7 +379,7 @@ fn decrypt_in_place_fallback(doc: &mut Document, password: &[u8]) -> DecryptStat // which already checks U against key derived from pw (user). Owner-only docs use empty user pw that still validates, // but some require owner. // Attempt direct authenticate with given password (user path)- if let Some(k) = crypto::authenticate(password, &o, &u, p, &id0, n, r as u8, encrypt_metadata) {+ if let Some(k) = crypto::authenticate(&crypto::AuthParams { pw: password, o: &o, u: &u, p, id0: &id0, n, rev: r as u8, encrypt_metadata }) { k } else { // Owner path: if owner pw supplied, O entry contains user pw encrypted; try to brute cheap?@@ -387,7 +390,7 @@ fn decrypt_in_place_fallback(doc: &mut Document, password: &[u8]) -> DecryptStat // Try derive candidate owner key and then decrypt O to get user pw, then authenticate that user pw // Algorithm 3 reverse: owner pw -> okey -> user_pad = rc4 decypt O etc. // We'll delegate to helper.- if let Some(k) = crypto::authenticate_owner_fallback(password, &o, &u, p, &id0, n, r as u8, encrypt_metadata) {+ if let Some(k) = crypto::authenticate_owner_fallback(&crypto::AuthParams { pw: password, o: &o, u: &u, p, id0: &id0, n, rev: r as u8, encrypt_metadata }) { found = Some(k); } if let Some(k) = found {
pdf/src/main/rust/src/decrypt_part1.rs
diff --git a/pdf/src/main/rust/src/decrypt_part1.rs b/pdf/src/main/rust/src/decrypt_part1.rsindex 0b5ad27487..d3d9743e35 100644--- a/pdf/src/main/rust/src/decrypt_part1.rs+++ b/pdf/src/main/rust/src/decrypt_part1.rs@@ -9,15 +9,15 @@ /// a document with zero pages. fn expand_object_streams(doc: &mut Document) { let mut recovered: Vec<(ObjectId, Object)> = Vec::new();- for (_, object) in doc.objects.iter() {+ for object in doc.objects.values() { let Ok(stream) = object.as_stream() else { continue; }; if !stream.dict.has_type(b"ObjStm") { continue; }- let mut stream = stream.clone();- if let Ok(obj_stream) = lopdf::ObjectStream::new(&mut stream) {+ let stream = stream.clone();+ if let Ok(obj_stream) = lopdf::ObjectStream::new(&stream) { recovered.extend(obj_stream.objects); } }@@ -28,6 +28,11 @@ fn expand_object_streams(doc: &mut Document) { } /// Which standard-security-handler algorithm to write on save.+///+/// Only `Aes128` is selected by the production save path; `Rc4_128` and+/// `Aes256` are constructed by the encrypt/decrypt round-trip tests, which+/// the library (non-test) build cannot see.+#[allow(dead_code)] #[derive(Clone, Copy, PartialEq)] pub(crate) enum EncryptAlgo { /// RC4-128, revision 3 (V2/R3).
pdf/src/main/rust/src/filters.rs
diff --git a/pdf/src/main/rust/src/filters.rs b/pdf/src/main/rust/src/filters.rsindex 1829887832..2666a2ccb1 100644--- a/pdf/src/main/rust/src/filters.rs+++ b/pdf/src/main/rust/src/filters.rs@@ -46,16 +46,6 @@ impl Default for CcittParams { } } -#[derive(Clone, Debug)]-pub struct LzwParams {- pub early_change: bool,-}-impl Default for LzwParams {- fn default() -> Self {- Self { early_change: true }- }-}- fn num(obj: &Object) -> Option<f64> { match obj { Object::Integer(i) => Some(*i as f64),@@ -303,13 +293,10 @@ fn lzw_decode_std(data: &[u8], early_change: bool, limit: usize) -> Option<Vec<u Some(code) }; - loop {- let Some(code) = read_code(&mut bit_buf, &mut bits_in_buf, data, &mut data_pos, code_bits)- else {- // Stream ended without an EOD (257). Many producers omit it; returning None- // here discarded a fully-decoded stream and blanked the page.- break;- };+ // Stream ended without an EOD (257) ends the loop: many producers omit+ // it; returning None there discarded a fully-decoded stream and blanked+ // the page.+ while let Some(code) = read_code(&mut bit_buf, &mut bits_in_buf, data, &mut data_pos, code_bits) { if code == CLEAR { dict.truncate(258); code_bits = 9;
pdf/src/main/rust/src/filters_part1.rs
diff --git a/pdf/src/main/rust/src/filters_part1.rs b/pdf/src/main/rust/src/filters_part1.rsindex 2f9a9bf422..4f7bb6dd9b 100644--- a/pdf/src/main/rust/src/filters_part1.rs+++ b/pdf/src/main/rust/src/filters_part1.rs@@ -78,8 +78,7 @@ pub fn decode_ccitt(data: &[u8], w: u32, h: u32, params: &CcittParams) -> Option for (y, trans) in lines.into_iter().enumerate() { if y >= rows_us { break; } let row_off = y * row_bytes;- let mut cur_x = 0usize;- for pel in fax::decoder::pels(&trans, columns) {+ for (cur_x, pel) in fax::decoder::pels(&trans, columns).enumerate() { if cur_x >= cols_us { break; } let is_black = matches!(pel, fax::Color::Black); // Whether this pel's SAMPLE is a 1 bit, which /BlackIs1 selects.@@ -90,7 +89,6 @@ pub fn decode_ccitt(data: &[u8], w: u32, h: u32, params: &CcittParams) -> Option // one. Pels the decoder never reaches keep the white background. let b = &mut packed[row_off + cur_x / 8]; if bit_is_one { *b |= mask; } else { *b &= !mask; }- cur_x += 1; } } };@@ -148,14 +146,16 @@ pub fn decode_stream_chain(mut data: Vec<u8>, specs: &[(FilterKind, Option<Dicti FilterKind::RunLength => { data = decode_runlength(&data); } FilterKind::Flate => { // Handle PNG/TIFF predictors via parms if present- if let Some(d) = decode_flate(&data) { data = d; } else { return None; }+ {+ let d = decode_flate(&data)?; data = d; } data = apply_predictor(data, parms.as_ref(), doc); } FilterKind::Lzw => { let early = parms.as_ref().and_then(|d| { d.get(b"EarlyChange").ok().and_then(num).or_else(|| d.get(b"EarlyChange").ok().and_then(|o| deref(doc,o).and_then(num))) }).map(|v| v!=0.0).unwrap_or(true);- if let Some(d)=decode_lzw(&data, early) { data=d; } else { return None; }+ {+ let d = decode_lzw(&data, early)?; data=d; } // LZW supports the same PNG/TIFF predictors as Flate. data = apply_predictor(data, parms.as_ref(), doc); }
pdf/src/main/rust/src/fonts.rs
diff --git a/pdf/src/main/rust/src/fonts.rs b/pdf/src/main/rust/src/fonts.rsindex ddc6c95f5d..de4ef95538 100644--- a/pdf/src/main/rust/src/fonts.rs+++ b/pdf/src/main/rust/src/fonts.rs@@ -186,7 +186,7 @@ thread_local! { /// Populated only inside a [`FontCacheScope`]. `None` means "no cache", which /// is the safe default: an entry cannot go stale if none is stored. static FONT_CACHE: std::cell::RefCell<Option<HashMap<ObjectId, (u64, FontInfo)>>> =- std::cell::RefCell::new(None);+ const { std::cell::RefCell::new(None) }; } /// Enables the [`FontInfo`] cache for the lifetime of the guard.@@ -223,6 +223,7 @@ thread_local! { /// * the id paired with the font dictionary itself — shallow equality misses two /// documents whose font dicts are byte-identical but whose indirect TARGETS differ, /// the same `/Widths 7 0 R` naming different arrays.+/// /// Resolving through the references closes both. /// /// It is still a *complete* key only while the document is not mutated. That is precisely
pdf/src/main/rust/src/fonts_part5.rs
diff --git a/pdf/src/main/rust/src/fonts_part5.rs b/pdf/src/main/rust/src/fonts_part5.rsindex 5a45b4420c..949f8e533f 100644--- a/pdf/src/main/rust/src/fonts_part5.rs+++ b/pdf/src/main/rust/src/fonts_part5.rs@@ -27,7 +27,7 @@ mod encoding_priority_tests { let (c1, c2) = (52845u16, 22719u16); let mut r = seed; let mut out = Vec::new();- for &p in std::iter::repeat(&0u8).take(lead).chain(plain) {+ for &p in std::iter::repeat_n(&0u8, lead).chain(plain) { let c = p ^ (r >> 8) as u8; r = (c as u16).wrapping_add(r).wrapping_mul(c1).wrapping_add(c2); out.push(c);
pdf/src/main/rust/src/functions_part1.rs
diff --git a/pdf/src/main/rust/src/functions_part1.rs b/pdf/src/main/rust/src/functions_part1.rsindex b139086c00..3b7e7e69fb 100644--- a/pdf/src/main/rust/src/functions_part1.rs+++ b/pdf/src/main/rust/src/functions_part1.rs@@ -62,7 +62,7 @@ impl PdfFunction { if size.len() > MAX_SAMPLED_INPUTS || range.len() > MAX_FN_OUTPUTS { return None; }- if size.iter().any(|s| *s == 0) {+ if size.contains(&0) { return None; } let n_in = size.len();
pdf/src/main/rust/src/geometry.rs
diff --git a/pdf/src/main/rust/src/geometry.rs b/pdf/src/main/rust/src/geometry.rsindex a71567042b..8678d7caa2 100644--- a/pdf/src/main/rust/src/geometry.rs+++ b/pdf/src/main/rust/src/geometry.rs@@ -40,9 +40,9 @@ pub(crate) fn inherited<'a>(doc: &'a Document, page_id: ObjectId, key: &[u8]) -> if let Ok(obj) = dict.get(key) { return Some(obj); }- match dict.get(b"Parent").ok().and_then(|o| o.as_reference().ok()) {- Some(parent) => current = parent,- None => return None,+ {+ let parent = dict.get(b"Parent").ok().and_then(|o| o.as_reference().ok())?;+ current = parent } } None
pdf/src/main/rust/src/golden_tests.rs
diff --git a/pdf/src/main/rust/src/golden_tests.rs b/pdf/src/main/rust/src/golden_tests.rsindex 37f72fc9de..f3460308df 100644--- a/pdf/src/main/rust/src/golden_tests.rs+++ b/pdf/src/main/rust/src/golden_tests.rs@@ -198,7 +198,7 @@ fn polygon_area(pts: &[(f32, f32)]) -> f64 { } /// A soft mask carrying a `/TR` must still produce a well-formed bracket. Pinned-+/// /// Build a page whose content is wrapped in `BDC /OC`, with the OCG switched OFF /// via `/OCProperties /D /OFF`. `inner` is spliced inside the hidden region and /// `after` follows the closing `EMC`.
pdf/src/main/rust/src/golden_tests_part2.rs
diff --git a/pdf/src/main/rust/src/golden_tests_part2.rs b/pdf/src/main/rust/src/golden_tests_part2.rsindex c54d39a71f..817aa8ffc3 100644--- a/pdf/src/main/rust/src/golden_tests_part2.rs+++ b/pdf/src/main/rust/src/golden_tests_part2.rs@@ -193,10 +193,10 @@ fn stencil_image_mask_paints_where_the_sample_bit_is_zero() { let img = extract_image(&doc, &stream, 0xFF00_FF00, &no_cs()).expect("stencil must decode"); assert_eq!((img.w, img.h), (8, 1)); let a = alphas(&img);- for x in 0..8 {+ for (x, alpha) in a.iter().enumerate().take(8) { let bit = (0b1010_1010u8 >> (7 - x)) & 1; let want = if bit == 0 { 255 } else { 0 };- assert_eq!(a[x], want, "x={x}: sample bit {bit} must give alpha {want}");+ assert_eq!(*alpha, want, "x={x}: sample bit {bit} must give alpha {want}"); } // The painted pixels carry the fill colour, not black. let px = &img.data[4..8];@@ -227,7 +227,7 @@ fn stencil_image_mask_decode_one_zero_inverts_exactly_once() { "x={x}: /Decode [1 0] must flip coverage, got {} both ways", plain[x] ); }- assert!(plain.iter().any(|&v| v == 255) && inv.iter().any(|&v| v == 255), "both must paint something");+ assert!(plain.contains(&255) && inv.contains(&255), "both must paint something"); } /// §8.9.5.4: an `/SMask` sample IS the alpha, so sample 0 is transparent.
pdf/src/main/rust/src/golden_tests_part4.rs
diff --git a/pdf/src/main/rust/src/golden_tests_part4.rs b/pdf/src/main/rust/src/golden_tests_part4.rsindex c53b88c81d..dd3d2a4238 100644--- a/pdf/src/main/rust/src/golden_tests_part4.rs+++ b/pdf/src/main/rust/src/golden_tests_part4.rs@@ -233,10 +233,7 @@ fn tiling_pattern_with_a_small_step_covers_the_whole_region() { let pid = tiling_pattern(&mut doc, 10.0, 10.0); let region = fill_region(0.0, 0.0, 200.0, 200.0); let mut prims = Vec::new();- paint_pattern_fill(- &doc, pid, ®ion, false, &IDENTITY, 0xFF00_0000, 1.0, BlendMode::Normal,- &HashMap::new(), &mut prims, 0, 0,- );+ paint_pattern_fill(PatternFill { doc: &doc, pattern_id: pid, polys: ®ion, even_odd: false, pattern_base_ctm: &IDENTITY, base_argb: 0xFF00_0000, alpha_fill: 1.0, blend: BlendMode::Normal, cs_resources: &HashMap::new(), prims: &mut prims, depth: 0, clip_depth: 0 }); assert!( prims.iter().any(is_ink), "the pattern must paint something at all"@@ -260,10 +257,7 @@ fn tiling_pattern_with_a_negative_step_still_paints() { let pid = tiling_pattern(&mut doc, -10.0, -10.0); let region = fill_region(0.0, 0.0, 100.0, 100.0); let mut prims = Vec::new();- paint_pattern_fill(- &doc, pid, ®ion, false, &IDENTITY, 0xFF00_0000, 1.0, BlendMode::Normal,- &HashMap::new(), &mut prims, 0, 0,- );+ paint_pattern_fill(PatternFill { doc: &doc, pattern_id: pid, polys: ®ion, even_odd: false, pattern_base_ctm: &IDENTITY, base_argb: 0xFF00_0000, alpha_fill: 1.0, blend: BlendMode::Normal, cs_resources: &HashMap::new(), prims: &mut prims, depth: 0, clip_depth: 0 }); assert!( prims.iter().any(is_ink), "a negative /XStep must tile by its magnitude, not paint nothing"
pdf/src/main/rust/src/golden_tests_part5.rs
diff --git a/pdf/src/main/rust/src/golden_tests_part5.rs b/pdf/src/main/rust/src/golden_tests_part5.rsindex 8673f698d9..16df52f970 100644--- a/pdf/src/main/rust/src/golden_tests_part5.rs+++ b/pdf/src/main/rust/src/golden_tests_part5.rs@@ -285,10 +285,7 @@ fn tiling_pattern_cell_raster_is_not_vertically_flipped() { )); let region = fill_region(0.0, 0.0, 100.0, 100.0); let mut prims = Vec::new();- paint_pattern_fill(- &doc, pid, ®ion, false, &IDENTITY, 0xFF00_0000, 1.0, BlendMode::Normal,- &HashMap::new(), &mut prims, 0, 0,- );+ paint_pattern_fill(PatternFill { doc: &doc, pattern_id: pid, polys: ®ion, even_odd: false, pattern_base_ctm: &IDENTITY, base_argb: 0xFF00_0000, alpha_fill: 1.0, blend: BlendMode::Normal, cs_resources: &HashMap::new(), prims: &mut prims, depth: 0, clip_depth: 0 }); // The periodic path emits one ImageTiled cell raster; the per-tile path emits // Fills. Both are valid representations, so assert whichever appeared.
pdf/src/main/rust/src/golden_tests_part6.rs
diff --git a/pdf/src/main/rust/src/golden_tests_part6.rs b/pdf/src/main/rust/src/golden_tests_part6.rsindex 30648f36f7..c14d8ca2b8 100644--- a/pdf/src/main/rust/src/golden_tests_part6.rs+++ b/pdf/src/main/rust/src/golden_tests_part6.rs@@ -145,13 +145,14 @@ fn content_beyond_the_caps_truncates_to_a_valid_page() { // For the simplest content, one `re f` pair is 2 operators and 1 prim, so the // operator cap must leave room for MAX_PRIMITIVES prims or it binds first and // MAX_PRIMITIVES becomes unreachable.- assert!(- MAX_CONTENT_OPS >= 2 * MAX_PRIMITIVES,- "cap ordering is inverted: MAX_CONTENT_OPS ({MAX_CONTENT_OPS}) must leave \- room for MAX_PRIMITIVES ({MAX_PRIMITIVES}) prims at 2 operators each, or \- the operator cap binds first and MAX_PRIMITIVES is dead code — which also \- makes any larger consumer-side bound unreachable"- );+ const {+ assert!(+ MAX_CONTENT_OPS >= 2 * MAX_PRIMITIVES,+ "cap ordering is inverted: MAX_CONTENT_OPS must leave room for \+ MAX_PRIMITIVES prims at 2 operators each, or the operator cap \+ binds first and MAX_PRIMITIVES is dead code"+ )+ }; let mut doc = Document::with_version("1.5"); let ceiling = (MAX_CONTENT_OPS / 2).min(MAX_PRIMITIVES);
pdf/src/main/rust/src/golden_tests_part7.rs
diff --git a/pdf/src/main/rust/src/golden_tests_part7.rs b/pdf/src/main/rust/src/golden_tests_part7.rsindex 1a8bea0810..a2d67f7198 100644--- a/pdf/src/main/rust/src/golden_tests_part7.rs+++ b/pdf/src/main/rust/src/golden_tests_part7.rs@@ -160,10 +160,7 @@ fn inline_image_inside_a_tiling_pattern_cell_keeps_the_rest_of_the_cell() { )); let region = fill_region(0.0, 0.0, 100.0, 100.0); let mut prims = Vec::new();- paint_pattern_fill(- &doc, pid, ®ion, false, &IDENTITY, 0xFF00_0000, 1.0, BlendMode::Normal,- &HashMap::new(), &mut prims, 0, 0,- );+ paint_pattern_fill(PatternFill { doc: &doc, pattern_id: pid, polys: ®ion, even_odd: false, pattern_base_ctm: &IDENTITY, base_argb: 0xFF00_0000, alpha_fill: 1.0, blend: BlendMode::Normal, cs_resources: &HashMap::new(), prims: &mut prims, depth: 0, clip_depth: 0 }); let inked = prims.iter().filter(|p| is_ink(p)).count(); assert!( inked > 4,
pdf/src/main/rust/src/images_part1.rs
diff --git a/pdf/src/main/rust/src/images_part1.rs b/pdf/src/main/rust/src/images_part1.rsindex d1e3c52cd7..db9521158a 100644--- a/pdf/src/main/rust/src/images_part1.rs+++ b/pdf/src/main/rust/src/images_part1.rs@@ -143,11 +143,12 @@ fn image_samples_to_rgba( dict: &lopdf::Dictionary, cs_resources: &HashMap<Vec<u8>, ObjectId>, decoded_comps: &[u8],- w: usize,- h: usize,+ // (width, height) in samples+ wh: (usize, usize), ncomp: usize, bpc: u32, ) -> Vec<u8> {+ let (w, h) = wh; let mut rgba = vec![0u8; w * h * 4]; let cs_kind = dict .get(b"ColorSpace")
pdf/src/main/rust/src/images_part12.rs
diff --git a/pdf/src/main/rust/src/images_part12.rs b/pdf/src/main/rust/src/images_part12.rsindex 84d78b1eef..31a39cfd30 100644--- a/pdf/src/main/rust/src/images_part12.rs+++ b/pdf/src/main/rust/src/images_part12.rs@@ -24,7 +24,7 @@ mod mask_tests3 { // One 8-bpc sample of 255. With the default decode that is index 255, clamped to // hival 3 -> blue. let plain = dictionary! { "ColorSpace" => "Cs", "BitsPerComponent" => 8 };- let out = image_samples_to_rgba(&doc, &plain, &res, &[255u8], 1, 1, 1, 8);+ let out = image_samples_to_rgba(&doc, &plain, &res, &[255u8], (1, 1), 1, 8); assert_eq!(&out[0..3], &[0, 0, 255], "default decode clamps to hival -> blue"); // /Decode [0 1] maps sample 0..255 onto index 0..1, so 255 -> index 1 -> RED.@@ -33,10 +33,10 @@ mod mask_tests3 { "BitsPerComponent" => 8, "Decode" => vec![0.into(), 1.into()], };- let out = image_samples_to_rgba(&doc, &decoded, &res, &[255u8], 1, 1, 1, 8);+ let out = image_samples_to_rgba(&doc, &decoded, &res, &[255u8], (1, 1), 1, 8); assert_eq!(&out[0..3], &[255, 0, 0], "/Decode [0 1] remaps 255 to index 1 -> red"); // And the low end still maps to index 0.- let out = image_samples_to_rgba(&doc, &decoded, &res, &[0u8], 1, 1, 1, 8);+ let out = image_samples_to_rgba(&doc, &decoded, &res, &[0u8], (1, 1), 1, 8); assert_eq!(&out[0..3], &[0, 0, 0], "sample 0 stays index 0 -> black"); }
pdf/src/main/rust/src/images_part15.rs
diff --git a/pdf/src/main/rust/src/images_part15.rs b/pdf/src/main/rust/src/images_part15.rsindex b1c3c26f57..962e0dbfd9 100644--- a/pdf/src/main/rust/src/images_part15.rs+++ b/pdf/src/main/rust/src/images_part15.rs@@ -191,7 +191,7 @@ mod dct_decode_tests { "ColorSpace" => "DeviceGray", }; // Four pixels' worth of raster, one pixel's worth of samples.- let rgba = image_samples_to_rgba(&doc, &dict, &HashMap::new(), &[0x40u8], 2, 2, 1, 8);+ let rgba = image_samples_to_rgba(&doc, &dict, &HashMap::new(), &[0x40u8], (2, 2), 1, 8); assert_eq!(rgba.len(), 16); assert_eq!(rgba[3], 255, "the covered pixel is opaque"); assert_eq!(&rgba[0..3], &[0x40, 0x40, 0x40]);@@ -303,11 +303,7 @@ mod pixel_budget_tests { fn a_ccitt_raster_over_the_pixel_budget_renders_decimated_instead_of_vanishing() { const COLS: usize = 20000; const ROWS: usize = 839;- assert!(- COLS * ROWS > MAX_IMAGE_PIXELS,- "fixture must cross the budget: {} vs {}",- COLS * ROWS, MAX_IMAGE_PIXELS- );+ const { assert!(COLS * ROWS > MAX_IMAGE_PIXELS, "fixture must cross the budget") }; // Packed at one bit per pixel this is only ~2.1 MB, which is the whole point. assert!(COLS.div_ceil(8) * ROWS < MAX_UNPACKED_SAMPLE_BYTES);
pdf/src/main/rust/src/images_part2.rs
diff --git a/pdf/src/main/rust/src/images_part2.rs b/pdf/src/main/rust/src/images_part2.rsindex 0fdf7a1b52..8503e404c7 100644--- a/pdf/src/main/rust/src/images_part2.rs+++ b/pdf/src/main/rust/src/images_part2.rs@@ -49,16 +49,10 @@ fn downscale_rgba(data: &[u8], w: u32, h: u32, max_dim: u32, smooth: bool) -> Op if cnt > 0 { // Un-premultiply: the output buffer stays straight-alpha, which is what // the Kotlin side's Bitmap.createBitmap(int[], ...) expects.- if a > 0 {- out[o] = (r / a) as u8;- out[o + 1] = (g / a) as u8;- out[o + 2] = (b / a) as u8;- } else {- out[o] = 0;- out[o + 1] = 0;- out[o + 2] = 0;- }- out[o + 3] = (a / cnt) as u8;+ out[o] = r.checked_div(a).unwrap_or(0) as u8;+ out[o + 1] = g.checked_div(a).unwrap_or(0) as u8;+ out[o + 2] = b.checked_div(a).unwrap_or(0) as u8;+ out[o + 3] = a.checked_div(cnt).unwrap_or(0) as u8; } } }@@ -184,7 +178,7 @@ fn jbig2_globals( if let Some(g) = specs .iter() .filter(|(k, _)| *k == filters::FilterKind::Jbig2)- .find_map(|(_, pd)| pd.as_ref().and_then(|d| from_parms(d)))+ .find_map(|(_, pd)| pd.as_ref().and_then(&from_parms)) { return Some(g); }@@ -198,7 +192,7 @@ fn jbig2_globals( Some(Object::Array(a)) => a .iter() .filter_map(|el| deref(doc, el).and_then(|o| o.as_dict().ok()))- .find_map(|d| from_parms(d)),+ .find_map(from_parms), _ => None, } }
pdf/src/main/rust/src/images_part3.rs
diff --git a/pdf/src/main/rust/src/images_part3.rs b/pdf/src/main/rust/src/images_part3.rsindex 9b3575c02b..62c32b84a5 100644--- a/pdf/src/main/rust/src/images_part3.rs+++ b/pdf/src/main/rust/src/images_part3.rs@@ -101,8 +101,8 @@ fn extract_image_inner(doc: &Document, stream: &lopdf::Stream, fill_argb: u32, c // channel is used at all; its default is 0, i.e. "ignore it". Clamp anything // out of range to the default rather than guessing. let smask_in_data = match dict.get(b"SMaskInData").ok().and_then(|o| deref(doc, o)).and_then(num) {- Some(v) if v == 1.0 => 1u8,- Some(v) if v == 2.0 => 2u8,+ Some(1.0) => 1u8,+ Some(2.0) => 2u8, _ => 0u8, }; // §7.4.9: "the value of ColorSpace shall override any colour space specified in@@ -468,7 +468,7 @@ fn extract_image_inner(doc: &Document, stream: &lopdf::Stream, fill_argb: u32, c image_warn!("image {}x{} over pixel budget: decimated by {} to {}x{}", w, h, step, out_w, out_h); } - let mut rgba = image_samples_to_rgba(doc, dict, cs_resources, &decoded_comps, dw, dh, ncomp as usize, bpc);+ let mut rgba = image_samples_to_rgba(doc, dict, cs_resources, &decoded_comps, (dw, dh), ncomp as usize, bpc); // Masks are resampled to the (possibly decimated) raster, not to /Width x /Height. let smask = read_smask(doc, dict, out_w, out_h);
pdf/src/main/rust/src/images_part4.rs
diff --git a/pdf/src/main/rust/src/images_part4.rs b/pdf/src/main/rust/src/images_part4.rsindex 933f8a7157..1cec8c7d61 100644--- a/pdf/src/main/rust/src/images_part4.rs+++ b/pdf/src/main/rust/src/images_part4.rs@@ -203,7 +203,7 @@ fn extract_inline_image_inner(doc: &Document, stream: &lopdf::Stream, fill_argb: // over everything below the last real scanline. The XObject stencil branch // defaults absent bytes to the no-paint value for exactly this reason; the // inline one reached the unpacker first and lost the distinction.- let rows_present = if src_row_bytes > 0 { samples.len() / src_row_bytes } else { 0 };+ let rows_present = samples.len().checked_div(src_row_bytes).unwrap_or(0); for (i, px) in rgba.chunks_exact_mut(4).enumerate() { if i / (w as usize) >= rows_present { continue;@@ -218,7 +218,7 @@ fn extract_inline_image_inner(doc: &Document, stream: &lopdf::Stream, fill_argb: } return Some(ImageData { w, h, format: 0, data: rgba }); }- let mut rgba = image_samples_to_rgba(doc, dict, cs_resources, &unpacked, w as usize, h as usize, ncomp as usize, bpc);+ let mut rgba = image_samples_to_rgba(doc, dict, cs_resources, &unpacked, (w as usize, h as usize), ncomp as usize, bpc); let smask = read_smask(doc, dict, w, h); apply_smask(&mut rgba, &smask); if let Some(ranges_raw) = read_color_key_ranges_raw(doc, dict) {
pdf/src/main/rust/src/images_part7.rs
diff --git a/pdf/src/main/rust/src/images_part7.rs b/pdf/src/main/rust/src/images_part7.rsindex 0f5d470de0..47878f6010 100644--- a/pdf/src/main/rust/src/images_part7.rs+++ b/pdf/src/main/rust/src/images_part7.rs@@ -157,11 +157,11 @@ pub(crate) fn rasterize_prims_to_rgba( continue; } let weight = 1.0 / SS as f32;- for px in xa.floor() as usize..(xb.ceil() as usize).min(w) {+ for (px, cov_px) in cov.iter_mut().enumerate().take((xb.ceil() as usize).min(w)).skip(xa.floor() as usize) { let l = xa.max(px as f64); let r = xb.min(px as f64 + 1.0); if r > l {- cov[px] += (r - l) as f32 * weight;+ *cov_px += (r - l) as f32 * weight; } } }@@ -171,8 +171,8 @@ pub(crate) fn rasterize_prims_to_rgba( ((argb >> 8) & 0xFF) as f64, (argb & 0xFF) as f64, );- for px in 0..w {- let a = alpha * (cov[px].clamp(0.0, 1.0) as f64);+ for (px, cov_px) in cov.iter().enumerate().take(w) {+ let a = alpha * (cov_px.clamp(0.0, 1.0) as f64); if a <= 0.0 { continue; }@@ -191,8 +191,8 @@ pub(crate) fn rasterize_prims_to_rgba( if a == 0 || a == 255 { continue; }- for ch in 0..3 {- px[ch] = ((px[ch] as u32 * 255) / a as u32).min(255) as u8;+ for ch in px.iter_mut().take(3) {+ *ch = ((*ch as u32 * 255) / a as u32).min(255) as u8; } } Some(acc)
pdf/src/main/rust/src/interpret.rs
diff --git a/pdf/src/main/rust/src/interpret.rs b/pdf/src/main/rust/src/interpret.rsindex 2b0e38352d..b04abf5349 100644--- a/pdf/src/main/rust/src/interpret.rs+++ b/pdf/src/main/rust/src/interpret.rs@@ -283,6 +283,18 @@ pub(crate) fn parse_dash_extgstate(doc: &Document, obj: &Object) -> (Vec<f64>, f } } +/// The shared context threaded through the per-operator handlers: the+/// document and resources being interpreted, the primitive sink, the+/// form/pattern recursion depth and whether only text is wanted (search+/// indexing rather than rendering).+pub(crate) struct HandlerCtx<'a> {+ pub doc: &'a Document,+ pub resources: Option<&'a lopdf::Dictionary>,+ pub prims: &'a mut Vec<Prim>,+ pub depth: u32,+ pub text_only: bool,+}+ include!("interpret_part1.rs"); include!("interpret_part2.rs"); include!("interpret_part3.rs");
pdf/src/main/rust/src/interpret_part1.rs
diff --git a/pdf/src/main/rust/src/interpret_part1.rs b/pdf/src/main/rust/src/interpret_part1.rsindex 2cd27ae066..f212e587b1 100644--- a/pdf/src/main/rust/src/interpret_part1.rs+++ b/pdf/src/main/rust/src/interpret_part1.rs@@ -161,10 +161,10 @@ pub(crate) fn interpret_content_seeded( match op.operator.as_str() { "q" | "Q" | "cm" | "w" | "J" | "j" | "M" | "i" | "d" | "gs" => st.handle_state_ops(op, o, doc, resources, prims, text_only), "W" | "W*" | "m" | "l" | "c" | "v" | "y" | "re" | "h" => st.handle_path_ops(op, o, doc, prims, text_only),- "S" | "s" | "f" | "F" | "f*" | "B" | "B*" | "b" | "b*" | "n" | "BI" => st.handle_paint_ops(op, o, doc, resources, prims, depth, text_only),- "Do" => st.handle_do_op(op, o, doc, resources, prims, depth, text_only),- "rg" | "RG" | "g" | "G" | "k" | "K" | "CS" | "cs" | "SC" | "sc" | "SCN" | "scn" | "sh" | "BMC" | "BDC" | "MP" | "DP" | "EMC" | "d0" | "d1" => st.handle_color_ops(op, o, doc, resources, prims, depth, text_only),- "BT" | "ET" | "Tf" | "TL" | "Tc" | "Tw" | "Tz" | "Ts" | "Tr" | "Td" | "TD" | "Tm" | "T*" | "Tj" | "'" | "\"" | "TJ" | "ri" | "BX" | "EX" | "EI" => st.handle_text_ops(op, o, doc, resources, prims, depth, text_only),+ "S" | "s" | "f" | "F" | "f*" | "B" | "B*" | "b" | "b*" | "n" | "BI" => st.handle_paint_ops(op, o, HandlerCtx { doc, resources, prims, depth, text_only }),+ "Do" => st.handle_do_op(op, o, HandlerCtx { doc, resources, prims, depth, text_only }),+ "rg" | "RG" | "g" | "G" | "k" | "K" | "CS" | "cs" | "SC" | "sc" | "SCN" | "scn" | "sh" | "BMC" | "BDC" | "MP" | "DP" | "EMC" | "d0" | "d1" => st.handle_color_ops(op, o, HandlerCtx { doc, resources, prims, depth, text_only }),+ "BT" | "ET" | "Tf" | "TL" | "Tc" | "Tw" | "Tz" | "Ts" | "Tr" | "Td" | "TD" | "Tm" | "T*" | "Tj" | "'" | "\"" | "TJ" | "ri" | "BX" | "EX" | "EI" => st.handle_text_ops(op, o, HandlerCtx { doc, resources, prims, depth, text_only }), _ => {} } }
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 70fafd6bea..79b89167cd 100644--- a/pdf/src/main/rust/src/interpret_part10.rs+++ b/pdf/src/main/rust/src/interpret_part10.rs@@ -9,10 +9,6 @@ mod refdiff_followup_tests_2 { Operation::new(name, operands) } - fn clip_applies(prims: &[Prim]) -> usize {- prims.iter().filter(|p| matches!(p, Prim::TextClipApply)).count()- }- /// §8.7.4.2 makes a `/Shading` resource "a dictionary or a stream", and /// §7.3.8.1 requires only the STREAM form to be indirect — ShadingTypes 1-3 /// are dictionaries and are legally written directly in the resource@@ -227,8 +223,7 @@ mod refdiff_followup_tests_2 { let doc = Document::with_version("1.7"); let red = rgb_to_argb(1.0, 0.0, 0.0);- let mut gs = GraphicsState::default();- gs.fill = red;+ let gs = GraphicsState { fill: red, ..Default::default() }; let mut prims = Vec::new(); interpret_content(&doc, &ops, None, gs.clone(), &mut prims, 0, false); let fills: Vec<u32> = prims
pdf/src/main/rust/src/interpret_part11.rs
diff --git a/pdf/src/main/rust/src/interpret_part11.rs b/pdf/src/main/rust/src/interpret_part11.rsindex 07f133c3c7..d39400eb75 100644--- a/pdf/src/main/rust/src/interpret_part11.rs+++ b/pdf/src/main/rust/src/interpret_part11.rs@@ -298,6 +298,7 @@ mod blind_reaudit_r4_tests { /// - `sh` honouring it floods the whole clip with the background colour, /// painting a solid block over content (the damaging direction); /// - a pattern ignoring it drops a legitimate, if rare, entry.+/// /// Handoff from `a-images`/`a-shading`, who landed the images.rs side. #[test] fn background_applies_to_shading_patterns_but_not_to_the_sh_operator() {
pdf/src/main/rust/src/interpret_part12.rs
diff --git a/pdf/src/main/rust/src/interpret_part12.rs b/pdf/src/main/rust/src/interpret_part12.rsindex cce6a00a25..134525a24e 100644--- a/pdf/src/main/rust/src/interpret_part12.rs+++ b/pdf/src/main/rust/src/interpret_part12.rs@@ -9,13 +9,6 @@ mod blind_reaudit_r4_tests_2 { Operation::new(name, operands) } - fn run(ops: &[Operation], res: Option<&lopdf::Dictionary>) -> Vec<Prim> {- let doc = Document::with_version("1.7");- let mut prims = Vec::new();- interpret_content(&doc, ops, res, GraphicsState::default(), &mut prims, 0, false);- prims- }- /// §7.3.3 bounds a real to the implementation limit, and lopdf's `Object::Real` /// is an `f32`, so a content stream carrying `1e40` parses to INFINITY. Nothing /// between the interpreter and `Canvas.drawPath` filters a non-finite coordinate@@ -125,6 +118,7 @@ mod blind_reaudit_r4_tests_2 { /// - a pattern `/Matrix`, which reaches the shading placement matrix; /// - `Tm`, which assigns straight to the text matrix and so places every /// subsequent glyph at a non-finite origin.+/// /// `cm` was already safe, but only because it guards the product it computes. /// Found by `a-images`, who hit the same class in shading matrices. #[test]
pdf/src/main/rust/src/interpret_part13.rs
diff --git a/pdf/src/main/rust/src/interpret_part13.rs b/pdf/src/main/rust/src/interpret_part13.rsindex 446b832f23..d3a10fed32 100644--- a/pdf/src/main/rust/src/interpret_part13.rs+++ b/pdf/src/main/rust/src/interpret_part13.rs@@ -307,7 +307,7 @@ mod blind_reaudit_r5_tests { blend: BlendMode::Normal, }]; let mut bracket = None;- wrap_with_soft_mask(&mut prims, 0, &doc, None, &mask, depth, &mut bracket, None);+ wrap_with_soft_mask(SoftMaskWrap { prims: &mut prims, start: 0, doc: &doc, resources: None, mask: &mask, depth, bracket: &mut bracket, masked_extent: None }); prims }; let good = SoftMask {
pdf/src/main/rust/src/interpret_part14.rs
diff --git a/pdf/src/main/rust/src/interpret_part14.rs b/pdf/src/main/rust/src/interpret_part14.rsindex 5c47d2e32e..b5541fc61e 100644--- a/pdf/src/main/rust/src/interpret_part14.rs+++ b/pdf/src/main/rust/src/interpret_part14.rs@@ -3,29 +3,12 @@ mod blind_reaudit_r5_tests_2 { use crate::*; use lopdf::content::Operation;- use lopdf::{dictionary, Stream};+ use lopdf::dictionary; fn op(name: &str, operands: Vec<Object>) -> Operation { Operation::new(name, operands) } - fn run(ops: &[Operation]) -> Vec<Prim> {- let doc = Document::with_version("1.7");- let mut prims = Vec::new();- interpret_content(&doc, ops, None, GraphicsState::default(), &mut prims, 0, false);- prims- }-- fn contours(prims: &[Prim]) -> Vec<Vec<(f32, f32)>> {- prims- .iter()- .find_map(|p| match p {- Prim::Fill { contours, .. } => Some(contours.clone()),- _ => None,- })- .expect("a fill must be emitted")- }- /// §8.11.3.3 bars DRAWING inside an OFF optional-content group, not state /// changes — and §9.3.6 Table 106 mode 7 is precisely "add to clip, paint /// nothing", which is what suppressing the paint of a mode 4-6 run leaves.@@ -344,11 +327,9 @@ mod blind_reaudit_r5_tests_2 { .expect("a stroke must be emitted") }; - let line = vec![- op("m", vec![0.into(), 0.into()]),+ let line = [op("m", vec![0.into(), 0.into()]), op("l", vec![50.into(), 50.into()]),- op("S", vec![]),- ];+ op("S", vec![])]; let mut baseline_ops = Vec::new(); baseline_ops.extend(line.iter().cloned()); let mut prims = Vec::new();
pdf/src/main/rust/src/interpret_part3.rs
diff --git a/pdf/src/main/rust/src/interpret_part3.rs b/pdf/src/main/rust/src/interpret_part3.rsindex 6c1713f2de..d90e0b51b9 100644--- a/pdf/src/main/rust/src/interpret_part3.rs+++ b/pdf/src/main/rust/src/interpret_part3.rs@@ -176,7 +176,8 @@ impl SeededInterp { } impl SeededInterp {- fn handle_paint_ops(&mut self, op: &lopdf::content::Operation, o: &[Object], doc: &Document, resources: Option<&lopdf::Dictionary>, prims: &mut Vec<Prim>, depth: u32, text_only: bool) {+ fn handle_paint_ops(&mut self, op: &lopdf::content::Operation, o: &[Object], ctx: HandlerCtx<'_>) {+ let HandlerCtx { doc, resources, prims, depth, text_only } = ctx; match op.operator.as_str() { "S" | "s" => { // `s` closes first (§8.5.3.1). A subpath `re` or `h` already closed@@ -189,12 +190,12 @@ impl SeededInterp { if !text_only && !self.oc_stack.last().copied().unwrap_or(false) { let sm_start = prims.len(); if let Some(pid) = self.gs.stroke_pattern {- paint_pattern_stroke(doc, pid, &self.subpaths, &self.gs, &self.pattern_base_ctm, &self.colorspaces, prims, depth, self.clip_depth);+ paint_pattern_stroke(PatternStroke { doc, pattern_id: pid, subpaths: &self.subpaths, gs: &self.gs, pattern_base_ctm: &self.pattern_base_ctm, cs_resources: &self.colorspaces, prims: &mut *prims, depth, clip_depth: self.clip_depth }); } else if prims.len() < MAX_PRIMITIVES { emit_stroke(prims, &self.subpaths, &self.gs); } if let Some(m) = self.gs.soft_mask.clone() {- wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox);+ wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } // §8.5.4: a pending `W` takes effect only AFTER the painting@@ -211,12 +212,12 @@ impl SeededInterp { if !text_only && !self.oc_stack.last().copied().unwrap_or(false) { let sm_start = prims.len(); if let Some(pid) = self.gs.fill_pattern {- paint_pattern_fill(doc, pid, &self.subpaths, op.operator == "f*", &self.pattern_base_ctm, self.gs.fill, self.gs.alpha_fill as f32, self.gs.blend_mode, &self.colorspaces, prims, depth, self.clip_depth);+ paint_pattern_fill(PatternFill { doc, pattern_id: pid, polys: &self.subpaths, even_odd: op.operator == "f*", pattern_base_ctm: &self.pattern_base_ctm, base_argb: self.gs.fill, alpha_fill: self.gs.alpha_fill as f32, blend: self.gs.blend_mode, cs_resources: &self.colorspaces, prims: &mut *prims, depth, clip_depth: self.clip_depth }); } else if prims.len() < MAX_PRIMITIVES { emit_fill(prims, &self.subpaths, self.gs.fill, op.operator == "f*", self.gs.alpha_fill, self.gs.blend_mode); } if let Some(m) = self.gs.soft_mask.clone() {- wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox);+ wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } // §8.5.4: see the `S` arm — the clip lands after the paint.@@ -234,17 +235,17 @@ impl SeededInterp { if !text_only && !self.oc_stack.last().copied().unwrap_or(false) { let sm_start = prims.len(); if let Some(pid) = self.gs.fill_pattern {- paint_pattern_fill(doc, pid, &self.subpaths, op.operator.ends_with('*'), &self.pattern_base_ctm, self.gs.fill, self.gs.alpha_fill as f32, self.gs.blend_mode, &self.colorspaces, prims, depth, self.clip_depth);+ paint_pattern_fill(PatternFill { doc, pattern_id: pid, polys: &self.subpaths, even_odd: op.operator.ends_with('*'), pattern_base_ctm: &self.pattern_base_ctm, base_argb: self.gs.fill, alpha_fill: self.gs.alpha_fill as f32, blend: self.gs.blend_mode, cs_resources: &self.colorspaces, prims: &mut *prims, depth, clip_depth: self.clip_depth }); } else if prims.len() < MAX_PRIMITIVES { emit_fill(prims, &self.subpaths, self.gs.fill, op.operator.ends_with('*'), self.gs.alpha_fill, self.gs.blend_mode); } if let Some(pid) = self.gs.stroke_pattern {- paint_pattern_stroke(doc, pid, &self.subpaths, &self.gs, &self.pattern_base_ctm, &self.colorspaces, prims, depth, self.clip_depth);+ paint_pattern_stroke(PatternStroke { doc, pattern_id: pid, subpaths: &self.subpaths, gs: &self.gs, pattern_base_ctm: &self.pattern_base_ctm, cs_resources: &self.colorspaces, prims: &mut *prims, depth, clip_depth: self.clip_depth }); } else if prims.len() < MAX_PRIMITIVES { emit_stroke(prims, &self.subpaths, &self.gs); } if let Some(m) = self.gs.soft_mask.clone() {- wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox);+ wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } // §8.5.4: see the `S` arm — the clip lands after the paint.@@ -268,7 +269,7 @@ impl SeededInterp { if let Some(img) = extract_inline_image(doc, stream, self.gs.fill, &self.colorspaces) { let sm_start = prims.len(); if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: self.gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode }); }- if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox); }+ if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } } }
pdf/src/main/rust/src/interpret_part4.rs
diff --git a/pdf/src/main/rust/src/interpret_part4.rs b/pdf/src/main/rust/src/interpret_part4.rsindex 03867f2589..d5c2c11838 100644--- a/pdf/src/main/rust/src/interpret_part4.rs+++ b/pdf/src/main/rust/src/interpret_part4.rs@@ -1,268 +1,266 @@ impl SeededInterp {- fn handle_do_op(&mut self, op: &lopdf::content::Operation, o: &[Object], doc: &Document, resources: Option<&lopdf::Dictionary>, prims: &mut Vec<Prim>, depth: u32, text_only: bool) {- match op.operator.as_str() {- "Do" => {- if let Some(pc) = self.pending_clip.take() {- emit_one_clip(prims, pc, &mut self.clip_depth, &mut self.current_clip_bbox, text_only);- }- if let Some(Object::Name(name)) = o.first() {- if let Some(&id) = self.xobjects.get(name) {- if let Ok(Object::Stream(stream)) = doc.get_object(id) {- // Skip the whole XObject if its optional-content group is OFF.- if stream.dict.get(b"OC").ok().map(|oc| { let cfg = self.oc_config.get_or_insert_with(|| OcConfig::from_doc(doc)); cfg.object_hidden(doc, oc) }).unwrap_or(false) {- return;+ fn handle_do_op(&mut self, op: &lopdf::content::Operation, o: &[Object], ctx: HandlerCtx<'_>) {+ let HandlerCtx { doc, resources, prims, depth, text_only } = ctx;+ if op.operator.as_str() == "Do" {+ if let Some(pc) = self.pending_clip.take() {+ emit_one_clip(prims, pc, &mut self.clip_depth, &mut self.current_clip_bbox, text_only);+ }+ if let Some(Object::Name(name)) = o.first() {+ if let Some(&id) = self.xobjects.get(name) {+ if let Ok(Object::Stream(stream)) = doc.get_object(id) {+ // Skip the whole XObject if its optional-content group is OFF.+ if stream.dict.get(b"OC").ok().map(|oc| { let cfg = self.oc_config.get_or_insert_with(|| OcConfig::from_doc(doc)); cfg.object_hidden(doc, oc) }).unwrap_or(false) {+ return;+ }+ let subtype = stream+ .dict+ .get(b"Subtype")+ .ok()+ .and_then(|o| o.as_name().ok());+ if subtype == Some(b"Image") {+ if !text_only && !self.oc_stack.last().copied().unwrap_or(false) {+ if let Some(img) = extract_image(doc, stream, self.gs.fill, &self.colorspaces) {+ let sm_start = prims.len();+ if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: self.gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode }); }+ if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } }- let subtype = stream+ }+ } else if subtype == Some(b"Form")+ && depth < 10+ // §8.11.2: content in a disabled optional-content group+ // shall not be drawn. The Image branch above is gated on+ // this; the form recursion was NOT, and `oc_stack` is a+ // local that no nested stream inherits, so+ // `/OC1 BDC /Fm0 Do EMC` with OC1 OFF painted the form's+ // ENTIRE contents. Worse, it painted them UNCLIPPED,+ // because the `/BBox` ClipPush and the `GroupPush` below+ // are both gated on this same flag while the recursion+ // that needed them was not.+ //+ // `text_only` deliberately still descends. That caller is+ // `search::build_index`, and the policy set in the `Tj`+ // arm is that an OC-hidden layer is hidden, not absent:+ // its text has to stay searchable. Suppressing ink and+ // keeping the index is exactly what mode 3 achieves there.+ && !(self.oc_stack.last().copied().unwrap_or(false) && !text_only)+ {+ // Bounds BRANCHING, which `depth < 10` above does+ // not: see [`MAX_FORM_INVOCATIONS`]. Checked before+ // anything is emitted, so exhausting it drops the+ // whole `Do` cleanly rather than leaving a clip or+ // group bracket half-open.+ if !take_form_budget() {+ return;+ }+ let form_matrix = stream+ .dict+ .get(b"Matrix")+ .ok()+ .and_then(|o| read_matrix_obj(deref(doc, o).unwrap_or(o)))+ .unwrap_or(IDENTITY);+ let form_res = stream+ .dict+ .get(b"Resources")+ .ok()+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_dict().ok())+ .cloned();+ // Transparency group detection per Phase 4: /Group << /S /Transparency /I bool /K bool >>+ let (is_transparency_group, isolated, knockout) = {+ if let Some(Object::Dictionary(gdict)) = stream.dict.get(b"Group").ok().and_then(|o| deref(doc,o).or(Some(o))).cloned() {+ let s = gdict.get(b"S").ok().and_then(|o| o.as_name().ok());+ if s == Some(b"Transparency") {+ let i = gdict.get(b"I").ok().and_then(|o| match o { Object::Boolean(b) => Some(*b), _=> None }).unwrap_or(false);+ let k = gdict.get(b"K").ok().and_then(|o| match o { Object::Boolean(b) => Some(*b), _=> None }).unwrap_or(false);+ (true, i, k)+ } else { (false,false,false) }+ } else { (false,false,false) }+ };+ // ExtGState soft mask active at this Do: bracket+ // the form as the masked content and emit the /G+ // group as the mask.+ let active_smask = self.gs.soft_mask.clone();+ let use_smask = active_smask.is_some()+ && !text_only+ && !self.oc_stack.last().copied().unwrap_or(false)+ && prims.len() < crate::MAX_PRIMITIVES+ && depth < MAX_GROUP_DEPTH;+ let sm_start = prims.len();+ // The group push is NOT mutually exclusive with the+ // soft-mask bracket. Making it so silently disabled the+ // §11.6.6 alpha reset below, which is gated on+ // `pushed_group`: a form carrying BOTH `/ca` < 1 and an+ // `/SMask` then applied `ca` to every element inside+ // instead of once to the composited group, over-darkening+ // wherever that content overlaps itself.+ //+ // Both fit because `sm_start` is captured ABOVE the push,+ // so `wrap_with_soft_mask` inserts `SoftMaskPush` outside+ // the group: the group composites (applying `ca` once)+ // inside the masked layer, then the mask applies to that+ // result, which is the §11.6.5.1 order.+ let should_emit_group = is_transparency_group && !text_only && !self.oc_stack.last().copied().unwrap_or(false) && depth < MAX_GROUP_DEPTH;+ let pushed_group = should_emit_group+ && prims.len() < crate::MAX_PRIMITIVES+ && self.group_depth < 32;+ if pushed_group {+ // The nonstroking constant alpha (ca) applies to the+ // group as a whole when it is painted; NOT ca*CA.+ prims.push(Prim::GroupPush { isolated, knockout, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode });+ self.group_depth+=1;+ }+ // Form content shall be clipped to /BBox (transformed by+ // /Matrix), per PDF 8.10.1, so it can't bleed past its box.+ let form_ctm = mat_mul(&form_matrix, &self.gs.ctm);+ // §8.7.4.1 requires `sh` to cover the ENTIRE current+ // clipping region, so `rasterize_shading` refuses to guess:+ // handed no clip extent, a shading with no `/BBox` of its own+ // paints NOTHING at all. Only the page-level caller seeded+ // that extent, and every nested stream reaches the+ // interpreter through `interpret_content`, which passes+ // `None` — so `/Sh sh` inside a form XObject silently+ // vanished, which is one of the few ways a fully-implemented+ // operator can still render nothing.+ //+ // §8.10.1 clips a form's content to `/BBox` transformed by+ // `/Matrix`, so that box — intersected with the clip already+ // in force — IS the region a nested `sh` has to fill. It is+ // the same quantity the `ClipPush` below is built from.+ let form_clip_bbox = {+ let own = stream .dict- .get(b"Subtype")+ .get(b"BBox") .ok()- .and_then(|o| o.as_name().ok());- if subtype == Some(b"Image") {- if !text_only && !self.oc_stack.last().copied().unwrap_or(false) {- if let Some(img) = extract_image(doc, stream, self.gs.fill, &self.colorspaces) {- let sm_start = prims.len();- if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: self.gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode }); }- if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox); }- }- }- } else if subtype == Some(b"Form")- && depth < 10- // §8.11.2: content in a disabled optional-content group- // shall not be drawn. The Image branch above is gated on- // this; the form recursion was NOT, and `oc_stack` is a- // local that no nested stream inherits, so- // `/OC1 BDC /Fm0 Do EMC` with OC1 OFF painted the form's- // ENTIRE contents. Worse, it painted them UNCLIPPED,- // because the `/BBox` ClipPush and the `GroupPush` below- // are both gated on this same flag while the recursion- // that needed them was not.- //- // `text_only` deliberately still descends. That caller is- // `search::build_index`, and the policy set in the `Tj`- // arm is that an OC-hidden layer is hidden, not absent:- // its text has to stay searchable. Suppressing ink and- // keeping the index is exactly what mode 3 achieves there.- && !(self.oc_stack.last().copied().unwrap_or(false) && !text_only)- {- // Bounds BRANCHING, which `depth < 10` above does- // not: see [`MAX_FORM_INVOCATIONS`]. Checked before- // anything is emitted, so exhausting it drops the- // whole `Do` cleanly rather than leaving a clip or- // group bracket half-open.- if !take_form_budget() {- return;- }- let form_matrix = stream- .dict- .get(b"Matrix")- .ok()- .and_then(|o| read_matrix_obj(deref(doc, o).unwrap_or(o)))- .unwrap_or(IDENTITY);- let form_res = stream- .dict- .get(b"Resources")- .ok()- .and_then(|o| deref(doc, o))- .and_then(|o| o.as_dict().ok())- .cloned();- // Transparency group detection per Phase 4: /Group << /S /Transparency /I bool /K bool >>- let (is_transparency_group, isolated, knockout) = {- if let Some(Object::Dictionary(gdict)) = stream.dict.get(b"Group").ok().and_then(|o| deref(doc,o).or(Some(o))).cloned() {- let s = gdict.get(b"S").ok().and_then(|o| o.as_name().ok());- if s == Some(b"Transparency") {- let i = gdict.get(b"I").ok().and_then(|o| match o { Object::Boolean(b) => Some(*b), _=> None }).unwrap_or(false);- let k = gdict.get(b"K").ok().and_then(|o| match o { Object::Boolean(b) => Some(*b), _=> None }).unwrap_or(false);- (true, i, k)- } else { (false,false,false) }- } else { (false,false,false) }- };- // ExtGState soft mask active at this Do: bracket- // the form as the masked content and emit the /G- // group as the mask.- let active_smask = self.gs.soft_mask.clone();- let use_smask = active_smask.is_some()- && !text_only- && !self.oc_stack.last().copied().unwrap_or(false)- && prims.len() < crate::MAX_PRIMITIVES- && depth < MAX_GROUP_DEPTH;- let sm_start = prims.len();- // The group push is NOT mutually exclusive with the- // soft-mask bracket. Making it so silently disabled the- // §11.6.6 alpha reset below, which is gated on- // `pushed_group`: a form carrying BOTH `/ca` < 1 and an- // `/SMask` then applied `ca` to every element inside- // instead of once to the composited group, over-darkening- // wherever that content overlaps itself.- //- // Both fit because `sm_start` is captured ABOVE the push,- // so `wrap_with_soft_mask` inserts `SoftMaskPush` outside- // the group: the group composites (applying `ca` once)- // inside the masked layer, then the mask applies to that- // result, which is the §11.6.5.1 order.- let should_emit_group = is_transparency_group && !text_only && !self.oc_stack.last().copied().unwrap_or(false) && depth < MAX_GROUP_DEPTH;- let pushed_group = should_emit_group- && prims.len() < crate::MAX_PRIMITIVES- && self.group_depth < 32;- if pushed_group {- // The nonstroking constant alpha (ca) applies to the- // group as a whole when it is painted; NOT ca*CA.- prims.push(Prim::GroupPush { isolated, knockout, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode });- self.group_depth+=1;+ .and_then(|o| read_rect(doc, o))+ .and_then(|bb| {+ quad_device_bbox(&[+ transform(&form_ctm, bb[0], bb[1]),+ transform(&form_ctm, bb[2], bb[1]),+ transform(&form_ctm, bb[2], bb[3]),+ transform(&form_ctm, bb[0], bb[3]),+ ])+ });+ // No `/BBox` (malformed, §8.10.2 makes it required) means+ // no extra bound, not an empty one: inherit the caller's.+ match (own, self.current_clip_bbox) {+ (Some(b), Some(cur)) => Some([+ b[0].max(cur[0]),+ b[1].max(cur[1]),+ b[2].min(cur[2]),+ b[3].min(cur[3]),+ ]),+ (Some(b), None) => Some(b),+ (None, cur) => cur,+ }+ // The intersection itself can come out empty.+ .filter(|b| b[2] > b[0] && b[3] > b[1])+ };+ let mut bbox_clipped = false;+ if !text_only && !self.oc_stack.last().copied().unwrap_or(false) {+ // §8.10.2 makes `/BBox` REQUIRED on a form+ // XObject, so a form without one is malformed+ // and there is no box to clip to. Deliberately+ // left unclipped rather than falling back to+ // the page box: that matches pdf.js, and the+ // form's `/Matrix` may legitimately place its+ // content outside the page, so a page-box+ // fallback would erase content in files that+ // render today. It does resolve malformed+ // input in the ink-ADDING direction, which is+ // the trade being made knowingly. Raised by+ // `hunt-extra`; a decision, not an oversight.+ if let Some(bb) = stream.dict.get(b"BBox").ok().and_then(|o| read_rect(doc, o)) {+ if prims.len() < MAX_PRIMITIVES {+ let c = [+ transform(&form_ctm, bb[0], bb[1]),+ transform(&form_ctm, bb[2], bb[1]),+ transform(&form_ctm, bb[2], bb[3]),+ transform(&form_ctm, bb[0], bb[3]),+ ];+ let pts: Vec<(f32, f32)> = c.iter().map(|&(x, y)| (x as f32, y as f32)).collect();+ let po = vec![+ PathOp::Move(c[0].0 as f32, c[0].1 as f32),+ PathOp::Line(c[1].0 as f32, c[1].1 as f32),+ PathOp::Line(c[2].0 as f32, c[2].1 as f32),+ PathOp::Line(c[3].0 as f32, c[3].1 as f32),+ PathOp::Close,+ ];+ prims.push(Prim::ClipPush { even_odd: false, pts, path_ops: Some(po) });+ bbox_clipped = true; }- // Form content shall be clipped to /BBox (transformed by- // /Matrix), per PDF 8.10.1, so it can't bleed past its box.- let form_ctm = mat_mul(&form_matrix, &self.gs.ctm);- // §8.7.4.1 requires `sh` to cover the ENTIRE current- // clipping region, so `rasterize_shading` refuses to guess:- // handed no clip extent, a shading with no `/BBox` of its own- // paints NOTHING at all. Only the page-level caller seeded- // that extent, and every nested stream reaches the- // interpreter through `interpret_content`, which passes- // `None` — so `/Sh sh` inside a form XObject silently- // vanished, which is one of the few ways a fully-implemented- // operator can still render nothing.+ }+ }+ // §8.9.7: lopdf wraps inline-image parsing in nom+ // `cut(...)`, so ONE inline image it cannot handle+ // failed this whole form and blanked it, exactly as it+ // used to blank a whole page. `stream_operations`+ // returns lopdf's result untouched when it succeeds, so+ // a form that renders today is unaffected.+ let sub_ops = crate::content::stream_operations(doc, stream);+ if !sub_ops.is_empty() {+ let mut sub_gs = self.gs.clone();+ sub_gs.ctm = form_ctm;+ // A soft mask applies once, to this form as a+ // whole. Only clear it when the wrap actually+ // happened; otherwise the mask must stay in the+ // state and be applied per element inside, since+ // §11.6.5.1 makes it inherited state that cannot+ // silently vanish.+ if use_smask { sub_gs.soft_mask = None; }+ // Per PDF 11.6.6: on entering a transparency group the+ // alpha constants reset to 1.0 and blend to Normal — they+ // are applied when the group's result is composited (via+ // GroupPush), not again to each element inside. Without+ // this, ca is double-applied and low-alpha groups vanish. //- // §8.10.1 clips a form's content to `/BBox` transformed by- // `/Matrix`, so that box — intersected with the clip already- // in force — IS the region a nested `sh` has to fill. It is- // the same quantity the `ClipPush` below is built from.- let form_clip_bbox = {- let own = stream- .dict- .get(b"BBox")- .ok()- .and_then(|o| read_rect(doc, o))- .and_then(|bb| {- quad_device_bbox(&[- transform(&form_ctm, bb[0], bb[1]),- transform(&form_ctm, bb[2], bb[1]),- transform(&form_ctm, bb[2], bb[3]),- transform(&form_ctm, bb[0], bb[3]),- ])- });- // No `/BBox` (malformed, §8.10.2 makes it required) means- // no extra bound, not an empty one: inherit the caller's.- match (own, self.current_clip_bbox) {- (Some(b), Some(cur)) => Some([- b[0].max(cur[0]),- b[1].max(cur[1]),- b[2].min(cur[2]),- b[3].min(cur[3]),- ]),- (Some(b), None) => Some(b),- (None, cur) => cur,- }- // The intersection itself can come out empty.- .filter(|b| b[2] > b[0] && b[3] > b[1])- };- let mut bbox_clipped = false;- if !text_only && !self.oc_stack.last().copied().unwrap_or(false) {- // §8.10.2 makes `/BBox` REQUIRED on a form- // XObject, so a form without one is malformed- // and there is no box to clip to. Deliberately- // left unclipped rather than falling back to- // the page box: that matches pdf.js, and the- // form's `/Matrix` may legitimately place its- // content outside the page, so a page-box- // fallback would erase content in files that- // render today. It does resolve malformed- // input in the ink-ADDING direction, which is- // the trade being made knowingly. Raised by- // `hunt-extra`; a decision, not an oversight.- if let Some(bb) = stream.dict.get(b"BBox").ok().and_then(|o| read_rect(doc, o)) {- if prims.len() < MAX_PRIMITIVES {- let c = [- transform(&form_ctm, bb[0], bb[1]),- transform(&form_ctm, bb[2], bb[1]),- transform(&form_ctm, bb[2], bb[3]),- transform(&form_ctm, bb[0], bb[3]),- ];- let pts: Vec<(f32, f32)> = c.iter().map(|&(x, y)| (x as f32, y as f32)).collect();- let po = vec![- PathOp::Move(c[0].0 as f32, c[0].1 as f32),- PathOp::Line(c[1].0 as f32, c[1].1 as f32),- PathOp::Line(c[2].0 as f32, c[2].1 as f32),- PathOp::Line(c[3].0 as f32, c[3].1 as f32),- PathOp::Close,- ];- prims.push(Prim::ClipPush { even_odd: false, pts, path_ops: Some(po) });- bbox_clipped = true;- }- }- }- // §8.9.7: lopdf wraps inline-image parsing in nom- // `cut(...)`, so ONE inline image it cannot handle- // failed this whole form and blanked it, exactly as it- // used to blank a whole page. `stream_operations`- // returns lopdf's result untouched when it succeeds, so- // a form that renders today is unaffected.- let sub_ops = crate::content::stream_operations(doc, stream);- if !sub_ops.is_empty() {- let mut sub_gs = self.gs.clone();- sub_gs.ctm = form_ctm;- // A soft mask applies once, to this form as a- // whole. Only clear it when the wrap actually- // happened; otherwise the mask must stay in the- // state and be applied per element inside, since- // §11.6.5.1 makes it inherited state that cannot- // silently vanish.- if use_smask { sub_gs.soft_mask = None; }- // Per PDF 11.6.6: on entering a transparency group the- // alpha constants reset to 1.0 and blend to Normal — they- // are applied when the group's result is composited (via- // GroupPush), not again to each element inside. Without- // this, ca is double-applied and low-alpha groups vanish.- //- // Deliberately still gated on `pushed_group`, so when- // `MAX_PRIMITIVES` or the group-depth cap demotes the push- // the alpha keeps being applied per element. There is no- // composite to apply it to once in that case, and resetting- // anyway would drop `ca` entirely and paint the form fully- // opaque — wrong for all content, where per-element is- // wrong only where content overlaps itself.- if pushed_group {- sub_gs.alpha_fill = 1.0;- sub_gs.alpha_stroke = 1.0;- sub_gs.blend_mode = BlendMode::Normal;- }- let res_ref = form_res.as_ref().or(resources);- interpret_content_seeded(- doc,- &sub_ops,- res_ref,- sub_gs,- prims,- depth + 1,- text_only,- form_clip_bbox,- );- }- if bbox_clipped {- // Always balance the ClipPush, even if the prim cap- // was hit inside the form, to keep the clip stack sane.- prims.push(Prim::ClipPop);- }- // §8.10.1: `Do` on a form behaves as `q … Q`, so the- // group must be composited here rather than being left- // open until the next `Q` (or end of stream), which let- // its alpha and blend mode leak onto later content.+ // Deliberately still gated on `pushed_group`, so when+ // `MAX_PRIMITIVES` or the group-depth cap demotes the push+ // the alpha keeps being applied per element. There is no+ // composite to apply it to once in that case, and resetting+ // anyway would drop `ca` entirely and paint the form fully+ // opaque — wrong for all content, where per-element is+ // wrong only where content overlaps itself. if pushed_group {- prims.push(Prim::GroupPop);- self.group_depth -= 1;- }- // Bracket the whole form as the masked content, then- // append the mask group (rendered at the mask's set-time CTM).- if use_smask {- if let Some(mask) = active_smask {- wrap_with_soft_mask(prims, sm_start, doc, resources, &mask, depth, &mut self.mask_bracket, self.current_clip_bbox);- }+ sub_gs.alpha_fill = 1.0;+ sub_gs.alpha_stroke = 1.0;+ sub_gs.blend_mode = BlendMode::Normal; }+ let res_ref = form_res.as_ref().or(resources);+ interpret_content_seeded(+ doc,+ &sub_ops,+ res_ref,+ sub_gs,+ prims,+ depth + 1,+ text_only,+ form_clip_bbox,+ );+ }+ if bbox_clipped {+ // Always balance the ClipPush, even if the prim cap+ // was hit inside the form, to keep the clip stack sane.+ prims.push(Prim::ClipPop);+ }+ // §8.10.1: `Do` on a form behaves as `q … Q`, so the+ // group must be composited here rather than being left+ // open until the next `Q` (or end of stream), which let+ // its alpha and blend mode leak onto later content.+ if pushed_group {+ prims.push(Prim::GroupPop);+ self.group_depth -= 1;+ }+ // Bracket the whole form as the masked content, then+ // append the mask group (rendered at the mask's set-time CTM).+ if use_smask {+ if let Some(mask) = active_smask {+ wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &mask, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } } } }- _ => {}+ } } } }
pdf/src/main/rust/src/interpret_part5.rs
diff --git a/pdf/src/main/rust/src/interpret_part5.rs b/pdf/src/main/rust/src/interpret_part5.rsindex 690468f2bf..f4bd21aa07 100644--- a/pdf/src/main/rust/src/interpret_part5.rs+++ b/pdf/src/main/rust/src/interpret_part5.rs@@ -1,5 +1,6 @@ impl SeededInterp {- fn handle_color_ops(&mut self, op: &lopdf::content::Operation, o: &[Object], doc: &Document, resources: Option<&lopdf::Dictionary>, prims: &mut Vec<Prim>, depth: u32, text_only: bool) {+ fn handle_color_ops(&mut self, op: &lopdf::content::Operation, o: &[Object], ctx: HandlerCtx<'_>) {+ let HandlerCtx { doc, resources, prims, depth, text_only } = ctx; match op.operator.as_str() { "rg" => { let n: Vec<f64> = o.iter().filter_map(num).collect();@@ -141,7 +142,7 @@ impl SeededInterp { if prims.len() < MAX_PRIMITIVES && !self.oc_stack.last().copied().unwrap_or(false) { let sm_start = prims.len(); prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: self.gs.alpha_fill as f32, blend: self.gs.blend_mode });- if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox); }+ if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } } }
pdf/src/main/rust/src/interpret_part6.rs
diff --git a/pdf/src/main/rust/src/interpret_part6.rs b/pdf/src/main/rust/src/interpret_part6.rsindex a067abcd1b..2be3e008a1 100644--- a/pdf/src/main/rust/src/interpret_part6.rs+++ b/pdf/src/main/rust/src/interpret_part6.rs@@ -1,5 +1,6 @@ impl SeededInterp {- fn handle_text_ops(&mut self, op: &lopdf::content::Operation, o: &[Object], doc: &Document, resources: Option<&lopdf::Dictionary>, prims: &mut Vec<Prim>, depth: u32, text_only: bool) {+ fn handle_text_ops(&mut self, op: &lopdf::content::Operation, o: &[Object], ctx: HandlerCtx<'_>) {+ let HandlerCtx { doc, resources, prims, depth, text_only } = ctx; // Operand accessor (same as in `handle_state_ops`): `None` means "treat // the operand as absent"; filters non-finite values. let numop = |o: &[Object], i: usize| -> Option<f64> {@@ -136,7 +137,7 @@ impl SeededInterp { // budget that `show_string`'s Text records are also drawn from — // so a mask-heavy document silently indexed less of its own text. if !text_only && !oc_hidden && matches!(self.gs.render_mode, 0|1|2|4|5|6) {- if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox); }+ if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } } }@@ -158,7 +159,7 @@ impl SeededInterp { self.text_matrix = mat_mul(&translate(adv, 0.0), &self.text_matrix); } if !text_only && !oc_hidden && matches!(self.gs.render_mode, 0|1|2|4|5|6) {- if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox); }+ if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } } }@@ -182,7 +183,7 @@ impl SeededInterp { self.text_matrix = mat_mul(&translate(adv, 0.0), &self.text_matrix); } if !text_only && !oc_hidden && matches!(self.gs.render_mode, 0|1|2|4|5|6) {- if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox); }+ if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } } }@@ -228,7 +229,7 @@ impl SeededInterp { } if oc_hidden { self.gs.render_mode = shown_mode; } if !text_only && !oc_hidden && matches!(self.gs.render_mode, 0|1|2|4|5|6) {- if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth, &mut self.mask_bracket, self.current_clip_bbox); }+ if let Some(m) = self.gs.soft_mask.clone() { wrap_with_soft_mask(SoftMaskWrap { prims: &mut *prims, start: sm_start, doc, resources, mask: &m, depth, bracket: &mut self.mask_bracket, masked_extent: self.current_clip_bbox }); } } } // Explicit no-ops (documented): rendering intent, and compatibility
pdf/src/main/rust/src/interpret_part7.rs
diff --git a/pdf/src/main/rust/src/interpret_part7.rs b/pdf/src/main/rust/src/interpret_part7.rsindex af63550e30..4321abd27c 100644--- a/pdf/src/main/rust/src/interpret_part7.rs+++ b/pdf/src/main/rust/src/interpret_part7.rs@@ -219,6 +219,70 @@ pub(crate) fn render_soft_mask_group( true } +/// Everything needed to wrap already-emitted primitives in a soft mask.+pub(crate) struct SoftMaskWrap<'a> {+ pub prims: &'a mut Vec<Prim>,+ pub start: usize,+ pub doc: &'a Document,+ pub resources: Option<&'a lopdf::Dictionary>,+ pub mask: &'a SoftMask,+ pub depth: u32,+ pub bracket: &'a mut Option<MaskBracket>,+ pub masked_extent: Option<[f64; 4]>,+}++/// Everything needed to fill a region with a pattern.+pub(crate) struct PatternFill<'a> {+ pub doc: &'a Document,+ pub pattern_id: ObjectId,+ pub polys: &'a [Vec<(f64, f64)>],+ pub even_odd: bool,+ pub pattern_base_ctm: &'a Mat,+ pub base_argb: u32,+ pub alpha_fill: f32,+ pub blend: BlendMode,+ // The invoking stream's `/Resources /ColorSpace` map: a shading whose+ // `/ColorSpace` is a NAME resolves against it (see PatternStroke).+ pub cs_resources: &'a HashMap<Vec<u8>, ObjectId>,+ pub prims: &'a mut Vec<Prim>,+ pub depth: u32,+ pub clip_depth: usize,+}++/// Everything needed to stroke subpaths with a pattern.+pub(crate) struct PatternStroke<'a> {+ pub doc: &'a Document,+ pub pattern_id: ObjectId,+ pub subpaths: &'a [Vec<(f64, f64)>],+ pub gs: &'a GraphicsState,+ pub pattern_base_ctm: &'a Mat,+ // The invoking stream's `/Resources /ColorSpace` map. §8.6.1 lets any+ // non-device colour space be written as a NAME, and Table 78 puts no+ // restriction on the form a shading's `/ColorSpace` takes — a PatternType 2+ // dictionary has no `/Resources` of its own (only tiling patterns do), so a+ // name in its shading resolves against the stream that invoked the pattern.+ // Passing an empty map made every such lookup miss and silently substitute+ // DeviceRGB. Found by `r5-color`.+ pub cs_resources: &'a HashMap<Vec<u8>, ObjectId>,+ pub prims: &'a mut Vec<Prim>,+ pub depth: u32,+ pub clip_depth: usize,+}++/// Everything needed to paint one tiling-pattern cell lattice.+pub(crate) struct TilingPattern<'a> {+ pub doc: &'a Document,+ pub obj: &'a Object,+ pub dict: &'a lopdf::Dictionary,+ pub pmat: &'a Mat,+ pub base_argb: u32,+ pub polys: &'a [Vec<(f64, f64)>],+ pub prims: &'a mut Vec<Prim>,+ pub depth: u32,+ pub alpha: f32,+ pub blend: BlendMode,+}+ /// Bracket the primitives appended since `start` with the given soft mask so /// they are drawn only where the mask is opaque/luminous. No-op if nothing was /// emitted. Reuses the SoftMaskPush/Content/Pop wire prims.@@ -238,16 +302,8 @@ pub(crate) fn render_soft_mask_group( /// fully transparent mask and for non-overlapping content — which is what a run /// of shapes under one mask is in practice — and differ only in the alpha /// arithmetic where partially-masked content overlaps itself.-pub(crate) fn wrap_with_soft_mask(- prims: &mut Vec<Prim>,- start: usize,- doc: &Document,- resources: Option<&lopdf::Dictionary>,- mask: &SoftMask,- depth: u32,- bracket: &mut Option<MaskBracket>,- masked_extent: Option<[f64; 4]>,-) {+pub(crate) fn wrap_with_soft_mask(wrap: SoftMaskWrap<'_>) {+ let SoftMaskWrap { prims, start, doc, resources, mask, depth, bracket, masked_extent } = wrap; if start >= prims.len() || prims.len() >= MAX_PRIMITIVES { return; }@@ -341,24 +397,8 @@ fn polys_device_bbox(polys: &[Vec<(f64, f64)>]) -> Option<[f64;4]> { } /// the segments (matching how a real stroke covers the path).-pub(crate) fn paint_pattern_stroke(- doc: &Document,- pattern_id: ObjectId,- subpaths: &[Vec<(f64, f64)>],- gs: &GraphicsState,- pattern_base_ctm: &Mat,- // The invoking stream's `/Resources /ColorSpace` map. §8.6.1 lets any- // non-device colour space be written as a NAME, and Table 78 puts no- // restriction on the form a shading's `/ColorSpace` takes — a PatternType 2- // dictionary has no `/Resources` of its own (only tiling patterns do), so a- // name in its shading resolves against the stream that invoked the pattern.- // Passing an empty map made every such lookup miss and silently substitute- // DeviceRGB. Found by `r5-color`.- cs_resources: &HashMap<Vec<u8>, ObjectId>,- prims: &mut Vec<Prim>,- depth: u32,- clip_depth: usize,-) {+pub(crate) fn paint_pattern_stroke(stroke: PatternStroke<'_>) {+ let PatternStroke { doc, pattern_id, subpaths, gs, pattern_base_ctm, cs_resources, prims, depth, clip_depth } = stroke; // These clips are pushed and popped inside this function, so they never // unbalance the stream — but they DO consume renderer clip levels, so they // have to respect the same ceiling as `emit_one_clip`.@@ -437,7 +477,7 @@ pub(crate) fn paint_pattern_stroke( } } } else if ptype == 1 {- paint_tiling_pattern(doc, obj, dict, &pmat, gs.stroke, &quads, prims, depth, gs.alpha_stroke as f32, gs.blend_mode);+ paint_tiling_pattern(TilingPattern { doc, obj, dict, pmat: &pmat, base_argb: gs.stroke, polys: &quads, prims, depth, alpha: gs.alpha_stroke as f32, blend: gs.blend_mode }); } prims.push(Prim::ClipPop); }
pdf/src/main/rust/src/interpret_part8.rs
diff --git a/pdf/src/main/rust/src/interpret_part8.rs b/pdf/src/main/rust/src/interpret_part8.rsindex 8f8f7e9a22..957d3c0407 100644--- a/pdf/src/main/rust/src/interpret_part8.rs+++ b/pdf/src/main/rust/src/interpret_part8.rs@@ -1,20 +1,5 @@-pub(crate) fn paint_pattern_fill(- doc: &Document,- pattern_id: ObjectId,- polys: &[Vec<(f64, f64)>],- even_odd: bool,- pattern_base_ctm: &Mat,- base_argb: u32,- alpha_fill: f32,- blend: BlendMode,- // See [`paint_pattern_stroke`]: the invoking stream's `/Resources- // /ColorSpace` map, without which a shading whose `/ColorSpace` is a NAME- // falls back to DeviceRGB.- cs_resources: &HashMap<Vec<u8>, ObjectId>,- prims: &mut Vec<Prim>,- depth: u32,- clip_depth: usize,-) {+pub(crate) fn paint_pattern_fill(fill: PatternFill<'_>) {+ let PatternFill { doc, pattern_id, polys, even_odd, pattern_base_ctm, base_argb, alpha_fill, blend, cs_resources, prims, depth, clip_depth } = fill; if clip_depth >= MAX_CLIP_DEPTH { return; }@@ -73,7 +58,7 @@ pub(crate) fn paint_pattern_fill( } } } else if ptype == 1 {- paint_tiling_pattern(doc, obj, dict, &pmat, base_argb, polys, prims, depth, alpha_fill, blend);+ paint_tiling_pattern(TilingPattern { doc, obj, dict, pmat: &pmat, base_argb, polys, prims, depth, alpha: alpha_fill, blend }); } prims.push(Prim::ClipPop);
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 3e99f7e929..204d4c9180 100644--- a/pdf/src/main/rust/src/interpret_part9.rs+++ b/pdf/src/main/rust/src/interpret_part9.rs@@ -1,15 +1,5 @@-fn paint_tiling_pattern(- doc: &Document,- obj: &Object,- dict: &lopdf::Dictionary,- pmat: &Mat,- base_argb: u32,- polys: &[Vec<(f64, f64)>],- prims: &mut Vec<Prim>,- depth: u32,- alpha: f32,- blend: BlendMode,-) {+fn paint_tiling_pattern(tiling: TilingPattern<'_>) {+ let TilingPattern { doc, obj, dict, pmat, base_argb, polys, prims, depth, alpha, blend } = tiling; let stream = match obj { Object::Stream(s) => s, _ => return,@@ -285,7 +275,7 @@ pub(crate) fn read_rect(doc: &Document, obj: &Object) -> Option<[f64; 4]> { mod refdiff_followup_tests { use crate::*; use lopdf::content::Operation;- use lopdf::{dictionary, Stream};+ use lopdf::dictionary; fn op(name: &str, operands: Vec<Object>) -> Operation { Operation::new(name, operands)@@ -378,8 +368,7 @@ mod refdiff_followup_tests { op("re", vec![0.into(), 0.into(), 100.into(), 100.into()]), op("f", vec![]), ];- let mut gs = GraphicsState::default();- gs.fill = red;+ let gs = GraphicsState { fill: red, ..Default::default() }; let mut prims = Vec::new(); interpret_content(&doc, &glyph, None, gs.clone(), &mut prims, 0, false); let fills: Vec<u32> = prims
pdf/src/main/rust/src/issue321_tests.rs
diff --git a/pdf/src/main/rust/src/issue321_tests.rs b/pdf/src/main/rust/src/issue321_tests.rsindex d5ff532740..097f0e6a55 100644--- a/pdf/src/main/rust/src/issue321_tests.rs+++ b/pdf/src/main/rust/src/issue321_tests.rs@@ -18,6 +18,7 @@ //! * it prints a banner naming every fixture that went unverified; //! * `ISSUE321_REQUIRE_FIXTURES=1` turns the skip into a hard failure, for //! anyone who needs the run to actually mean something.+//! //! It does not fail by default, because the fixtures legitimately cannot be //! committed and an unconditional failure would just get muted. //!@@ -316,7 +317,7 @@ mod issue321 { } } let mut v: Vec<(u32, usize)> = counts.into_iter().collect();- v.sort_by(|a, b| b.1.cmp(&a.1));+ v.sort_by_key(|b| std::cmp::Reverse(b.1)); println!("=== {} p{} top fill/text colors (ARGB) ===", name, page_idx); for (argb, n) in v.iter().take(25) { println!(
pdf/src/main/rust/src/jni_bindings.rs
diff --git a/pdf/src/main/rust/src/jni_bindings.rs b/pdf/src/main/rust/src/jni_bindings.rsindex 6f6c1f15f7..73d32b3a85 100644--- a/pdf/src/main/rust/src/jni_bindings.rs+++ b/pdf/src/main/rust/src/jni_bindings.rs@@ -30,11 +30,11 @@ impl Drop for InvalidateSearchIndex { /// Throw a Java IllegalArgumentException (if possible). Requires &mut JNIEnv. fn throw_iae<'local>(env: &mut Env<'local>, msg: &str) {- let _ = env.throw_new(jni_str!("java/lang/IllegalArgumentException"), &jni::strings::JNIString::new(msg));+ let _ = env.throw_new(jni_str!("java/lang/IllegalArgumentException"), jni::strings::JNIString::new(msg)); } fn throw_oom<'local>(env: &mut Env<'local>, msg: &str) {- let _ = env.throw_new(jni_str!("java/lang/OutOfMemoryError"), &jni::strings::JNIString::new(msg));+ let _ = env.throw_new(jni_str!("java/lang/OutOfMemoryError"), jni::strings::JNIString::new(msg)); } /// Convert JString to Rust String with proper error propagation (no unwrap_or_default hiding errors).@@ -47,7 +47,7 @@ fn jstr_safe<'local>(env: &Env, s: &JString<'local>) -> Result<String, String> { match s.try_to_string(env) { Ok(js) => Ok(js), Err(e) => {- let _ = env.exception_clear();+ env.exception_clear(); Err(format!("Invalid JString (Modified UTF-8): {:?}", e)) } }@@ -59,7 +59,7 @@ fn jstr_safe<'local>(env: &Env, s: &JString<'local>) -> Result<String, String> { fn bytes_or_null_mut<'local>(env: &mut Env<'local>, data: Option<Vec<u8>>) -> jbyteArray { let null = std::ptr::null_mut(); if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return null; } match data {@@ -84,15 +84,15 @@ fn open_document_inner<'local>(env: &mut Env<'local>, data: JByteArray<'local>) throw_iae(env, "data is null"); return 0; }- let len = env.get_array_length(&data).unwrap_or(0);- if len as usize > MAX_JAVA_BYTE_ARRAY_BYTES {+ let len = data.len(env).unwrap_or(0);+ if len > MAX_JAVA_BYTE_ARRAY_BYTES { throw_oom(env, "PDF too large (>200MB)"); return 0; } let bytes = match env.convert_byte_array(&data) { Ok(b) => b, Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); return 0; } };@@ -108,15 +108,15 @@ fn open_document_pw_inner<'local>( throw_iae(env, "data is null"); return 0; }- let len = env.get_array_length(&data).unwrap_or(0);- if len as usize > MAX_JAVA_BYTE_ARRAY_BYTES {+ let len = data.len(env).unwrap_or(0);+ if len > MAX_JAVA_BYTE_ARRAY_BYTES { throw_oom(env, "PDF too large (>200MB)"); return 0; } let bytes = match env.convert_byte_array(&data) { Ok(b) => b, Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); return 0; } };@@ -139,15 +139,15 @@ fn pdf_password_state_inner<'local>(env: &mut Env<'local>, data: JByteArray<'loc throw_iae(env, "data is null"); return 0; }- let len = env.get_array_length(&data).unwrap_or(0);- if len as usize > MAX_JAVA_BYTE_ARRAY_BYTES {+ let len = data.len(env).unwrap_or(0);+ if len > MAX_JAVA_BYTE_ARRAY_BYTES { throw_oom(env, "PDF too large (>200MB)"); return 0; } let bytes = match env.convert_byte_array(&data) { Ok(b) => b, Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); return 0; } };@@ -176,7 +176,7 @@ fn save_encrypted_inner<'local>( }; // Ensure capacity before allocating byte array (audit #4) if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } bytes_or_null_mut(env, save_encrypted(handle, u.as_bytes(), o.as_bytes()))@@ -184,7 +184,7 @@ fn save_encrypted_inner<'local>( fn render_page_inner<'local>(env: &mut Env<'local>, handle: jlong, index: jint) -> jbyteArray { if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } bytes_or_null_mut(env, render_page(handle, index))@@ -199,15 +199,15 @@ fn append_pdf_inner<'local>( throw_iae(env, "data is null"); return 0; }- let len = env.get_array_length(&data).unwrap_or(0);- if len as usize > MAX_JAVA_BYTE_ARRAY_BYTES {+ let len = data.len(env).unwrap_or(0);+ if len > MAX_JAVA_BYTE_ARRAY_BYTES { throw_oom(env, "PDF to append too large (>200MB)"); return 0; } let bytes = match env.convert_byte_array(&data) { Ok(b) => b, Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); return 0; } };@@ -225,15 +225,15 @@ fn append_image_page_inner<'local>( throw_iae(env, "jpeg is null"); return 0; }- let len = env.get_array_length(&jpeg).unwrap_or(0);- if len as usize > MAX_JAVA_BYTE_ARRAY_BYTES {+ let len = jpeg.len(env).unwrap_or(0);+ if len > MAX_JAVA_BYTE_ARRAY_BYTES { throw_oom(env, "Image too large (>200MB)"); return 0; } let bytes = match env.convert_byte_array(&jpeg) { Ok(b) => b, Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); return 0; } };@@ -242,7 +242,7 @@ fn append_image_page_inner<'local>( fn extract_page_inner<'local>(env: &mut Env<'local>, handle: jlong, index: jint) -> jbyteArray { if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } bytes_or_null_mut(env, extract_page(handle, index))@@ -253,7 +253,7 @@ where F: FnOnce() -> Option<Vec<u8>>, { if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } bytes_or_null_mut(env, f())@@ -263,10 +263,8 @@ fn add_free_text_inner<'local>( env: &mut Env<'local>, handle: jlong, page: jint,- x0: jfloat,- y0: jfloat,- x1: jfloat,- y1: jfloat,+ // (x0, y0, x1, y1) text-box rect+ rect: [jfloat; 4], argb: jint, size: jfloat, text: JString<'local>,@@ -281,7 +279,7 @@ fn add_free_text_inner<'local>( add_free_text( handle, page,- [x0 as f64, y0 as f64, x1 as f64, y1 as f64],+ rect.map(|v| v as f64), argb as u32, size as f64, &t,@@ -312,10 +310,8 @@ fn add_callout_inner<'local>( env: &mut Env<'local>, handle: jlong, page: jint,- ax: jfloat,- ay: jfloat,- bx: jfloat,- by: jfloat,+ // (anchor x, anchor y, box x, box y): leader anchor and text-box corner+ pts: [jfloat; 4], argb: jint, size: jfloat, text: JString<'local>,@@ -330,10 +326,8 @@ fn add_callout_inner<'local>( add_callout( handle, page,- ax as f64,- ay as f64,- bx as f64,- by as f64,+ (pts[0] as f64, pts[1] as f64),+ (pts[2] as f64, pts[3] as f64), argb as u32, size as f64, &t,@@ -347,18 +341,19 @@ fn add_poly_inner<'local>( page: jint, argb: jint, line_width: jfloat,- fill: jboolean,- closed: jboolean,+ // (fill, closed)+ fill_closed: (jboolean, jboolean), pts: JFloatArray<'local>, ) -> jlong {+ let (fill, closed) = fill_closed; if pts.is_null() { throw_iae(env, "pts is null"); return 0; }- let len = match env.get_array_length(&pts) {- Ok(l) => l as usize,+ let len = match pts.len(env) {+ Ok(l) => l, Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); return 0; } };@@ -367,8 +362,8 @@ fn add_poly_inner<'local>( return 0; } let mut buf = vec![0f32; len];- if env.get_float_array_region(&pts, 0, &mut buf).is_err() {- let _ = env.exception_clear();+ if pts.get_region(env, 0, &mut buf).is_err() {+ env.exception_clear(); return 0; } add_poly(@@ -395,10 +390,10 @@ fn add_ink_inner<'local>( throw_iae(env, "pts is null"); return 0; }- let len = match env.get_array_length(&pts) {- Ok(l) => l as usize,+ let len = match pts.len(env) {+ Ok(l) => l, Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); return 0; } };@@ -407,8 +402,8 @@ fn add_ink_inner<'local>( return 0; } let mut buf = vec![0f32; len];- if env.get_float_array_region(&pts, 0, &mut buf).is_err() {- let _ = env.exception_clear();+ if pts.get_region(env, 0, &mut buf).is_err() {+ env.exception_clear(); return 0; } add_ink(handle, page, argb as u32, line_width as f64, &buf).unwrap_or(0)
pdf/src/main/rust/src/jni_bindings_part1.rs
diff --git a/pdf/src/main/rust/src/jni_bindings_part1.rs b/pdf/src/main/rust/src/jni_bindings_part1.rsindex d073bfe0eb..7bc0626bd0 100644--- a/pdf/src/main/rust/src/jni_bindings_part1.rs+++ b/pdf/src/main/rust/src/jni_bindings_part1.rs@@ -2,36 +2,33 @@ fn add_stamp_inner<'local>( env: &mut Env<'local>, handle: jlong, page: jint,- x0: jfloat,- y0: jfloat,- x1: jfloat,- y1: jfloat,- img_w: jint,- img_h: jint,+ // (x0, y0, x1, y1) stamp rect and (width, height) of the image+ rect: [jfloat; 4],+ img_size: (jint, jint), jpeg: JByteArray<'local>, ) -> jlong { if jpeg.is_null() { throw_iae(env, "jpeg is null"); return 0; }- let len = env.get_array_length(&jpeg).unwrap_or(0);- if len as usize > MAX_JAVA_BYTE_ARRAY_BYTES {+ let len = jpeg.len(env).unwrap_or(0);+ if len > MAX_JAVA_BYTE_ARRAY_BYTES { throw_oom(env, "Image stamp too large (>200MB)"); return 0; } let bytes = match env.convert_byte_array(&jpeg) { Ok(b) => b, Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); return 0; } }; add_stamp( handle, page,- [x0 as f64, y0 as f64, x1 as f64, y1 as f64],- img_w as u32,- img_h as u32,+ rect.map(|v| v as f64),+ img_size.0 as u32,+ img_size.1 as u32, &bytes, ) .unwrap_or(0)@@ -87,7 +84,7 @@ fn set_choice_field_inner<'local>( fn save_document_inner<'local>(env: &mut Env<'local>, handle: jlong) -> jbyteArray { if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } bytes_or_null_mut(env, save_document(handle))@@ -95,7 +92,7 @@ fn save_document_inner<'local>(env: &mut Env<'local>, handle: jlong) -> jbyteArr fn save_compressed_inner<'local>(env: &mut Env<'local>, handle: jlong) -> jbyteArray { if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } bytes_or_null_mut(env, save_compressed(handle))@@ -103,7 +100,7 @@ fn save_compressed_inner<'local>(env: &mut Env<'local>, handle: jlong) -> jbyteA fn extract_text_inner<'local>(env: &mut Env<'local>, handle: jlong) -> jstring { if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } let text_opt = document_text(handle);@@ -111,7 +108,7 @@ fn extract_text_inner<'local>(env: &mut Env<'local>, handle: jlong) -> jstring { Some(t) => match env.new_string(t) { Ok(js) => Some(js), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); None } },@@ -139,7 +136,7 @@ fn search_document_inner_fn<'local>( } }; if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } bytes_or_null_mut(env, search_document(handle, &q))@@ -158,7 +155,7 @@ fn search_document_cs_inner<'local>( } }; if env.ensure_local_capacity(4).is_err() {- let _ = env.exception_clear();+ env.exception_clear(); return std::ptr::null_mut(); } bytes_or_null_mut(env, search_document_case_sensitive(handle, &q))@@ -180,7 +177,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_openDocument<'loc match catch_unwind(AssertUnwindSafe(|| open_document_inner(&mut *env, data))) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in openDocument")); Ok(0) }@@ -203,7 +200,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_openDocumentWithP })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in openDocumentWithPassword")); Ok(0) }@@ -223,7 +220,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_pdfPasswordState< match catch_unwind(AssertUnwindSafe(|| pdf_password_state_inner(&mut *env, data))) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in pdfPasswordState")); Ok(0) }@@ -247,7 +244,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_saveEncrypted<'lo })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in saveEncrypted")); Ok(std::ptr::null_mut()) }@@ -267,7 +264,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_getPageCount<'loc match catch_unwind(AssertUnwindSafe(|| page_count(handle))) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in getPageCount")); Ok(0) }@@ -289,7 +286,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_renderPage<'local match catch_unwind(AssertUnwindSafe(|| render_page_inner(&mut *env, handle, index))) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in renderPage")); Ok(std::ptr::null_mut()) }@@ -310,7 +307,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_closeDocument<'lo close_document(handle); })); if res.is_err() {- let _ = env.exception_clear();+ env.exception_clear(); } Ok(()) })@@ -327,7 +324,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_createEmptyDocume match catch_unwind(AssertUnwindSafe(create_empty_document)) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in createEmptyDocument")); Ok(0) }@@ -349,7 +346,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_appendPdf<'local> match catch_unwind(AssertUnwindSafe(|| append_pdf_inner(&mut *env, handle, data))) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in appendPdf")); Ok(0) }@@ -375,7 +372,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_appendImagePage<' })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in appendImagePage")); Ok(0) }@@ -405,7 +402,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_movePage<'local>( })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(false) } }@@ -432,7 +429,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_removePage<'local })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(false) } }@@ -454,7 +451,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_rotatePage<'local match catch_unwind(AssertUnwindSafe(|| rotate_page(handle, index, delta))) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(false) } }
pdf/src/main/rust/src/jni_bindings_part2.rs
diff --git a/pdf/src/main/rust/src/jni_bindings_part2.rs b/pdf/src/main/rust/src/jni_bindings_part2.rsindex 51cb39aa3b..82706644af 100644--- a/pdf/src/main/rust/src/jni_bindings_part2.rs+++ b/pdf/src/main/rust/src/jni_bindings_part2.rs@@ -10,7 +10,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_extractPage<'loca match catch_unwind(AssertUnwindSafe(|| extract_page_inner(&mut *env, handle, index))) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in extractPage")); Ok(std::ptr::null_mut()) }@@ -33,7 +33,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_listAnnotations<' })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(std::ptr::null_mut()) } }@@ -55,7 +55,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_listFormFields<'l })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(std::ptr::null_mut()) } }@@ -76,7 +76,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_listLinks<'local> })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(std::ptr::null_mut()) } }@@ -102,11 +102,11 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addTextAnnotation env.with_env(|env| -> jni::errors::Result<jlong> { let _invalidate = InvalidateSearchIndex(handle); match catch_unwind(AssertUnwindSafe(|| {- add_free_text_inner(&mut *env, handle, page, x0, y0, x1, y1, argb, size, text)+ add_free_text_inner(&mut *env, handle, page, [x0, y0, x1, y1], argb, size, text) })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); let _ = env.throw_new(jni_str!("java/lang/RuntimeException"), jni_str!("Native panic in addTextAnnotation")); Ok(0) }@@ -141,7 +141,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addHighlight<'loc })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -177,7 +177,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addTextMarkup<'lo })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -203,7 +203,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addNote<'local>( })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -229,11 +229,11 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addCallout<'local env.with_env(|env| -> jni::errors::Result<jlong> { let _invalidate = InvalidateSearchIndex(handle); match catch_unwind(AssertUnwindSafe(|| {- add_callout_inner(&mut *env, handle, page, ax, ay, bx, by, argb, size, text)+ add_callout_inner(&mut *env, handle, page, [ax, ay, bx, by], argb, size, text) })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -271,7 +271,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addRectAnnotation })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -309,7 +309,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addCircleAnnotati })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -334,11 +334,11 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addPolyAnnotation env.with_env(|env| -> jni::errors::Result<jlong> { let _invalidate = InvalidateSearchIndex(handle); match catch_unwind(AssertUnwindSafe(|| {- add_poly_inner(&mut *env, handle, page, argb, line_width, fill, closed, pts)+ add_poly_inner(&mut *env, handle, page, argb, line_width, (fill, closed), pts) })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -364,7 +364,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addInkAnnotation< })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -391,11 +391,11 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_addImageStamp<'lo env.with_env(|env| -> jni::errors::Result<jlong> { let _invalidate = InvalidateSearchIndex(handle); match catch_unwind(AssertUnwindSafe(|| {- add_stamp_inner(&mut *env, handle, page, x0, y0, x1, y1, img_w, img_h, jpeg)+ add_stamp_inner(&mut *env, handle, page, [x0, y0, x1, y1], (img_w, img_h), jpeg) })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(0) } }@@ -428,7 +428,7 @@ pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_updateAnnotationR })) { Ok(v) => Ok(v), Err(_) => {- let _ = env.exception_clear();+ env.exception_clear(); Ok(false) } }@@ -451,7 +451,7 @@ pub extern "syste
Diff truncated.