Modern Apps git

← Modern-Apps.git

pdf: fix redaction leak, flatten resources, CCITT and filter fallbacks (#321)

Commit
06dfe1fbfc011b36157681ae7d9df8750e2bfcc2
Author
vayun-mathur <[email protected]>
When
2026-08-31 18:26 UTC (3 months ago)
Parents
ea60b8e

Diff

pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.ktindex a0c3b02cd0..34246e2a5a 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -1587,6 +1587,25 @@ private const val MIN_EMBEDDED_GLYPHS_FOR_TEXT = 6 /** Max distance (page px) a long-press may be from a glyph to start a selection. */ private const val SELECT_HIT_PX = 80f +/**+ * Bounds on the wire's horizontal text scale, applied to `Paint.textScaleX`.+ *+ * The field is `Th * x_scale / y_scale` (draw.rs), not the Tz percentage its name suggests,+ * so it legitimately reaches the single digits on an anisotropic text matrix. The clamp+ * exists only to bound what Skia is asked to raster — `textScaleX` multiplies the glyph's+ * device width, and an unbounded value blows up the glyph cache — not to express any PDF+ * limit. Both consumers must use the same range: [drawSafePage] paints with it and+ * [buildEmbeddedGlyphs] measures selection rectangles with it, and they have to agree.+ *+ * Rust bounds the geometric factor to the same 0.01..100 before it reaches the wire, so on+ * a well-formed stream this clamp normally never bites. It is deliberately kept as a+ * second line: Rust does NOT bound the Tz half of the product (`interpret.rs` takes+ * `Tz / 100` unchecked), so a pathological `Tz` still arrives large. NaN is handled at the+ * decoder instead — `coerceIn` propagates it — see the hScale read in [SafePdfParser].+ */+private const val MIN_TEXT_H_SCALE = 0.01f+private const val MAX_TEXT_H_SCALE = 100f+ /**  * Build ordered selectable glyphs from a page's embedded Text primitives. Uses  * accurate glyph advances via Text.advance and Paint.measureText for ligatures /@@ -1605,20 +1624,26 @@ private fun buildEmbeddedGlyphs(page: SafePdfPage, ch: Float, scale: Float): Lis         tmpPaint.typeface = selTf         tmpPaint.isFakeBoldText = prim.isBold && !selTf.isBold         tmpPaint.textSkewX = if (prim.isItalic && !selTf.isItalic) -0.25f else 0f-        tmpPaint.textScaleX = prim.hScale.coerceIn(0.2f, 4f)+        tmpPaint.textScaleX = prim.hScale.coerceIn(MIN_TEXT_H_SCALE, MAX_TEXT_H_SCALE)         tmpPaint.textSize = prim.size * scale         val textStr = prim.text         val measuredTotal = tmpPaint.measureText(textStr)         // A run that is PAINTED (drawText with this same paint) occupies exactly         // measuredTotal, so per-glyph measured widths are what put the selection rects on-        // the pixels the user sees. A run that is NOT painted — render mode 3, the invisible-        // OCR layer of a scanned PDF, or a glyph already drawn from its real outline — is-        // aligned to the scan underneath instead, and only `advance` (the true device-space-        // advance, wire v7) knows where that is. Substitute-typeface metrics have no relation-        // to it, so rescale the run to span `advance`. Characters are still spread evenly-        // within the run, as they were before — the fix is the run's total extent, which is-        // where the error accumulated and grew with run length.-        val alignToAdvance = prim.renderMode == 3 || prim.outline+        // the pixels the user sees. A run that is NOT painted is aligned to whatever is+        // underneath instead, and only `advance` (the true device-space advance, wire v7)+        // knows where that is. Substitute-typeface metrics have no relation to it, so+        // rescale the run to span `advance`. Characters are still spread evenly within the+        // run, as they were before — the fix is the run's total extent, which is where the+        // error accumulated and grew with run length.+        //+        // §9.3.6 Table 106 makes modes 3 AND 7 the two that paint nothing — 3 invisible,+        // 7 clip-only — so both belong here, along with a glyph already drawn from its real+        // outline. Mode 7 was originally missed because it was rare; it stopped being rare+        // when interpret.rs:118 `hidden_render_mode` began routing OC-hidden clipping runs+        // to 7 instead of collapsing them to 3, which is where that text used to pick up+        // this alignment.+        val alignToAdvance = prim.renderMode == 3 || prim.renderMode == 7 || prim.outline         val advanceFit = if (alignToAdvance && measuredTotal > 0f && prim.advance > 0f) {             prim.advance * scale / measuredTotal         } else {@@ -2951,13 +2976,25 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                 // generic family (sans/serif/mono) + bold/italic recovered by Rust. Rust                 // already emits one glyph per prim at its exact advance-based origin, so                 // letters are correctly spaced without distorting glyph widths — we draw-                // each glyph at its natural width and only apply Tz (hScale).+                // each glyph at its natural width and apply the wire's horizontal scale.                 val tf = pdfTypeface(prim.fontFamily, prim.isBold, prim.isItalic)                 // Only synthesize bold/italic when the real typeface can't supply it,                 // so a genuine bold serif isn't double-weighted into a heavy/wrong look.                 val fakeBold = prim.isBold && !tf.isBold                 val skew = if (prim.isItalic && !tf.isItalic) -0.25f else 0f-                val hs = prim.hScale.coerceIn(0.2f, 4f)+                // hScale is NOT Tz alone. `draw.rs`'s `show_string_in` sends+                // `Th * x_scale / y_scale` as its `wire_h_scale`,+                // because `size` carries only the matrix's Y scale, so the X/Y ratio has+                // nowhere else to ride. It is 1.0 for every isotropic matrix, rotations+                // included, and a 4x horizontal stretch (`4 0 0 1 0 0 cm`, ordinary for+                // expanded display text) reaches 4.0 on its own — so the old 0.2..4 range,+                // sized for Tz percentages of 50..200, clamped legitimate anisotropy and+                // drew that text too narrow. Widened to admit real matrices while still+                // bounding what Skia is asked to raster: textScaleX multiplies the glyph's+                // device width, so an unbounded value blows up the glyph cache. Keep this+                // range identical to the one in buildEmbeddedGlyphs, or the selection+                // rectangles stop matching the painted glyphs.+                val hs = prim.hScale.coerceIn(MIN_TEXT_H_SCALE, MAX_TEXT_H_SCALE)                 textPaint.typeface = tf                 textPaint.textSize = ts                 textPaint.isFakeBoldText = fakeBold
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.ktindex 3fd48955b4..92f7f9090e 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -93,7 +93,14 @@ class SafePdfDocument private constructor(                     cachedBytes = (cachedBytes - pageWeightBytes(evicted)).coerceAtLeast(0L)                 }             }-            cache[index] = page+            // The cache lookup at the top of renderPage is outside this lock, so two+            // coroutines can both miss for the same index and both insert. A replacing put+            // does not call removeEldestEntry, so the displaced page's weight was never+            // subtracted and cachedBytes drifted upward for the rest of the session —+            // permanently over-budget, evicting pages that fit and re-decoding them.+            cache.put(index, page)?.let { displaced ->+                cachedBytes = (cachedBytes - pageWeightBytes(displaced)).coerceAtLeast(0L)+            }         }         page     }
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.ktindex c3574f7458..45e9b85c9f 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt@@ -28,9 +28,9 @@ sealed interface PdfPrimitive {      * A run of text with its baseline origin, on-page size and color. Optional      * stroke for Tr modes 1,2,5,6. [renderMode] is the PDF text render mode (Tr):      * 0 fill, 1 stroke, 2 fill+stroke, 3 invisible, 4-6 = 0-2 plus clip, 7 clip.-     * v8 adds isBold/isItalic/hScale recovered from font BaseFont/FontDescriptor.-     * [fontFamily] selects the substitute system typeface: 0 sans-serif, 1 serif,-     * 2 monospace (also from BaseFont/FontDescriptor).+     * v8 adds isBold/isItalic recovered from font BaseFont/FontDescriptor, plus+     * [hScale]. [fontFamily] selects the substitute system typeface: 0 sans-serif,+     * 1 serif, 2 monospace (also from BaseFont/FontDescriptor).      */     data class Text(         val origin: Offset,@@ -48,6 +48,16 @@ sealed interface PdfPrimitive {         /// True when the glyph was already drawn via Fill prims (embedded-font         /// outline rendering); kept only for text selection/search, not painted.         val outline: Boolean = false,+        /**+         * Horizontal scale for the substitute face, applied as `Paint.textScaleX`.+         *+         * NOT the Tz percentage the name suggests: `draw.rs`'s `show_string_in` sends+         * `Th * x_scale / y_scale` (its `wire_h_scale`), because [size] carries only the+         * text matrix's Y+         * scale, so an anisotropic matrix has nowhere else to put its X/Y ratio. Exactly+         * 1.0 for every isotropic matrix, rotations included, so ordinary pages are+         * unaffected; a `4 0 0 1 0 0 cm` stretch sends 4.0.+         */         val hScale: Float = 1f,     ) : PdfPrimitive 
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.ktindex c68ef4f2b3..48c69b83dd 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -200,6 +200,23 @@ object SafePdfParser {         return PdfPrimitive.SoftMaskTransfer(gain.toFloat(), bias.toFloat(), affine)     } +    /**+     * This value, or [fallback] when the wire carried a non-finite one.+     *+     * Every float here arrives as four arbitrary bytes across JNI, so NaN and infinity are+     * always representable no matter what the producer guarantees — a desynced buffer alone+     * produces NaN from any bit pattern in the quiet range. They are worth singling out+     * because the usual Kotlin range guards do NOT stop them: `coerceIn` and `coerceAtLeast`+     * are written as `if (this < min) ... else this`, and every comparison against NaN is+     * false, so NaN passes through both untouched and lands in `Paint.textSize`,+     * `Paint.textScaleX` or a selection rectangle. Infinity survives a `> 0f` guard for the+     * same reason and then poisons the running geometry of a whole text run.+     *+     * `draw.rs` also bounds these at the producer, which is the right place for the+     * geometry; this is the decoder refusing to depend on that promise.+     */+    private fun Float.orIfNonFinite(fallback: Float): Float = if (isFinite()) this else fallback+     fun parse(bytes: ByteArray): SafePdfPage {         val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)         if (buf.remaining() < 12) throw IllegalArgumentException("Buffer too small")@@ -224,8 +241,14 @@ object SafePdfParser {             countRaw = buf.int         } -        // Safety guards: count caps, version enforcement, dimension sanity-        if (width <= 0f || height <= 0f || width > 20000f || height > 20000f) {+        // Safety guards: count caps, version enforcement, dimension sanity.+        // NaN is checked explicitly: every comparison against it is false, so a NaN width+        // passes `<= 0f` and `> 20000f` alike and reaches SafePdfPageCanvas, whose+        // `Modifier.aspectRatio(width / height)` requires a ratio > 0 and throws on NaN —+        // taking down the composition rather than the one page.+        if (!width.isFinite() || !height.isFinite() ||+            width <= 0f || height <= 0f || width > 20000f || height > 20000f+        ) {             throw IllegalArgumentException("Invalid page dimensions $width x $height")         }         if (countRaw < 0) {@@ -277,7 +300,10 @@ object SafePdfParser {                 TAG_TEXT -> {                     val x = buf.float                     val y = buf.float-                    val size = buf.float+                    // Reachable without exotic syntax: an overflowing `Tf` literal times a+                    // zero-scale matrix is `inf * 0` = NaN. Zero here becomes one pixel via+                    // the renderer's floor, rather than a NaN Paint.textSize.+                    val size = buf.float.orIfNonFinite(0f)                     val argb = buf.int                     val len = buf.short.toInt() and 0xFFFF                     // No upper-bound rejection: len is u16-bounded and Rust truncates at@@ -295,7 +321,7 @@ object SafePdfParser {                         val sWidth = buf.float                         if (hasStroke) {                             strokeColor = sArgb-                            strokeWidth = sWidth+                            strokeWidth = sWidth.orIfNonFinite(0f)                         } else {                             strokeColor = null                             strokeWidth = 0f@@ -314,12 +340,16 @@ object SafePdfParser {                     } else BlendMode.Normal                     val txt = String(strBytes, Charsets.UTF_8)                     // v7 carries the true device-space glyph advance; older wires-                    // fall back to the size*0.5*len heuristic.+                    // fall back to the size*0.5*len heuristic, and so does a non-finite+                    // one. buildEmbeddedGlyphs guards this with `advance > 0f`, which+                    // INFINITY passes, and it then scales the whole run's selection+                    // geometry to infinity off one overflowed glyph.+                    val advHeuristic = size * 0.5f * txt.length.coerceAtLeast(1)                     val adv = if (isV7) {                         if (buf.remaining() < 4) throw IllegalArgumentException("Text v7 advance truncated")-                        buf.float+                        buf.float.orIfNonFinite(advHeuristic)                     } else {-                        size * 0.5f * txt.length.coerceAtLeast(1)+                        advHeuristic                     }                     val isBold: Boolean                     val isItalic: Boolean@@ -335,7 +365,11 @@ object SafePdfParser {                         fontFamily = (fontFlags shr 2) and 0x3                         // Bit 4: glyph already drawn as outline fills (don't paint).                         outline = fontFlags and 0x10 != 0-                        hScale = buf.float+                        // Fall back to the identity rather than trusting the producer to+                        // have bounded this. Rust bounds the geometric half (draw.rs+                        // `aniso.clamp`) but the Tz half is a bare `v / 100.0` at+                        // interpret.rs, and these bytes are the trust boundary regardless.+                        hScale = buf.float.orIfNonFinite(1f)                     } else {                         isBold = false                         isItalic = false@@ -343,6 +377,16 @@ object SafePdfParser {                         outline = false                         hScale = 1f                     }+                    // Unlike the scalars above there is no sane default for a position, and+                    // a NaN origin is not harmless: it paints nothing but still produces a+                    // selection rectangle whose distance comparisons are all false, which+                    // breaks nearestGlyph for the page. Every byte of this primitive has+                    // been consumed, so dropping it leaves the stream in sync, and Text+                    // carries no bracket that a later primitive is paired with.+                    if (!x.isFinite() || !y.isFinite()) {+                        android.util.Log.w(TAG, "text primitive $primIndex has a non-finite origin, dropping it")+                        continue+                    }                     primitives.add(                         PdfPrimitive.Text(                             origin = Offset(x, y),@@ -383,9 +427,14 @@ object SafePdfParser {                 TAG_STROKE -> {                     val argb = buf.int                     val strokeWidth = buf.float-                    // u8 on the wire, so the allocation is bounded at 255 regardless; Rust-                    // caps at MAX_DASH_LEN (64). Never reject — the old `> 32` throw-                    // discarded the whole page over one stroke's dash array.+                    // u8 on the wire, so the allocation is bounded at 255 regardless.+                    // Rust's `MAX_DASH_LEN` is 32 (graphics_state.rs), not 64 — but+                    // `draw::emit_stroke` duplicates an odd-length array, since §8.4.3.6+                    // needs an even number of on/off phases, so the count actually EMITTED+                    // can be up to twice that. 64 is that doubled worst case, not the+                    // constant. Never reject — the old `> 32` throw discarded the whole+                    // page over one stroke's dash array, and nothing here depends on the+                    // producer's bound anyway.                     val nDash = buf.get().toInt() and 0xFF                     if (buf.remaining() < nDash*4+4) throw IllegalArgumentException("Stroke dash truncated")                     val dash = FloatArray(nDash) { buf.float }
pdf/src/main/rust/src/afm.rs
diff --git a/pdf/src/main/rust/src/afm.rs b/pdf/src/main/rust/src/afm.rsindex 0edc401682..5dbe6bde74 100644--- a/pdf/src/main/rust/src/afm.rs+++ b/pdf/src/main/rust/src/afm.rs@@ -72,10 +72,14 @@ fn resolve_face(base_font: &str) -> Option<Face> {     if n.contains("symbol") {         return Some(Face::Symbol);     }-    if n.contains("courier") || n.contains("mono") {+    // "monotype" is a foundry name, not a monospaced face: Monotype Corsiva is a+    // script font and must not be given Courier's uniform 600-unit advance.+    if n.contains("courier") || (n.contains("mono") && !n.contains("monotype")) {         return Some(Face::Courier);     }-    if n.contains("times") || n.contains("serif") {+    // "sans" wins over "serif" because "sans-serif" contains both, and this test+    // runs first: without the exclusion every sans-serif face took Times metrics.+    if n.contains("times") || (n.contains("serif") && !n.contains("sans")) {         return Some(match (bold, italic) {             (true, true) => Face::TimesBoldItalic,             (true, false) => Face::TimesBold,@@ -482,6 +486,37 @@ static TIMES_BOLD_ITALIC: &[(&str, u16)] = &[ ];  // Symbol uses its own encoding; widths are keyed by the AFM glyph names.+//+// KNOWN GAP: this stops at code 0x7E ("similar"). Every Symbol code >= 0xA0 —+// the math operators, arrows, card suits and the bracket/integral build-up+// pieces — has no width here and falls to `default_width` (0.5 em) in+// `fonts.rs`. The real values are far from uniform (build-up pieces ~274-384,+// several operators 700+), so a line of Symbol math drifts both ways. Left+// unfilled rather than guessed: these numbers cannot be verified against+// Adobe's Symbol.afm from this tree, and a plausible-but-wrong advance for+// every math glyph is worse than one uniform one. Needs `/Widths` to be absent+// entirely to matter at all, which is legacy TeX/dvips-era files. The Greek+// alphabet is unaffected — Symbol puts Alpha..Omega and alpha..omega in+// 0x41-0x7A, inside the covered range.+//+// BEFORE ADDING ROWS, read this. `fonts.rs`'s code -> name chain ends in a+// last-resort guess against `type1::STANDARD_ENCODING`, and that step runs for+// every face, Symbol included, even though the two encodings are unrelated.+// Today it is harmless precisely BECAUSE this table stops at 0x7E: above it the+// Standard-guessed name ("section" for 0xA7, where Symbol has `club`) finds no+// row, so the lookup falls through to the code -> Unicode -> width path that+// does know about Symbol. Add a row whose name StandardEncoding also uses at a+// DIFFERENT code and the guess starts winning, silently charging that glyph the+// other encoding's width. The two encodings share exactly four names above+// 0xA0 — `fraction` (164), `florin` (166), `bullet` (183) and `ellipsis` (188)+// — and all four sit at the SAME code in both, so those are safe. Any name+// outside that set must be checked against `STANDARD_ENCODING` first.+//+// That check is ENFORCED, not just documented: `fonts.rs`'s+// `blind_reaudit_r5_width_tests::the_standard_encoding_guess_never_contradicts_symbols_own_encoding`+// walks every `STANDARD_ENCODING` entry and asserts that wherever the Standard+// guess and Symbol's own encoding both produce a width for a code, they agree.+// A colliding row added here fails that test with the code and both widths. static SYMBOL: &[(&str, u16)] = &[     ("space", 250), ("exclam", 333), ("universal", 713), ("numbersign", 500),     ("existential", 549), ("percent", 833), ("ampersand", 778), ("suchthat", 439),@@ -587,4 +622,18 @@ mod tests {         assert!(standard_14_widths("ZapfDingbats").is_some());         assert!(standard_14_widths("SomeRandomFont").is_none());     }++    #[test]+    fn foundry_and_family_names_do_not_hijack_a_face() {+        // "Monotype Corsiva" is a script face; it contains "mono" but is not+        // monospaced, and Courier's flat 600 would mis-space every glyph.+        let corsiva = standard_14_widths("MonotypeCorsiva");+        assert!(corsiva.is_none() || corsiva.as_ref().unwrap()["i"] != 0.6);+        // "sans-serif" contains "serif"; the serif test runs first, so without the+        // exclusion a sans face was given Times metrics.+        let sans = standard_14_widths("Some-Sans-Serif").expect("resolves to Helvetica");+        assert_eq!(sans["space"], 0.278, "sans-serif must not take Times' 250");+        // A real serif name still resolves to Times.+        assert_eq!(standard_14_widths("NimbusSerif").unwrap()["space"], 0.25);+    } }
pdf/src/main/rust/src/annotations.rs
diff --git a/pdf/src/main/rust/src/annotations.rs b/pdf/src/main/rust/src/annotations.rsindex 1c221699a6..bc4eb94a60 100644--- a/pdf/src/main/rust/src/annotations.rs+++ b/pdf/src/main/rust/src/annotations.rs@@ -371,6 +371,21 @@ fn annot_border_dash(doc: &Document, dict: &lopdf::Dictionary) -> Vec<f64> {     Vec::new() } +/// Numbers of an annotation's coordinate array (`/QuadPoints`, `/L`,+/// `/Vertices`, one `/InkList` path), or `None` when any of them is non-finite.+///+/// §7.3.3 numbers are finite, but a real with more digits than `f32` can hold+/// parses to an infinity, and one poisoned coordinate propagates through every+/// primitive derived from it — the rasterizer drops a path containing a+/// non-finite point silently, so the annotation vanishes with no error+/// anywhere. Rejecting the whole array matches `read_rect`'s treatment of a+/// non-finite `/Rect`, and matches this function's rule for missing geometry:+/// draw nothing rather than a shape the file did not actually give.+fn finite_coords(doc: &Document, obj: &Object) -> Option<Vec<f64>> {+    let v: Vec<f64> = deref(doc, obj)?.as_array().ok()?.iter().filter_map(num).collect();+    v.iter().all(|n| n.is_finite()).then_some(v)+}+ /// Synthesize a basic appearance for annotation types that lack an `/AP` stream. /// /// Only shapes the file actually specifies are drawn: Square/Circle from `/Rect`,@@ -431,9 +446,8 @@ pub(crate) fn synthesize_annotation_appearance(      // QuadPoints (text markup): 8 numbers per quad.     let quads: Vec<[(f64,f64);4]> = dict.get(b"QuadPoints").ok()-        .and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok())-        .map(|a| {-            let v: Vec<f64> = a.iter().filter_map(num).collect();+        .and_then(|o| finite_coords(doc, o))+        .map(|v| {             v.chunks_exact(8).map(|q| [(q[0],q[1]),(q[2],q[3]),(q[4],q[5]),(q[6],q[7])]).collect()         }).unwrap_or_default(); @@ -467,7 +481,7 @@ pub(crate) fn synthesize_annotation_appearance(             }         }         b"Line" => {-            let l_arr: Option<Vec<f64>> = dict.get(b"L").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok()).map(|a| a.iter().filter_map(num).collect());+            let l_arr: Option<Vec<f64>> = dict.get(b"L").ok().and_then(|o| finite_coords(doc, o));             if let Some(n) = l_arr {                 if n.len() >= 4 {                     let (p0, p1) = ((n[0], n[1]), (n[2], n[3]));@@ -507,7 +521,10 @@ pub(crate) fn synthesize_annotation_appearance(                 let d = annot_border_dash(doc, dict);                 if !d.is_empty() { sgs.dash = d; }                 for p in paths {-                    let n: Vec<f64> = p.as_array().map(|a| a.iter().filter_map(num).collect()).unwrap_or_default();+                    let n = match finite_coords(doc, p) {+                        Some(n) => n,+                        None => continue,+                    };                     let pts: Vec<(f64,f64)> = n.chunks_exact(2).map(|c| dev(c[0], c[1])).collect();                     if pts.len() >= 2 { emit_stroke(prims, std::slice::from_ref(&pts), &sgs); }                 }@@ -584,8 +601,7 @@ pub(crate) fn synthesize_annotation_appearance(             // draw nothing rather than the /Rect outline the old code fell back             // to — a rectangle is indistinguishable from a Square annotation and             // claims a geometry the file never gave.-            if let Some(Object::Array(verts)) = dict.get(b"Vertices").ok().and_then(|o| deref(doc, o)) {-                let n: Vec<f64> = verts.iter().filter_map(num).collect();+            if let Some(n) = dict.get(b"Vertices").ok().and_then(|o| finite_coords(doc, o)) {                 let pts: Vec<(f64,f64)> = n.chunks_exact(2).map(|c| dev(c[0], c[1])).collect();                 if pts.len() >= 2 {                     let closed = subtype == b"Polygon";@@ -2574,4 +2590,57 @@ mod synthesis_tests {             .expect("no stroke");         assert_eq!(argb, 0xFFFF_0000, "indirect /C ignored, fell back to black");     }++    /// §7.3.3 numbers are finite, but a real with more digits than `f32` holds+    /// parses to an infinity. One such coordinate reaches every primitive built+    /// from it, and the rasterizer drops a path containing a non-finite point+    /// silently — so the annotation disappears with no error rather than being+    /// visibly malformed. Draw nothing instead, as for absent geometry.+    #[test]+    fn non_finite_geometry_draws_nothing_rather_than_a_poisoned_path() {+        // A real with more digits than f32 can hold parses to this.+        let bad = Object::Real(f32::INFINITY);+        let ok = |v: f64| Object::Real(v as f32);++        let mut line = annot("Line");+        line.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));+        line.set("L", Object::Array(vec![ok(0.0), ok(0.0), bad.clone(), ok(10.0)]));+        assert!(synth(&line, [0.0, 0.0, 100.0, 20.0]).is_empty(), "/L");++        let mut poly = annot("Polygon");+        poly.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));+        poly.set(+            "Vertices",+            Object::Array(vec![ok(0.0), ok(0.0), ok(10.0), bad.clone(), ok(5.0), ok(9.0)]),+        );+        assert!(synth(&poly, [0.0, 0.0, 100.0, 20.0]).is_empty(), "/Vertices");++        let mut ink = annot("Ink");+        ink.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));+        ink.set(+            "InkList",+            Object::Array(vec![+                Object::Array(vec![ok(0.0), ok(0.0), bad.clone(), ok(1.0)]),+                Object::Array(vec![ok(0.0), ok(0.0), ok(9.0), ok(9.0)]),+            ]),+        );+        let strokes = synth(&ink, [0.0, 0.0, 100.0, 20.0]);+        assert_eq!(strokes.len(), 1, "the poisoned /InkList path drops, the clean one stays");++        let mut hl = annot("Highlight");+        hl.set(+            "QuadPoints",+            Object::Array(vec![+                ok(0.0), ok(10.0), bad, ok(10.0), ok(0.0), ok(0.0), ok(100.0), ok(0.0),+            ]),+        );+        // Falls back to the /Rect quad, which `read_rect` has already proven finite.+        for p in synth(&hl, [0.0, 0.0, 100.0, 10.0]) {+            if let Prim::Fill { contours, .. } = p {+                for (x, y) in contours.iter().flatten() {+                    assert!(x.is_finite() && y.is_finite(), "non-finite point reached a Fill");+                }+            }+        }+    } }
pdf/src/main/rust/src/cff.rs
diff --git a/pdf/src/main/rust/src/cff.rs b/pdf/src/main/rust/src/cff.rsindex 9af6664012..20df68fb91 100644--- a/pdf/src/main/rust/src/cff.rs+++ b/pdf/src/main/rust/src/cff.rs@@ -43,15 +43,21 @@ fn read_index(d: &[u8], pos: usize) -> Option<Index> {     if count == 0 {         return Some(Index { entries: Vec::new(), end: pos + 2 });     }-    // u16 max is 65535, but sanity cap to avoid DoS from huge counts-    if count > 32767 {-        return None;-    }+    // `count` is a u16, so the offset array is at most 65536 entries (~1 MB of+    // `entries`); no further cap is needed and capping lower would reject the+    // large CID-keyed CJK fonts that legitimately carry more than 32767 glyphs.     let off_size = u8a(d, pos + 2)?;     if off_size == 0 || off_size > 4 {         return None;     }     let off_array = pos + 3;+    // Size the allocations from what the file actually contains, not from the+    // declared count: `count` is attacker-controlled and would otherwise reserve+    // (count+1) offsets for a truncated INDEX. The offset array must be present.+    let off_bytes = (count + 1).checked_mul(off_size as usize)?;+    if off_array.checked_add(off_bytes)? > d.len() {+        return None;+    }     let mut offs = Vec::with_capacity(count + 1);     for i in 0..=count {         offs.push(offat(d, off_array + i * off_size as usize, off_size)?);@@ -560,7 +566,7 @@ fn parse(d: &[u8]) -> Option<HashMap<u32, char>> {         let cs_off = *top.get(&17)?.first()? as usize;         read_index(d, cs_off)?.entries.len()     };-    if nglyphs == 0 || nglyphs > 32767 {+    if nglyphs == 0 || nglyphs > 65535 {         return None;     } @@ -650,8 +656,9 @@ fn parse(d: &[u8]) -> Option<HashMap<u32, char>> {     Some(out) } -/// The 391 CFF standard strings (SID 0..390) — authoritative Adobe CFF2 list (Adobe TN #5176 + CFF2 extensions).-// Full verified length 391, last entry bracketleftbt matches FreeType & fontTools.+/// The 391 CFF standard strings (SID 0..390) — Adobe TN #5176 Appendix A.+// SID 390 is "Semibold"; SIDs 379..390 are the version/weight strings+// ("001.000" .. "Semibold"), which is the distinguishing tail of this table. const STD_STRINGS: &[&str] = &[     ".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand",     "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period",@@ -698,10 +705,10 @@ const STD_STRINGS: &[&str] = &[     "threeinferior", "fourinferior", "fiveinferior", "sixinferior", "seveninferior", "eightinferior", "nineinferior", "centinferior",     "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", "Atildesmall", "Adieresissmall",     "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall",-    "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall",-    "Odieresissmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Emacronsmall", "Omacronsmall", "Umacronsmall",-    "radicalex", "arrowvertex", "arrowhorizex", "registersans", "copyrightsans", "trademarksans", "parenlefttp", "parenrighttp",-    "parenleftbt", "parenrightbt", "parenleftalt", "parenrightalt", "bracketlefttp", "bracketrighttp", "bracketleftbt",+    "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall",+    "Otildesmall", "Odieresissmall", "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall",+    "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000", "001.001", "001.002", "001.003", "Black",+    "Bold", "Book", "Light", "Medium", "Regular", "Roman", "Semibold", ];  @@ -772,4 +779,64 @@ mod tests {         assert_eq!(sids.get(&2), None);     } +    #[test]+    fn std_strings_tail_is_the_version_and_weight_block() {+        // Adobe TN #5176 Appendix A: SIDs 363..390 run Ethsmall .. Semibold and+        // end with the version/weight strings. The tail previously held+        // MacExpert/Symbol names (radicalex, arrowvertex, parenlefttp, …), which+        // are not CFF standard strings at all, so every charset entry with a SID+        // above 362 resolved to the wrong glyph name — and therefore, for a+        // name-keyed CFF, to the wrong Unicode in the built-in encoding.+        assert_eq!(STD_STRINGS[363], "Ethsmall");+        assert_eq!(STD_STRINGS[378], "Ydieresissmall");+        assert_eq!(STD_STRINGS[379], "001.000");+        assert_eq!(STD_STRINGS[390], "Semibold");+        for bogus in ["radicalex", "arrowvertex", "parenlefttp", "bracketleftbt", "Emacronsmall"] {+            assert!(!STD_STRINGS.contains(&bogus), "{bogus} is not a CFF standard string");+        }+    }++    /// 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+    }++    #[test]+    fn index_count_is_bounded_by_the_format_not_by_a_lower_cap() {+        // A CFF INDEX count is a u16, so 32768..=65535 entries are legal, and+        // CID-keyed CJK fonts really do carry that many glyphs. Rejecting them+        // made `cid_to_gid_map` return None, and the caller then falls back to+        // CID==GID identity — silently drawing a different glyph per character.+        let d = empty_index(40000);+        let idx = read_index(&d, 0).expect("a 40000-entry INDEX is legal CFF");+        assert_eq!(idx.entries.len(), 40000);+        assert_eq!(idx.end, d.len());+    }++    #[test]+    fn index_offset_array_must_fit_in_the_data() {+        // `count` is attacker-controlled and sizes two allocations. A header+        // claiming 65535 four-byte offsets over 8 bytes of file must be rejected+        // before anything is reserved.+        let d = [0xFFu8, 0xFF, 4, 0, 0, 0, 1, 0];+        assert!(read_index(&d, 0).is_none());+        let mut short = empty_index(500);+        short.truncate(100);+        assert!(read_index(&short, 0).is_none());+    }++    #[test]+    fn charset_bounds_follow_the_string_index_size() {+        // Format 0 at offset 1 (offset 0 means the predefined ISOAdobe charset),+        // 3 glyphs, SIDs 391 and 392: legal only when the String INDEX supplies at+        // least two custom strings.+        let d = [0xFFu8, 0x00, 0x01, 0x87, 0x01, 0x88];+        let with_strings = parse_charset(&d, 1, 3, 2, false).unwrap();+        assert_eq!(with_strings.get(&1), Some(&391));+        assert_eq!(with_strings.get(&2), Some(&392));+        let without = parse_charset(&d, 1, 3, 0, false).unwrap();+        assert_eq!(without.get(&1), None, "a SID past the standard strings is dropped");+    } }
pdf/src/main/rust/src/color.rs
diff --git a/pdf/src/main/rust/src/color.rs b/pdf/src/main/rust/src/color.rsindex bc4d6979a4..c05745bf08 100644--- a/pdf/src/main/rust/src/color.rs+++ b/pdf/src/main/rust/src/color.rs@@ -310,9 +310,9 @@ pub(crate) fn cs_kind_ncomp(kind: &CsKind) -> u8 { /// [`cs_kind_ncomp`] except for Indexed, where one image sample is a single /// palette index (§8.6.6.3), not `base_ncomp` colour components. ///-/// Deliberately separate from [`cs_kind_ncomp`], which `shading.rs` relies on-/// returning `base_ncomp` for Indexed. Clamped to 1..=32 so a bogus `/N` or a-/// 255-name `/DeviceN` cannot turn `w*h*ncomp` into a huge allocation; Pattern+/// Deliberately separate from [`cs_kind_ncomp`], which reports the BASE arity for+/// Indexed because that is what the palette decode needs. Clamped to 1..=32 so a bogus+/// `/N` or a 255-name `/DeviceN` cannot turn `w*h*ncomp` into a huge allocation; Pattern /// (0 components, illegal for an image per §8.9.5.1) recovers as 1. pub(crate) fn cs_kind_image_ncomp(kind: &CsKind) -> u8 {     let n = match kind {@@ -463,10 +463,16 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re         }         CsKind::Lab { white, range, .. } => {             // PDF spec 8.6.5.4 Lab -> XYZ -> (D50->D65 adapt via Bradford) -> sRGB-            let _ = range; // a*/b* already in comps; spec range clamp is done by caller via Decode             let l = comps.first().copied().unwrap_or(0.0).clamp(0.0,100.0);-            let a = comps.get(1).copied().unwrap_or(0.0);-            let b = comps.get(2).copied().unwrap_or(0.0);+            // §8.6.5.4 Table 66: /Range bounds a* and b*, and "values outside the+            // range shall be adjusted to the nearest valid value". The image path+            // already arrives in range via /Decode, but `sc`/`scn` operands and a+            // tint transform whose own /Range is absent do NOT — and an unbounded+            // a*/b* drives `fx`/`fz` far outside the cube-root branch and produces a+            // saturated primary instead of the nearest in-gamut colour.+            let clamp_pair = |v: f64, r: [f64; 2]| v.max(r[0].min(r[1])).min(r[0].max(r[1]));+            let a = clamp_pair(comps.get(1).copied().unwrap_or(0.0), range[0]);+            let b = clamp_pair(comps.get(2).copied().unwrap_or(0.0), range[1]);             let fy = (l + 16.0)/116.0;             let fx = a / 500.0 + fy;             let fz = fy - b / 200.0;@@ -649,13 +655,24 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re             if let Some(tf) = tint_fn {                 // Evaluate the tint transform over all N input components.                 let alt_comps = tf.eval(comps);-                eval_cs_to_rgb(doc, alt, &alt_comps, cs_resources)-            } else {-                // No tint transform: treat each colorant as an independent subtractive-                // ink so all components contribute (0 tint = white, full tint = darker).-                let light: f64 = comps.iter().map(|c| 1.0 - c.clamp(0.0, 1.0)).product();-                Some(gray_to_argb(light))+                // Same arity check the Separation arm applies (§8.6.6.5 defers to+                // §8.6.6.4 for the tint transform): the function shall yield one value+                // per component of the alternate space. Without this the DeviceN arm+                // returned whatever `eval_cs_to_rgb` made of a short tuple — `None` for+                // an RGB/CMYK alternate, which leaves the PREVIOUS fill colour in place,+                // 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) {+                        return Some(rgb);+                    }+                }             }+            // No usable tint transform: treat each colorant as an independent+            // subtractive ink so all components contribute (0 tint = white, full+            // tint = darker).+            let light: f64 = comps.iter().map(|c| 1.0 - c.clamp(0.0, 1.0)).product();+            Some(gray_to_argb(light))         }         CsKind::Pattern { .. } => {             // Pattern color handling: SCN may include base color, we already evaluated base if comps present@@ -697,6 +714,22 @@ pub(crate) fn colorspace_info(     doc: &Document,     cs: Option<&Object>, ) -> (u8, Option<(u8, Vec<u8>)>) {+    colorspace_info_at(doc, cs, 0)+}++/// `MAX_CS_DEPTH` applies here for exactly the reason given at its definition, which+/// this second, parallel implementation of the same walk did not inherit:+/// `[/Indexed 5 0 R 255 <00FF00>]` stored AS object 5 makes the `Indexed` arm below+/// recurse on a reference that resolves back to the same array, forever. A Rust stack+/// overflow is not a panic and cannot be caught, so it takes the process with it.+fn colorspace_info_at(+    doc: &Document,+    cs: Option<&Object>,+    depth: u32,+) -> (u8, Option<(u8, Vec<u8>)>) {+    if depth >= MAX_CS_DEPTH {+        return (1, None);+    }     let cs = match cs.and_then(|o| deref(doc, o)) {         Some(o) => o,         None => return (1, None),@@ -725,7 +758,7 @@ pub(crate) fn colorspace_info(                     (n.max(1), None)                 }                 b"Indexed" | b"I" => {-                    let (base_n, _) = colorspace_info(doc, a.get(1));+                    let (base_n, _) = colorspace_info_at(doc, a.get(1), depth + 1);                     let lookup = match a.get(3).and_then(|o| deref(doc, o)) {                         Some(Object::String(s, _)) => s.clone(),                         // Same reasoning as the `parse_cs_array` Indexed arm above: an@@ -866,7 +899,8 @@ mod tests {     }      // An Indexed image sample is ONE palette index (§8.6.6.3), not base_ncomp colour-    // components. cs_kind_ncomp deliberately still reports base_ncomp for shading.rs.+    // components. cs_kind_ncomp still reports base_ncomp, which is what the palette+    // decode below needs — mesh shadings special-case Indexed themselves.     #[test]     fn indexed_image_ncomp_is_one() {         let cs = CsKind::Indexed {@@ -876,7 +910,7 @@ mod tests {             hival: 1,         };         assert_eq!(cs_kind_image_ncomp(&cs), 1, "one index per image sample");-        assert_eq!(cs_kind_ncomp(&cs), 3, "shading.rs still sees the base arity");+        assert_eq!(cs_kind_ncomp(&cs), 3, "the palette decode still needs the base arity");     }      // A named ICCBased colorspace stored as an INDIRECT array in the resource id@@ -1029,6 +1063,110 @@ mod tests {         assert_eq!(palette, vec![0x00, 0x00, 0xFF], "palette must be decoded");     } +    // §8.6.6.5 defers to §8.6.6.4 for the tint transform, which "shall produce one+    // value for each component of the alternate space". The Separation arm has checked+    // that since a previous round; the DeviceN arm did not, so a broken transform fed+    // `eval_cs_to_rgb` a short tuple. Over an RGB/CMYK alternate that returns None,+    // which every caller reads as "leave the current colour alone" — the fill silently+    // keeps whatever colour was set before, which is not a colour anyone chose.+    #[test]+    fn devicen_with_a_short_tint_output_falls_back_instead_of_vanishing() {+        let doc = Document::with_version("1.7");+        let cs = CsKind::DeviceN {+            names: vec![b"A".to_vec(), b"B".to_vec()],+            // DeviceCMYK needs 4 components; this Type 2 yields only 1.+            alt: Box::new(CsKind::DeviceCMYK),+            tint_fn: Some(PdfFunction::Exponential {+                domain: [0.0, 1.0],+                range: Vec::new(),+                c0: vec![0.0],+                c1: vec![1.0],+                n: 1.0,+            }),+        };+        let res = HashMap::new();+        let full = eval_cs_to_rgb(&doc, &cs, &[1.0, 1.0], &res)+            .expect("a broken tint transform must still yield a colour");+        assert_eq!(full & 0xFF, 0, "full ink darkens");+        let none = eval_cs_to_rgb(&doc, &cs, &[0.0, 0.0], &res).expect("resolves");+        assert_eq!(none & 0xFF, 255, "no ink leaves the page white");++        // A well-formed transform is untouched: 2 inks -> DeviceGray, t -> 1-t.+        let ok = CsKind::DeviceN {+            names: vec![b"A".to_vec(), b"B".to_vec()],+            alt: Box::new(CsKind::DeviceGray),+            tint_fn: Some(PdfFunction::Exponential {+                domain: [0.0, 1.0],+                range: Vec::new(),+                c0: vec![1.0],+                c1: vec![0.0],+                n: 1.0,+            }),+        };+        assert_eq!(eval_cs_to_rgb(&doc, &ok, &[0.0, 0.0], &res).unwrap() & 0xFF, 255);+        assert_eq!(eval_cs_to_rgb(&doc, &ok, &[1.0, 1.0], &res).unwrap() & 0xFF, 0);+    }++    // §8.6.5.4 Table 66: /Range bounds a* and b*, and a value outside it "shall be+    // adjusted to the nearest valid value". The image path arrives in range via+    // /Decode, but `sc`/`scn` operands and a tint transform with no /Range of its own+    // do not — and an unbounded a*/b* drives fx/fz far outside the cube-root branch,+    // producing a saturated primary instead of the nearest in-gamut colour.+    #[test]+    fn lab_clamps_a_and_b_to_the_spaces_range() {+        let doc = Document::with_version("1.7");+        let cs = CsKind::Lab {+            white: [0.9505, 1.0, 1.0890],+            range: [[-20.0, 20.0], [-20.0, 20.0]],+        };+        let res = HashMap::new();+        let at_edge = eval_cs_to_rgb(&doc, &cs, &[50.0, 20.0, 0.0], &res).unwrap();+        let beyond = eval_cs_to_rgb(&doc, &cs, &[50.0, 90.0, 0.0], &res).unwrap();+        assert_eq!(at_edge, beyond, "a* past /Range clamps to the edge of /Range");+        let below = eval_cs_to_rgb(&doc, &cs, &[50.0, -90.0, 0.0], &res).unwrap();+        assert_eq!(+            below,+            eval_cs_to_rgb(&doc, &cs, &[50.0, -20.0, 0.0], &res).unwrap()+        );+        // The clamp is not a blanket flattening: inside /Range the colour still varies.+        let inside = eval_cs_to_rgb(&doc, &cs, &[50.0, 0.0, 0.0], &res).unwrap();+        assert_ne!(inside, at_edge, "in-range a* is untouched");+        // And the DEFAULT range (-100..100) leaves ordinary Lab values alone.+        let wide = CsKind::Lab {+            white: [0.9505, 1.0, 1.0890],+            range: [[-100.0, 100.0], [-100.0, 100.0]],+        };+        assert_ne!(+            eval_cs_to_rgb(&doc, &wide, &[50.0, 60.0, 0.0], &res).unwrap(),+            eval_cs_to_rgb(&doc, &wide, &[50.0, 20.0, 0.0], &res).unwrap()+        );+    }++    // `parse_cs_array_at`'s MAX_CS_DEPTH comment describes the exact cycle+    // `[/Indexed 5 0 R 255 <..>]`-stored-as-object-5 creates. `colorspace_info` is a+    // second, parallel walk of the same object graph and did NOT have the guard, so the+    // same file that was safe through one entry point overflowed the stack through the+    // other. A stack overflow is not catchable, so the process dies.+    #[test]+    fn colorspace_info_survives_a_self_referential_indexed_base() {+        let mut doc = Document::with_version("1.7");+        let id = doc.new_object_id();+        doc.set_object(+            id,+            Object::Array(vec![+                Object::Name(b"Indexed".to_vec()),+                Object::Reference(id),+                Object::Integer(255),+                Object::String(vec![0, 0, 0], lopdf::StringFormat::Literal),+            ]),+        );+        let (n, indexed) = colorspace_info(&doc, Some(&Object::Reference(id)));+        assert_eq!(n, 1, "an Indexed image sample is still one index");+        assert!(indexed.is_some());+        // And the other entry point stays consistent.+        assert!(parse_cs_kind(&doc, Some(&Object::Reference(id)), &HashMap::new()).is_some());+    }+     // A malformed Cal*/Lab entry must mean exactly what an ABSENT one means — the spec     // default — not propagate into the conversion. A real like 1e40 overflows the f32     // `Object::Real` holds, and an infinite /WhitePoint reaches `adapt_to_d65` where
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 69a106ea13..b2fc3330bf 100644--- a/pdf/src/main/rust/src/decrypt.rs+++ b/pdf/src/main/rust/src/decrypt.rs@@ -9,6 +9,13 @@ type CryptFnFactory = Box<dyn Fn(ObjectId) -> CryptFn>; /// the empty password does not satisfy. Returns: 0 no, 1 needs password, 2 /// unsupported encryption (e.g. AES). pub(crate) fn pdf_password_state(bytes: &[u8]) -> i32 {+    // The same size guard `open_document_pw` applies, for the same bytes: this probe+    // runs FIRST in the UI flow, so without it a 1 GB file is fully parsed here and+    // only then refused at open. Reporting "no password needed" matches what open+    // will do with it.+    if bytes.len() > crate::registry::MAX_PDF_BYTES {+        return 0;+    }     // Must match open_document_pw's loader: using the strict Document::load_mem here made a     // damaged encrypted file report "no password needed" and then fail to open with no prompt.     let mut doc = match crate::registry::load_document_lenient(bytes) {
pdf/src/main/rust/src/docedit.rs
diff --git a/pdf/src/main/rust/src/docedit.rs b/pdf/src/main/rust/src/docedit.rsindex 00476caeea..b978de8b67 100644--- a/pdf/src/main/rust/src/docedit.rs+++ b/pdf/src/main/rust/src/docedit.rs@@ -84,9 +84,16 @@ pub(crate) fn remap_object(obj: &Object, map: &HashMap<ObjectId, ObjectId>) -> O /// Append every page of the PDF in `bytes` to the document behind `handle`. /// Returns the number of pages added (0 on failure/encrypted source). pub(crate) fn append_pdf(handle: i64, bytes: &[u8]) -> i32 {-    let src = match Document::load_mem(bytes) {-        Ok(d) => d,-        Err(_) => return 0,+    // The same untrusted, user-picked bytes that `open_document_pw` takes, so the same+    // door: raw `Document::load_mem` skips the §7.5.1 pre-scan that `load_document_lenient`+    // performs, and both hazards it exists for are unrecoverable once lopdf is entered —+    // unbounded recursion in the object parser is a guard-page fault, not an unwind, so+    // the JNI `catch_unwind` cannot see it, and a degenerate `/W [0 0 0]` cross-reference+    // stream is a multi-billion-iteration loop rather than an error. It also means a+    // damaged file the viewer can open can now be appended too.+    let src = match load_document_lenient(bytes) {+        Some(d) => d,+        None => return 0,     };     if src.trailer.get(b"Encrypt").is_ok() {         return 0;@@ -250,7 +257,11 @@ pub(crate) fn rotate_page(handle: i64, index: i32, delta: i32) -> bool {         None => return false,     };     let cur = page_rotation(doc, page_id) as i32;-    let new = (((cur + delta) % 360) + 360) % 360;+    // `delta` arrives raw from the JNI boundary, so `cur + delta` can overflow i32:+    // a debug panic WHILE HOLDING the registry mutex (poisoning it for every other+    // caller), and a silent wrap in release, where overflow checks are off. Reducing+    // both terms first keeps the sum below 720.+    let new = (cur.rem_euclid(360) + delta.rem_euclid(360)).rem_euclid(360);     if let Ok(pd) = doc.get_dictionary_mut(page_id) {         pd.set("Rotate", Object::Integer(new as i64));         true@@ -401,18 +412,27 @@ pub(crate) fn save_compressed(handle: i64) -> Option<Vec<u8>> {     Some(out) } -/// Ensure page `page_id` has an inline `/Resources /XObject` mapping `name` -> `xid`.-pub(crate) fn add_page_xobject(doc: &mut Document, page_id: ObjectId, name: &str, xid: ObjectId) {+/// Ensure page `page_id` has an inline `/Resources` sub-dictionary `category`+/// mapping `name` -> `id`.+fn add_page_resource(+    doc: &mut Document,+    page_id: ObjectId,+    category: &str,+    name: &str,+    id: ObjectId,+) {     // Resolve to an inline Resources dict on the page (copying a referenced one).     let res_inline = matches!(         doc.get_dictionary(page_id).ok().and_then(|d| d.get(b"Resources").ok()),         Some(Object::Dictionary(_))     );     if !res_inline {-        let copied = doc-            .get_dictionary(page_id)-            .ok()-            .and_then(|d| d.get(b"Resources").ok())+        // §7.7.3.4: /Resources is INHERITABLE, so a page that carries none is not a+        // page without resources — `resources_dict`, the renderer's read path, walks+        // /Parent for it. Seeding the inline copy from the page's OWN entry produced+        // an empty dictionary that then SHADOWS the inherited one, so flattening a+        // single annotation blanked every font and image on such a page.+        let copied = inherited(doc, page_id, b"Resources")             .and_then(|o| deref(doc, o))             .and_then(|o| o.as_dict().ok())             .cloned()@@ -423,17 +443,22 @@ pub(crate) fn add_page_xobject(doc: &mut Document, page_id: ObjectId, name: &str     }     if let Ok(p) = doc.get_dictionary_mut(page_id) {         if let Ok(Object::Dictionary(res)) = p.get_mut(b"Resources") {-            let has_xo = matches!(res.get(b"XObject"), Ok(Object::Dictionary(_)));-            if !has_xo {-                res.set("XObject", Object::Dictionary(Dictionary::new()));+            let has = matches!(res.get(category.as_bytes()), Ok(Object::Dictionary(_)));+            if !has {+                res.set(category, Object::Dictionary(Dictionary::new()));             }-            if let Ok(Object::Dictionary(xo)) = res.get_mut(b"XObject") {-                xo.set(name, Object::Reference(xid));+            if let Ok(Object::Dictionary(sub)) = res.get_mut(category.as_bytes()) {+                sub.set(name, Object::Reference(id));             }         }     } } +/// Ensure page `page_id` has an inline `/Resources /XObject` mapping `name` -> `xid`.+pub(crate) fn add_page_xobject(doc: &mut Document, page_id: ObjectId, name: &str, xid: ObjectId) {+    add_page_resource(doc, page_id, "XObject", name, xid);+}+ /// Prepend `content_id` (a content stream) before page `page_id`'s `/Contents`. pub(crate) fn prepend_content(doc: &mut Document, page_id: ObjectId, content_id: ObjectId) {     let current = doc.get_dictionary(page_id).ok().and_then(|d| d.get(b"Contents").ok()).cloned();@@ -496,7 +521,7 @@ pub(crate) fn flatten_document(handle: i64) -> bool {         if annot_ids.is_empty() {             continue;         }-        let mut placements: Vec<(String, ObjectId, Mat)> = Vec::new();+        let mut placements: Vec<(String, ObjectId, Mat, f64)> = Vec::new();         for (i, aid) in annot_ids.iter().enumerate() {             let dict = match doc.get_dictionary(*aid) {                 Ok(d) => d,@@ -562,16 +587,42 @@ pub(crate) fn flatten_document(handle: i64) -> bool {             // `display_orientation`), so flattening one used to rotate it a             // second time and translate it clean off its /Rect.             let m = appearance_fit_matrix(rect, bbox, matrix);-            placements.push((format!("Fl{}_{}", page_id.0, i), ap_id, m));+            // §12.5.2 Table 164: /CA is the annotation's constant opacity, and the+            // renderer honours it (`render_annotation`). A bare `cm ... Do` carries no+            // alpha, so flattening turned a half-transparent highlight or stamp fully+            // opaque — and /Annots is dropped below, so it cannot be undone. §12.5.2+            // makes /CA govern stroking and non-stroking alike, so it is emitted as an+            // /ExtGState setting BOTH /ca and /CA (§11.6.4.4).+            let ca = dict+                .get(b"CA")+                .ok()+                .and_then(|o| deref(doc, o).or(Some(o)))+                .and_then(num)+                .unwrap_or(1.0)+                .clamp(0.0, 1.0);+            placements.push((format!("Fl{}_{}", page_id.0, i), ap_id, m, ca));         }         if placements.is_empty() {             continue;         }         let mut content = String::new();-        for (name, _, m) in &placements {+        let mut gstates: Vec<(String, ObjectId)> = Vec::new();+        for (i, (name, _, m, ca)) in placements.iter().enumerate() {+            let gs = if *ca < 1.0 {+                let gid = doc.add_object(dictionary! {+                    "Type" => name_obj("ExtGState"),+                    "ca" => Object::Real(*ca as f32),+                    "CA" => Object::Real(*ca as f32),+                });+                let gname = format!("FlG{}_{}", page_id.0, i);+                gstates.push((gname.clone(), gid));+                format!("/{gname} gs ")+            } else {+                String::new()+            };             content.push_str(&format!(-                "q {:.4} {:.4} {:.4} {:.4} {:.4} {:.4} cm /{} Do Q ",-                m[0], m[1], m[2], m[3], m[4], m[5], name+                "q {:.4} {:.4} {:.4} {:.4} {:.4} {:.4} cm {}/{} Do Q ",+                m[0], m[1], m[2], m[3], m[4], m[5], gs, name             ));         }         let cid = doc.add_object(Stream::new(dictionary! {}, content.into_bytes()));@@ -584,9 +635,12 @@ pub(crate) fn flatten_document(handle: i64) -> bool {         prepend_content(doc, page_id, qid);         append_content(doc, page_id, unqid);         append_content(doc, page_id, cid);-        for (name, ap_id, _) in &placements {+        for (name, ap_id, _, _) in &placements {             add_page_xobject(doc, page_id, name, *ap_id);         }+        for (name, gid) in &gstates {+            add_page_resource(doc, page_id, "ExtGState", name, *gid);+        }         if let Ok(p) = doc.get_dictionary_mut(page_id) {             p.remove(b"Annots");         }@@ -698,6 +752,95 @@ pub(crate) fn redact_operations(     out } +/// Encode an operator list back into content-stream bytes.+///+/// Not `Content::encode` on its own: §8.9.7 inline images come out of lopdf's parser+/// as a single `BI` operation whose one operand is an `Object::Stream`, and the writer+/// serializes a stream in INDIRECT-object syntax — `<< ... >> stream <data> endstream`,+/// with no `ID` and the `BI` keyword landing AFTER the data. That is not a content+/// stream: the image is destroyed and every operator after it desynchronizes. So `BI`+/// is re-emitted in inline syntax here and the rest is handed to `Content::encode`.+fn encode_operations(ops: Vec<lopdf::content::Operation>) -> Option<Vec<u8>> {+    fn flush(run: &mut Vec<lopdf::content::Operation>, out: &mut Vec<u8>) -> Option<()> {+        if run.is_empty() {+            return Some(());+        }+        let encoded = Content { operations: std::mem::take(run) }.encode().ok()?;+        out.extend_from_slice(&encoded);+        out.push(b'\n');+        Some(())+    }+    let mut out = Vec::new();+    let mut run: Vec<lopdf::content::Operation> = Vec::new();+    for op in ops {+        let inline = match (op.operator.as_str(), op.operands.first()) {+            ("BI", Some(Object::Stream(s))) => Some(s.clone()),+            _ => None,+        };+        match inline {+            Some(s) => {+                flush(&mut run, &mut out)?;+                out.extend_from_slice(&encode_inline_image(&s)?);+                out.push(b'\n');+            }+            None => run.push(op),+        }+    }+    flush(&mut run, &mut out)?;+    Some(out)+}++/// §8.9.7 `BI <key value>… ID <data> EI`.+///+/// The key/value pairs are emitted through `Content::encode` with `ID` as the operator,+/// which is exactly the `/Key value … ID` text the inline-image syntax calls for, and+/// keeps the operand writer (name escaping, number formatting) in one place.+fn encode_inline_image(s: &Stream) -> Option<Vec<u8>> {+    let mut operands = Vec::new();+    for (k, v) in s.dict.iter() {+        operands.push(Object::Name(k.clone()));+        operands.push(v.clone());+    }+    let head = Content {+        operations: vec![lopdf::content::Operation { operator: "ID".to_string(), operands }],+    }+    .encode()+    .ok()?;+    let mut out = b"BI ".to_vec();+    out.extend_from_slice(&head);+    // §8.9.7: exactly one white-space byte separates `ID` from the data.+    out.push(b'\n');+    out.extend_from_slice(&s.content);+    out.extend_from_slice(b"\nEI");+    Some(out)+}++/// Every object id referenced from the trailer or from any object in `doc`.+///+/// References are collected, not followed, so this cannot loop on a cyclic graph.+/// Used to decide whether an object that has just been detached is now unreachable.+fn referenced_object_ids(doc: &Document) -> std::collections::HashSet<ObjectId> {+    fn walk(obj: &Object, out: &mut std::collections::HashSet<ObjectId>) {+        match obj {+            Object::Reference(id) => {+                out.insert(*id);+            }+            Object::Array(a) => a.iter().for_each(|o| walk(o, out)),+            Object::Dictionary(d) => d.iter().for_each(|(_, v)| walk(v, out)),+            Object::Stream(s) => s.dict.iter().for_each(|(_, v)| walk(v, out)),+            _ => {}+        }+    }+    let mut out = std::collections::HashSet::new();+    for (_, v) in doc.trailer.iter() {+        walk(v, &mut out);+    }+    for obj in doc.objects.values() {+        walk(obj, &mut out);+    }+    out+}+ /// Whether the document has any redaction annotations pending. pub(crate) fn has_redactions(handle: i64) -> bool {     let reg = registry().lock().unwrap_or_else(|e| e.into_inner());@@ -731,11 +874,13 @@ pub(crate) fn has_redactions(handle: i64) -> bool { /// removes only text-showing operators whose ORIGIN falls inside a rect, using an /// approximate advance, so it does not remove images, inline images, form /// XObjects, shadings or vector artwork; nor text that starts outside the rect-/// and runs into it; nor the pre-redaction content stream object, which-/// `save_document` leaves in the file (only the separate `save_compressed` path-/// prunes it). For all of those the black rectangle only COVERS the content,-/// which remains extractable from the saved file. Anything relying on this for-/// confidentiality needs content-level removal per §12.5.6.24 first.+/// and runs into it. For all of those the black rectangle only COVERS the+/// content, which remains extractable from the saved file. Anything relying on+/// this for confidentiality needs content-level removal per §12.5.6.24 first.+///+/// What IS guaranteed: the operators this does drop are gone from the file, not+/// merely hidden — the pre-redaction content stream is detached and, when nothing+/// else references it, deleted, so `save_document` cannot ship it. /// /// Refuses the WHOLE operation, without touching the document, if any page's content /// stream can only be recovered by the lenient tokenizer — see the comment at the@@ -801,9 +946,13 @@ pub(crate) fn apply_redactions(handle: i64) -> bool {     }      let mut applied = false;+    // The pre-redaction content streams, detached below. §12.5.6.24 wants the content+    // GONE, and `save_document` writes every object in the document — leaving them+    // behind ships the redacted text inside the file for any object dumper to read.+    let mut stale: Vec<ObjectId> = Vec::new();     for (page_id, rects, redact_ids, ops) in work {         let new_ops = redact_operations(ops, &rects);-        let encoded = lopdf::content::Content { operations: new_ops }.encode().unwrap_or_default();+        let encoded = encode_operations(new_ops).unwrap_or_default();         // §7.8.2: the page content is one concatenated stream, and the redacted         // operator list can end with an unbalanced `q ... cm` or an active clip.         // Bracketing it in q/Q means the cover rectangles below are painted from@@ -821,6 +970,7 @@ pub(crate) fn apply_redactions(handle: i64) -> bool {             ));         }         bytes.extend_from_slice(cover.as_bytes());+        stale.extend(doc.get_page_contents(page_id));         let cid = doc.add_object(Stream::new(dictionary! {}, bytes));         if let Ok(p) = doc.get_dictionary_mut(page_id) {             p.set("Contents", Object::Reference(cid));@@ -831,6 +981,17 @@ pub(crate) fn apply_redactions(handle: i64) -> bool {         }         applied = true;     }+    if applied {+        // Only drop a detached stream nothing else still points at: a /Contents stream+        // may legitimately be shared between pages (page imports duplicate the object+        // graph, not the objects), and removing one of those would blank the other page.+        let live = referenced_object_ids(doc);+        for id in stale {+            if !live.contains(&id) {+                doc.objects.remove(&id);+            }+        }+    }     applied } @@ -937,6 +1098,77 @@ mod redaction_tests {         }     } +    /// §12.5.2 Table 164: `/CA` is the annotation's constant opacity, and the+    /// renderer honours it (`render_annotation` wraps the appearance in a group+    /// with that alpha). A bare `cm … Do` carries no alpha, so flattening turned+    /// a half-transparent highlight fully opaque — and `/Annots` is dropped, so+    /// the original opacity is unrecoverable.+    #[test]+    fn flatten_carries_the_annotation_constant_opacity() {+        let (dw, dh) = (40.0_f64, 20.0_f64);+        let rect = [10.0, 20.0, 10.0 + dw, 20.0 + dh];+        let (handle, page_id) = flattenable_doc(rect, [0.0, 0.0, dw, dh], IDENTITY);+        {+            let mut reg = registry().lock().unwrap_or_else(|e| e.into_inner());+            let doc = reg.get_mut(&handle).expect("handle is registered");+            let aid = doc+                .get_dictionary(page_id)+                .ok()+                .and_then(|d| d.get(b"Annots").ok())+                .and_then(|o| o.as_array().ok())+                .and_then(|a| a.first().and_then(|o| o.as_reference().ok()))+                .expect("the fixture has one annotation");+            doc.get_dictionary_mut(aid)+                .expect("annot")+                .set("CA", Object::Real(0.5));+        }+        assert!(flatten_document(handle), "flatten failed");++        let text = String::from_utf8_lossy(&page_bytes(handle, page_id)).into_owned();+        let gs = text+            .split_whitespace()+            .collect::<Vec<_>>()+            .windows(2)+            .find(|w| w[1] == "gs")+            .map(|w| w[0].trim_start_matches('/').to_string())+            .unwrap_or_else(|| panic!("no `gs` in the flattened content: {text}"));++        let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+        let doc = reg.get(&handle).expect("handle is registered");+        let res = resources_dict(doc, page_id).expect("resources");+        let egs = res+            .get(b"ExtGState")+            .ok()+            .and_then(|o| deref(doc, o))+            .and_then(|o| o.as_dict().ok())+            .and_then(|d| d.get(gs.as_bytes()).ok())+            .and_then(|o| deref(doc, o))+            .and_then(|o| o.as_dict().ok())+            .unwrap_or_else(|| panic!("/{gs} is not in /Resources /ExtGState: {res:?}"));+        // §12.5.2 makes /CA govern stroking and non-stroking alike, so both must be set.+        for key in [&b"ca"[..], &b"CA"[..]] {+            let v = egs.get(key).ok().and_then(num).unwrap_or_else(|| {+                panic!("/{} missing from the flatten ExtGState: {egs:?}", String::from_utf8_lossy(key))+            });+            assert!((v - 0.5).abs() < 1e-6, "expected 0.5, got {v}");+        }+        drop(reg);+        close_document(handle);+    }++    /// A fully opaque annotation (the common case, and `/CA` absent) must not gain+    /// an /ExtGState it does not need.+    #[test]+    fn flatten_emits_no_extgstate_for_an_opaque_annotation() {+        let (dw, dh) = (40.0_f64, 20.0_f64);+        let (handle, page_id) =+            flattenable_doc([10.0, 20.0, 10.0 + dw, 20.0 + dh], [0.0, 0.0, dw, dh], IDENTITY);+        assert!(flatten_document(handle));+        let text = String::from_utf8_lossy(&page_bytes(handle, page_id)).into_owned();+        assert!(!text.contains(" gs"), "unexpected /ExtGState: {text}");+        close_document(handle);+    }+     /// One-page document carrying a single annotation whose `/AP /N` has the     /// given `/BBox` and `/Matrix`.     fn flattenable_doc(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> (i64, ObjectId) {@@ -1024,6 +1256,140 @@ mod redaction_tests {         close_document(handle);     } +    /// §12.5.6.24: redaction means the content is REMOVED, not covered. The+    /// pre-redaction content stream still holds the text verbatim and+    /// `save_document` writes every object in the document, so leaving it behind+    /// ships a file the user believes is redacted with the text still in it —+    /// recoverable with any object dumper.+    #[test]+    fn the_pre_redaction_content_stream_is_not_left_in_the_saved_file() {+        let content = b"BT /F1 12 Tf 100 700 Td (secret) Tj ET\n";+        let (handle, _page_id, _annot_id) = redactable_doc(content, [90, 690, 200, 720]);+        assert!(apply_redactions(handle));+        let saved = save_document(handle).expect("save");+        assert!(+            !saved.windows(6).any(|w| w == b"secret"),+            "the redacted text is still in the saved file"+        );+        close_document(handle);+    }++    /// §8.9.7: lopdf represents `BI` as a single operation whose operand is an+    /// `Object::Stream`, and `Content::encode` writes an `Object::Stream` in+    /// INDIRECT-object syntax (`<<...>> stream ... endstream`) — there is no `ID`+    /// and the `BI` lands after the data. Re-encoding such a page destroys the+    /// image and desynchronises everything after it. The refusal at the+    /// `page_operations` call only covers streams lopdf CANNOT parse, so a+    /// perfectly good inline image took this path.+    #[test]+    fn redacting_a_page_with_an_inline_image_keeps_the_image_intact() {+        let px: Vec<u8> = (1u8..=12).collect(); // 2x2, 3 components, 8 bpc+        let mut content = b"BT /F1 12 Tf 100 700 Td (secret) Tj ET\n".to_vec();+        content.extend_from_slice(b"q 10 0 0 10 300 300 cm BI /W 2 /H 2 /CS /RGB /BPC 8 ID ");+        content.extend_from_slice(&px);+        content.extend_from_slice(b" EI Q\n");+        let (handle, page_id, _annot_id) = redactable_doc(&content, [90, 690, 200, 720]);+        {+            let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+            let doc = reg.get(&handle).expect("handle is registered");+            assert!(+                doc.get_and_decode_page_content(page_id).is_ok(),+                "precondition: lopdf parses this inline image, so redaction proceeds"+            );+        }+        assert!(apply_redactions(handle), "a healthy page must redact");++        let after = page_bytes(handle, page_id);+        assert!(+            !after.windows(6).any(|w| w == b"secret"),+            "the text under the rect must be gone: {}",+            String::from_utf8_lossy(&after)+        );+        assert!(+            !after.windows(9).any(|w| w == b"endstream"),+            "an inline image must not be written back as an indirect stream: {}",+            String::from_utf8_lossy(&after)+        );+        let ops = crate::content::parse_operations_lenient(&after);+        let images: Vec<Vec<u8>> = ops+            .iter()+            .filter(|o| o.operator == "BI")+            .filter_map(|o| match o.operands.first() {+                Some(Object::Stream(s)) => Some(s.content.clone()),+                _ => None,+            })+            .collect();+        assert_eq!(images, vec![px], "the inline image data must survive verbatim");+        // And the operators after the image must still be there.+        let names: Vec<&str> = ops.iter().map(|o| o.operator.as_str()).collect();+        assert!(names.contains(&"Q"), "content after the image was lost: {names:?}");+        close_document(handle);+    }++    /// §7.7.3.4: `/Resources` is INHERITABLE. `resources_dict` (the renderer's+    /// read path) walks `/Parent` for it, so a page that carries none is not a+    /// page without resources. `add_page_xobject` wrote an inline `/Resources`+    /// built only from the page's OWN entry, which on such a page is an empty+    /// dictionary that then SHADOWS the inherited one — flattening a single+    /// annotation blanked every font and image on the page.+    #[test]+    fn flatten_does_not_shadow_an_inherited_resources_dictionary() {+        let mut doc = Document::with_version("1.7");+        let ap_id = doc.add_object(Stream::new(+            dictionary! {+                "Type" => name_obj("XObject"),+                "Subtype" => name_obj("Form"),+                "BBox" => rect_obj([0.0, 0.0, 10.0, 10.0]),+            },+            b"0 0 1 rg 0 0 10 10 re f".to_vec(),+        ));+        let annot_id = doc.add_object(dictionary! {+            "Type" => name_obj("Annot"),+            "Subtype" => name_obj("Square"),+            "Rect" => rect_obj([10.0, 10.0, 20.0, 20.0]),+            "AP" => dictionary! { "N" => ap_id },+        });+        let pages_id = doc.new_object_id();+        // No /Resources on the page: it inherits the /Pages node's.+        let page_id = doc.add_object(dictionary! {+            "Type" => name_obj("Page"),+            "Parent" => Object::Reference(pages_id),+            "MediaBox" => rect_obj([0.0, 0.0, 612.0, 792.0]),+            "Annots" => Object::Array(vec![Object::Reference(annot_id)]),+        });+        doc.objects.insert(+            pages_id,+            Object::Dictionary(dictionary! {+                "Type" => name_obj("Pages"),+                "Kids" => Object::Array(vec![Object::Reference(page_id)]),+                "Count" => 1,+                "Resources" => Object::Dictionary(helvetica_resources()),+            }),+        );+        let cat = doc.add_object(dictionary! {+            "Type" => name_obj("Catalog"),+            "Pages" => Object::Reference(pages_id),+        });+        doc.trailer.set("Root", cat);+        let handle = next_handle();+        registry().lock().unwrap_or_else(|e| e.into_inner()).insert(handle, doc);++        assert!(flatten_document(handle));+        let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+        let doc = reg.get(&handle).expect("handle is registered");+        let res = resources_dict(doc, page_id).expect("the page must still resolve resources");+        assert!(+            res.get(b"Font").is_ok(),+            "the inherited /Font was shadowed by the flatten overlay: {res:?}"+        );+        assert!(+            res.get(b"XObject").is_ok(),+            "the flattened appearance must still be reachable: {res:?}"+        );+        drop(reg);+        close_document(handle);+    }+     /// The refusal above must not cost the normal path: a stream lopdf parses is still     /// redacted, so the fix cannot regress any document that redacts today.     #[test]
pdf/src/main/rust/src/draw.rs
diff --git a/pdf/src/main/rust/src/draw.rs b/pdf/src/main/rust/src/draw.rsindex d04093580b..efaec767df 100644--- a/pdf/src/main/rust/src/draw.rs+++ b/pdf/src/main/rust/src/draw.rs@@ -1,5 +1,19 @@ use crate::*; +/// Everything on `Prim::Text` is derived from unvalidated file input (`Tf`, `Tz`,+/// `/Widths`, the CTM), and a non-finite value can survive even validated operands:+/// `f64 as f32` saturates to infinity above ~3.4e38. It cannot be left to the+/// consumer, because Kotlin's `coerceIn`/`coerceAtLeast` are comparisons and every+/// comparison against NaN is false — it passes straight through the clamp into+/// `Paint`, and the glyph silently disappears rather than being visibly wrong.+fn finite_or_zero(v: f32) -> f32 {+    if v.is_finite() {+        v+    } else {+        0.0+    }+}+ pub(crate) fn cubic_bezier(     p0: (f64, f64),     p1: (f64, f64),@@ -56,6 +70,14 @@ pub(crate) fn emit_stroke(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], g     // stroker, because what the spec asks for here is a fill, not a stroke.     let dot_radius = (width as f64 / 2.0).max(0.05);     for sp in subpaths {+        // One primitive PER SUBPATH, so the caller's single pre-call cap check+        // cannot bound this loop: a path carrying MAX_SUBPATHS subpaths overshot+        // MAX_PRIMITIVES by up to that many. `emit_fill` has no equivalent problem+        // because it emits one Fill holding every contour. Reported by `r5-state`,+        // whose doc on the constant states it is enforced at every emitting push.+        if prims.len() >= MAX_PRIMITIVES {+            break;+        }         if sp.is_empty() { continue; }         let (fx, fy) = sp[0];         if sp.iter().all(|&(x, y)| (x - fx).abs() < 1e-9 && (y - fy).abs() < 1e-9) {@@ -150,7 +172,37 @@ pub(crate) fn show_string_in(     // Device-space horizontal scale, used to convert glyph advances (user space)     // into the device advance carried on the wire for text selection/search.     let x_scale = (trm[0] * trm[0] + trm[1] * trm[1]).sqrt();+    // Horizontal scale to put on the wire for the SUBSTITUTE face. Kotlin derives+    // the glyph's em from `size` (= Tfs·y_scale) and multiplies its width by+    // `h_scale`, so Th alone under-describes an anisotropic matrix: with+    // x_scale != y_scale the outline path draws the glyph x_scale/y_scale wider+    // than the substitute path does, and the two disagree about the SIZE of the+    // same glyph. Folding the ratio in is exactly 1.0 for every isotropic matrix+    // — including every pure rotation — so it changes nothing on ordinary pages.+    // This is the only part of the mismatch expressible in the v8 wire; the glyph+    // being axis-aligned under a rotated matrix needs a field that does not exist.+    //+    // Bounded here rather than at the consumer. A near-degenerate matrix makes the+    // ratio enormous, and `th` is `Tz/100` whose product can overflow; the check is+    // on the f32 that is actually serialized, because `f64 as f32` saturates to inf+    // above ~3.4e38 and a finite f64 would otherwise sail through.+    let aniso = if y_scale > 1e-9 { x_scale / y_scale } else { 1.0 };+    let wire_h_scale = th * if aniso.is_finite() { aniso.clamp(0.01, 100.0) } else { 1.0 };+    let wire_h_scale = {+        let v = wire_h_scale as f32;+        if v.is_finite() {+            v+        } else {+            1.0+        }+    };     let size = (tfs * y_scale) as f32;+    // `Tf`'s operand and the CTM are file input, and `size` is their product, so a+    // non-finite value is reachable even with both validated — an f64 above the f32+    // range saturates to inf on the cast. NaN then survives Kotlin's+    // `coerceAtLeast` (a comparison) into `Paint.textSize` and the glyph vanishes.+    // Zero is the honest substitute: the consumer floors it to one pixel.+    let size = finite_or_zero(size);     // Modes 3 (invisible) and 7 (clip only) advance the pen but paint nothing.     let drawable = gs.render_mode != 3 && gs.render_mode != 7;     // Mode 3 is how a scan carries its OCR layer: nothing is painted, but the run@@ -162,6 +214,7 @@ pub(crate) fn show_string_in(         Some(fi) => fi,         None => {             // No font metrics: emit the run at the origin and estimate advance.+            let run_advance = bytes.len() as f64 * 0.5 * tfs * th;             if (drawable || invisible) && !bytes.is_empty() {                 let (x, y) = transform(&trm, 0.0, gs.rise);                 let text: String =@@ -175,18 +228,24 @@ pub(crate) fn show_string_in(                         text,                         stroke_argb: None,                         stroke_width: None,-                        advance: size,+                        // The DEVICE advance of the whole run, which is what the+                        // wire contract says this field is and what the selection+                        // layer rescales a non-painted run to. `size` was one+                        // glyph's worth for a run of any length, so a mode-3 OCR+                        // run with no font resource had every selection rectangle+                        // piled onto its first character.+                        advance: finite_or_zero((run_advance * x_scale) as f32).max(size * 0.1),                         render_mode: gs.render_mode as u8,                         blend: gs.blend_mode,                         is_bold: false,                         is_italic: false,                         font_family: 0,                         outline: false,-                        h_scale: th as f32,+                        h_scale: wire_h_scale,                     });                 }             }-            return bytes.len() as f64 * 0.5 * tfs * th;+            return run_advance;         }     }; @@ -231,7 +290,11 @@ pub(crate) fn show_string_in(                 .unwrap_or((fi.default_vertical.1, 0.5 * w0));             let vy = fi.default_vertical.0;             let extra = gs.char_spacing + if is_space { gs.word_spacing } else { 0.0 };-            (-vx * tfs * th, pen - vy * tfs, w1y * tfs - extra)+            // Trise is part of §9.4.4's text-space parameter matrix, which does not+            // depend on the writing mode: it displaces the glyph in text-space y in+            // vertical writing exactly as it does in horizontal. Dropping it here put+            // super/subscripts in vertical CJK back on the baseline.+            (-vx * tfs * th, pen - vy * tfs + gs.rise, w1y * tfs - extra)         } else {             (pen, gs.rise, glyph_advance_user)         };@@ -260,6 +323,11 @@ pub(crate) fn show_string_in(                 } else {                     (glyph_advance_user * x_scale) as f32                 };+                // Same reasoning as `size`. The selection layer rescales a+                // non-painted run by `advance * scale / measured`, and its+                // `advance > 0f` guard PASSES infinity, so one overflowed glyph+                // would stretch every remaining glyph's rectangle in the run.+                let glyph_device_adv = finite_or_zero(glyph_device_adv);                 // Real embedded outline for pure paint modes (0/1/2). Clip modes                 // (4-7) keep the substitute-glyph path so Kotlin can build the clip.                 let outline = if has_program && matches!(gs.render_mode, 0..=2) {@@ -332,7 +400,7 @@ pub(crate) fn show_string_in(                                 is_italic: italic,                                 font_family: family,                                 outline: true,-                                h_scale: th as f32,+                                h_scale: wire_h_scale,                             });                         }                     }@@ -356,7 +424,7 @@ pub(crate) fn show_string_in(                             is_italic: italic,                             font_family: family,                             outline: false,-                            h_scale: th as f32,+                            h_scale: wire_h_scale,                         });                     } else if has_stroke {                         prims.push(Prim::Text {@@ -374,7 +442,7 @@ pub(crate) fn show_string_in(                             is_italic: italic,                             font_family: family,                             outline: false,-                            h_scale: th as f32,+                            h_scale: wire_h_scale,                         });                     } else if clip_only || invisible {                         // Mode 7: no paint, but carry the glyph so Kotlin can add@@ -399,7 +467,7 @@ pub(crate) fn show_string_in(                             is_italic: italic,                             font_family: family,                             outline: false,-                            h_scale: th as f32,+                            h_scale: wire_h_scale,                         });                     }                 }@@ -465,7 +533,21 @@ fn show_string_type3(     let trm = mat_mul(text_matrix, &gs.ctm);     let x_scale = (trm[0] * trm[0] + trm[1] * trm[1]).sqrt();     let y_scale = (trm[2] * trm[2] + trm[3] * trm[3]).sqrt();-    let size = (tfs * y_scale) as f32;+    // See `show_string_in`: Th alone under-describes an anisotropic matrix to the+    // substitute face, is exactly right for every isotropic one, and is bounded on+    // the serialized f32 so neither a degenerate matrix nor an overflowing cast can+    // put a non-finite scale on the wire (NaN survives the consumer's clamp).+    let aniso = if y_scale > 1e-9 { x_scale / y_scale } else { 1.0 };+    let wire_h_scale = th * if aniso.is_finite() { aniso.clamp(0.01, 100.0) } else { 1.0 };+    let wire_h_scale = {+        let v = wire_h_scale as f32;+        if v.is_finite() {+            v+        } else {+            1.0+        }+    };+    let size = finite_or_zero((tfs * y_scale) as f32);     let mut pen = 0.0_f64;     let mut glyphs = 0usize; @@ -623,7 +705,8 @@ fn show_string_type3(                     size,                     argb: 0,                     text: s,-                    advance: ((fi.width(code) * tfs * th * x_scale) as f32).max(size * 0.1),+                    advance: finite_or_zero((fi.width(code) * tfs * th * x_scale) as f32)+                        .max(size * 0.1),                     stroke_argb: None,                     stroke_width: None,                     render_mode: gs.render_mode as u8,@@ -632,7 +715,7 @@ fn show_string_type3(                     is_italic: false,                     font_family: 0,                     outline: false,-                    h_scale: th as f32,+                    h_scale: wire_h_scale,                 });             }         }@@ -772,6 +855,320 @@ mod degenerate_stroke_tests {             assert!(!out.iter().any(|p| matches!(p, Prim::Fill { .. })));         }     }++    /// `emit_stroke` emits one primitive PER SUBPATH, and every caller checks the+    /// cap once BEFORE the call (`interpret.rs`: `else if prims.len() <+    /// MAX_PRIMITIVES { emit_stroke(…) }`), so the loop has to bound itself or a+    /// single `S` on a MAX_SUBPATHS-subpath path walks straight past the ceiling.+    /// `MAX_PRIMITIVES` is the process's memory guard against an uncatchable Rust+    /// OOM and its doc states it is enforced at every content-emitting push.+    #[test]+    fn emit_stroke_stops_at_the_primitive_cap() {+        let gs = GraphicsState { line_width: 1.0, ..Default::default() };+        let subpaths: Vec<Vec<(f64, f64)>> =+            (0..64).map(|i| vec![(i as f64, 0.0), (i as f64, 10.0)]).collect();+        let mut prims: Vec<Prim> = Vec::new();+        // Start just under the cap, as the caller's own check guarantees. Built by+        // `extend` rather than `resize` on purpose: `Vec::resize` needs `T: Clone`,+        // and `Prim` must not be cloneable-by-habit — `Image`/`ImageTiled` carry the+        // whole decoded payload. Nothing here should force a derive on model.rs.+        prims.extend((0..MAX_PRIMITIVES - 4).map(|_| Prim::ClipPop));+        emit_stroke(&mut prims, &subpaths, &gs);+        assert_eq!(+            prims.len(),+            MAX_PRIMITIVES,+            "the cap must bound the per-subpath loop, not just its entry"+        );+    }+}++#[cfg(test)]+mod blind_reaudit_r5_text_tests {+    use crate::outlines::GlyphProgram;+    use crate::type1::Type1Font;+    use crate::*;+    use std::sync::Arc;++    /// A 1000x1000 box on a 1000-unit em, reachable as glyph name "A" at code 65.+    fn embedded_box_font(wmode: u8) -> FontInfo {+        let t1 = Type1Font {+            glyphs: [(+                "A".to_string(),+                vec![vec![(0.0, 0.0), (1000.0, 0.0), (1000.0, 1000.0), (0.0, 1000.0), (0.0, 0.0)]],+            )]+            .into_iter()+            .collect(),+            encoding: [(65u32, "A".to_string())].into_iter().collect(),+            font_matrix: [0.001, 0.0, 0.0, 0.001, 0.0, 0.0],+        };+        FontInfo {+            two_byte: false,+            wmode,+            vertical_metrics: Arc::default(),+            default_vertical: (0.880, -1.0),+            cid_to_gid: None,+            to_unicode: None,+            encoding: Arc::new([(65u32, 'A')].into_iter().collect()),+            cmap_uni: Arc::default(),+            cmap: None,+            widths: Arc::new([(65u32, 0.5)].into_iter().collect()),+            default_width: 0.5,+            t3: None,+            style: FontStyle::default(),+            family: 0,+            base_font: String::new(),+            glyph_program: Some(Arc::new(GlyphProgram::Type1(t1))),+            glyph_names: Arc::new([(65u32, "A".to_string())].into_iter().collect()),+        }+    }++    fn show(fi: FontInfo, gs: GraphicsState) -> Vec<Prim> {+        let doc = Document::with_version("1.7");+        let mut fonts = HashMap::new();+        fonts.insert(b"F1".to_vec(), fi);+        let mut prims = Vec::new();+        show_string(&doc, &mut prims, &gs, &fonts, &IDENTITY, b"A", 0);+        prims+    }++    fn state(render_mode: i64) -> GraphicsState {+        GraphicsState {+            font_key: b"F1".to_vec(),+            font_size: 100.0,+            render_mode,+            ..Default::default()+        }+    }++    /// §9.3.6 Table 106: mode 3 is "Neither fill nor stroke text (invisible)" and+    /// mode 7 is "Add to path for clipping" — neither marks the page. Mode 3 is how+    /// every scanned document carries its OCR layer, so if it paints, the scan is+    /// overprinted with a second copy of its own text.+    ///+    /// Asserted against an EMBEDDED font, because that is the path that can paint:+    /// modes 0-2 emit real outlines as `Prim::Fill`/`Prim::Stroke`, which the Kotlin+    /// side has no render-mode guard for (it skips `Prim::Text` for rm 3/7, and skips+    /// `outline`-flagged Text entirely). Ink for mode 3 therefore has to be suppressed+    /// HERE or not at all.+    #[test]+    fn render_mode_3_and_7_emit_no_ink_even_with_an_embedded_program() {+        let ink = |p: &Prim| matches!(p, Prim::Fill { .. } | Prim::Stroke { .. });++        // Precondition: this font really does paint in a painting mode.+        assert!(+            show(embedded_box_font(0), state(0)).iter().any(ink),+            "precondition: mode 0 must emit outline ink, or the test proves nothing"+        );++        for rm in [3i64, 7] {+            let prims = show(embedded_box_font(0), state(rm));+            assert!(+                !prims.iter().any(ink),+                "render mode {rm} must paint nothing, got {} ink prim(s)",+                prims.iter().filter(|p| ink(p)).count()+            );+            let texts: Vec<_> = prims+                .iter()+                .filter_map(|p| match p {+                    Prim::Text { argb, render_mode, text, .. } => Some((*argb, *render_mode, text)),+                    _ => None,+                })+                .collect();+            assert_eq!(texts.len(), 1, "mode {rm} must still reach the text index");+            assert_eq!(texts[0].0, 0, "mode {rm} text prim must carry no colour");+            assert_eq!(texts[0].1, rm as u8);+        }+    }++    /// The glyph-space -> text-space scale is the font program's units-per-em, and it+    /// is applied exactly once: a 1000-unit box on a 1000-unit em at 100 Tf spans+    /// 100 user-space units. Applying it twice (or not at all) is invisible in a+    /// units-per-em-1000 font only if the second factor is 1, which is why this+    /// asserts the absolute extent rather than a ratio.+    #[test]+    fn an_embedded_outline_is_scaled_by_units_per_em_exactly_once() {+        let prims = show(embedded_box_font(0), state(0));+        let contours = prims+            .iter()+            .find_map(|p| match p {+                Prim::Fill { contours, .. } => Some(contours.clone()),+                _ => None,+            })+            .expect("mode 0 with an embedded program must emit outline fills");+        let xs: Vec<f32> = contours.iter().flatten().map(|p| p.0).collect();+        let ys: Vec<f32> = contours.iter().flatten().map(|p| p.1).collect();+        let max_x = xs.iter().cloned().fold(f32::MIN, f32::max);+        let max_y = ys.iter().cloned().fold(f32::MIN, f32::max);+        assert!((max_x - 100.0).abs() < 1e-3, "em box should span 100 user units, got {max_x}");+        assert!((max_y - 100.0).abs() < 1e-3, "em box should span 100 user units, got {max_y}");+    }++    /// Horizontal scaling (Tz) scales the glyph and its advance horizontally only+    /// (§9.4.4: Th multiplies the x column of the text-space parameter matrix).+    #[test]+    fn horizontal_scaling_widens_the_outline_without_stretching_it_vertically() {+        let gs = GraphicsState { h_scale: 2.0, ..state(0) };+        let prims = show(embedded_box_font(0), gs);+        let contours = prims+            .iter()+            .find_map(|p| match p {+                Prim::Fill { contours, .. } => Some(contours.clone()),+                _ => None,+            })+            .expect("outline fill");+        let max_x = contours.iter().flatten().map(|p| p.0).fold(f32::MIN, f32::max);+        let max_y = contours.iter().flatten().map(|p| p.1).fold(f32::MIN, f32::max);+        assert!((max_x - 200.0).abs() < 1e-3, "Tz 200 must double the width, got {max_x}");+        assert!((max_y - 100.0).abs() < 1e-3, "Tz must not touch the height, got {max_y}");+    }++    /// §9.4.4: Trise is a row of the text-space parameter matrix, which does not+    /// depend on the writing mode. The vertical branch built its placement point+    /// from the position vector alone and dropped Trise, so a superscript in+    /// vertical CJK sat on the baseline.+    #[test]+    fn text_rise_applies_in_vertical_writing_mode_too() {+        let origin = |rise: f64| {+            let gs = GraphicsState { rise, ..state(3) };+            show(embedded_box_font(1), gs)+                .into_iter()+                .find_map(|p| match p {+                    Prim::Text { y, .. } => Some(y),+                    _ => None,+                })+                .expect("a text prim per glyph")+        };+        assert!(+            (origin(20.0) - origin(0.0) - 20.0).abs() < 1e-3,+            "Trise must displace a vertical glyph by 20 user units"+        );+    }++    /// Substitute glyphs are sized by Kotlin as `size` (the em, taken from the+    /// matrix's Y scale) times `h_scale` (Tz). Under an ANISOTROPIC matrix those+    /// two do not describe the glyph the outline path draws: the outline is scaled+    /// by x_scale horizontally and y_scale vertically, so the substitute came out+    /// narrower or wider by exactly that ratio — the two paths disagreeing about+    /// the size of the same glyph. The ratio is the only part of the mismatch the+    /// current wire can carry (a rotation still needs a field that does not exist),+    /// and it must be exactly 1 for every isotropic matrix, which is nearly all of+    /// them — hence the second half of this test.+    #[test]+    fn the_substitute_face_is_told_the_matrixs_horizontal_scale() {+        let h_scale_for = |ctm: Mat, th: f64| {+            let mut fi = embedded_box_font(0);+            fi.glyph_program = None; // force the substitute path+            let gs = GraphicsState { ctm, h_scale: th, ..state(0) };+            show(fi, gs)+                .into_iter()+                .find_map(|p| match p {+                    Prim::Text { h_scale, size, .. } => Some((h_scale, size)),+                    _ => None,+                })+                .expect("substitute path emits a text prim")+        };++        // Isotropic: unchanged, whatever the zoom. This is the case that must not move.+        for s in [1.0, 3.0, 0.25] {+            let (hs, _) = h_scale_for([s, 0.0, 0.0, s, 0.0, 0.0], 1.0);+            assert!((hs - 1.0).abs() < 1e-5, "isotropic scale {s} must leave Tz alone, got {hs}");+        }+        // A pure rotation is isotropic too.+        let (a, b) = (0.6_f64, 0.8_f64); // cos/sin of a 53-degree rotation+        let (hs, _) = h_scale_for([a, b, -b, a, 0.0, 0.0], 1.0);+        assert!((hs - 1.0).abs() < 1e-5, "a pure rotation must leave Tz alone, got {hs}");++        // Anisotropic: x twice y. The em still comes from the Y scale, and the+        // horizontal stretch rides on h_scale.+        let (hs, size) = h_scale_for([2.0, 0.0, 0.0, 1.0, 0.0, 0.0], 1.0);+        assert!((hs - 2.0).abs() < 1e-5, "x_scale/y_scale = 2 must reach the wire, got {hs}");+        assert!((size - 100.0).abs() < 1e-3, "the em still follows the Y scale, got {size}");++        // …and it composes with a real Tz rather than replacing it.+        let (hs, _) = h_scale_for([2.0, 0.0, 0.0, 1.0, 0.0, 0.0], 0.5);+        assert!((hs - 1.0).abs() < 1e-5, "Tz 50% under a 2:1 matrix, got {hs}");++        // A near-degenerate matrix must not put a non-finite or absurd scale on the+        // wire. y_scale sits just above the divide-by-zero guard, so the raw ratio+        // is ~5e8; the producer bounds it rather than relying on the consumer.+        let (hs, _) = h_scale_for([1.0, 0.0, 0.0, 2e-9, 0.0, 0.0], 1.0);+        assert!(hs.is_finite() && (0.01..=100.0).contains(&hs), "unbounded scale {hs}");+        // Fully degenerate (below the guard) falls back to plain Tz.+        let (hs, _) = h_scale_for([1.0, 0.0, 0.0, 0.0, 0.0, 0.0], 0.75);+        assert!((hs - 0.75).abs() < 1e-5, "degenerate matrix must yield plain Tz, got {hs}");++        // A pathological Tz must not reach the wire either. NaN is the one that+        // matters: Kotlin's `coerceIn` is two comparisons, both false against NaN,+        // so it would sail through the consumer's clamp into `Paint.textScaleX` and+        // the glyph would silently disappear rather than be the wrong width.+        for bad_tz in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {+            for ctm in [[1.0, 0.0, 0.0, 1.0, 0.0, 0.0], [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]] {+                let (hs, _) = h_scale_for(ctm, bad_tz);+                assert!(hs.is_finite(), "Tz {bad_tz} put {hs} on the wire");+            }+        }+    }++    /// `Tf`'s operand and the CTM are file input and `size` is their product, so a+    /// non-finite value is reachable even with both validated upstream: `f64 as f32`+    /// saturates to infinity above ~3.4e38, and `inf * 0` from a zero-scale matrix+    /// is NaN. It matters because NaN is not merely a wrong number here — Kotlin+    /// floors the size with `coerceAtLeast`, a comparison that is false against NaN,+    /// so it reaches `Paint.textSize` and the glyph vanishes.+    #[test]+    fn a_pathological_font_size_cannot_put_nan_on_the_wire() {+        let sizes = |tfs: f64, ctm: Mat| {+            let mut fi = embedded_box_font(0);+            fi.glyph_program = None;+            let gs = GraphicsState { ctm, font_size: tfs, ..state(0) };+            show(fi, gs)+                .into_iter()+                .filter_map(|p| match p {+                    Prim::Text { size, advance, .. } => Some((size, advance)),+                    _ => None,+                })+                .collect::<Vec<_>>()+        };+        let zero_scale: Mat = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0];+        let identity: Mat = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];+        for (tfs, ctm) in [+            (f64::INFINITY, zero_scale), // inf * 0 = NaN, the reachable case+            (f64::INFINITY, identity),+            (f64::NAN, identity),+            (1e308, identity),+        ] {+            for (size, advance) in sizes(tfs, ctm) {+                assert!(size.is_finite(), "Tf {tfs} produced size {size}");+                assert!(advance.is_finite(), "Tf {tfs} produced advance {advance}");+            }+        }+    }++    /// The no-metrics fallback returns a run advance of `len * 0.5 * Tfs * Th` but+    /// used to put ONE glyph's `size` on the wire as the run's device advance. A+    /// non-painted run (mode 3 — the OCR layer of a scan with an unresolvable font+    /// resource) is aligned to that field by the selection layer, so every glyph's+    /// selection rectangle piled up on the first character.+    #[test]+    fn a_run_with_no_font_metrics_reports_the_whole_runs_advance() {+        let doc = Document::with_version("1.7");+        let fonts: HashMap<Vec<u8>, FontInfo> = HashMap::new();+        let gs = GraphicsState { font_key: b"F1".to_vec(), font_size: 10.0, ..Default::default() };+        let mut prims = Vec::new();+        let pen = show_string(&doc, &mut prims, &gs, &fonts, &IDENTITY, b"ABCD", 0);+        let advance = prims+            .iter()+            .find_map(|p| match p {+                Prim::Text { advance, .. } => Some(*advance),+                _ => None,+            })+            .expect("the run must still reach the text index");+        assert!((pen - 20.0).abs() < 1e-9, "4 codes at 0.5 em of 10 Tf");+        assert!(+            (advance - pen as f32).abs() < 1e-3,+            "the wire advance must span the whole run ({pen}), got {advance}"+        );+    } }  #[cfg(test)]
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 9a139f9bb5..dc17a19450 100644--- a/pdf/src/main/rust/src/filters.rs+++ b/pdf/src/main/rust/src/filters.rs@@ -453,27 +453,43 @@ pub fn decode_ccitt(data: &[u8], w: u32, h: u32, params: &CcittParams) -> Option     if cols_us == 0 || rows_us == 0 || cols_us > 20000 || rows_us > 20000 { return None; }     let row_bytes = cols_us.div_ceil(8);     if (cols_us * rows_us) > 16 * 1024 * 1024 { return None; }-    let mut packed = vec![0u8; row_bytes * rows_us];      let black_is1 = params.black_is1;-    // Fill helper honoring BlackIs1 inversion: fax crate Black pel = 1 bit per G3/G4 logical.-    // Spec: BlackIs1 false (default) means 0 bits are black? Actually PDF spec: BlackIs1 false => 1-bits are not black (0=black), True=>1=black.-    // Wait typical fax: BlackIs1 false (default) 0=white, 1? Actually check: PDF 1.7 Table 8: BlackIs1: 0= white is 0? spec says if false, 1 bits are white? Let's interpret: false => 1 is black? Quick reference: PDF spec says BlackIs1 false (default) means 1 bits will be interpreted as white (0 black), True means 1 is black. But many viewers treat default as 1=white? Actually typical TIFF: 0=white means Photometric 0=white, so 1=black. BlackIs1 true means 1=black.-    // So false => 1=white => need invert black pels (fax Black -> should be white when false? Hmm)-    // For robustness and to match Telerik # fix: invert when BlackIs1==false (default) vs true? Let's implement: true=>1=black => keep black as black (no invert), false=>1=white => black pel should become white => invert.-    // Previous code ignored flag; we now honor: paint_black = is_black if black_is1 else !is_black+    // Byte value meaning WHITE in the sample polarity this function emits (see+    // `fill_rows`): with the /BlackIs1 default of false a 1 bit is white, with+    // /BlackIs1 true a 0 bit is.+    //+    // Rows the fax decoder never produced — a truncated or corrupt codestream, or a+    // /Rows//Height taller than the data — keep this value. They used to keep 0, which+    // under the DEFAULT parameters is BLACK, so the undecoded tail of a scan rendered+    // as a solid black band across the page (and as alpha 0, i.e. the base image+    // vanishing, when the stream was a soft mask). Neither `decode_ccitt`'s caller nor+    // this function can tell those rows apart from decoded ones after the fact, so the+    // background has to be right here. White is the background of every fax page.+    let white_byte: u8 = if black_is1 { 0x00 } else { 0xFF };+    let mut packed = vec![white_byte; row_bytes * rows_us];+    // §7.4.6 Table 11 /BlackIs1: false (the default) means 0 bits are black, true means+    // 1 bits are black. The filter's job is only to emit samples in that polarity; it is+    // the COLOUR SPACE that then decides what a sample means on the page, so this must+    // not also be folded into the image layer (`images.rs` reads sample 0 as black per+    // §8.9.5.2 and does not re-apply the flag).     let fill_rows = |lines: Vec<Vec<u32>>, packed: &mut Vec<u8>| {         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) {+                if cur_x >= cols_us { break; }                 let is_black = matches!(pel, fax::Color::Black);-                let paint_black = if black_is1 { is_black } else { !is_black };-                if paint_black {-                    packed[y * row_bytes + cur_x / 8] |= 1 << (7 - (cur_x % 8));-                }+                // Whether this pel's SAMPLE is a 1 bit, which /BlackIs1 selects.+                let bit_is_one = if black_is1 { is_black } else { !is_black };+                let mask = 1u8 << (7 - (cur_x % 8));+                // Written rather than OR-ed: the row starts at `white_byte`, so a pel+                // the decoder says is white must be able to CLEAR a bit as well as set+                // 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;-                if cur_x >= cols_us { break; }             }         }     };@@ -746,6 +762,52 @@ fn apply_tiff_predictor2(mut data: Vec<u8>, cols: usize, colors: usize, bpc: usi #[cfg(test)] mod tests {     use super::*;+    #[test]+    fn ccitt_rows_the_decoder_never_reached_come_back_white() {+        // §7.4.6 Table 11: /Rows (or /Height) fixes the scan-line count, and a real+        // fax stream is routinely truncated. The rows the decoder never produced used+        // to keep the zero the buffer was allocated with, which under the /BlackIs1+        // DEFAULT is BLACK - a solid black band across the bottom of the page, and+        // alpha 0 (the base image gone) when the same stream is a soft mask.+        //+        // A fax page's background is white, so that is what an unproduced row has to be.+        let mut enc = fax::encoder::Encoder::new(fax::VecWriter::new());+        let row = (0..8).map(|_| fax::Color::White);+        enc.encode_line(row, 8).expect("VecWriter is infallible");+        let data = enc.finish().expect("infallible").finish();++        // Three rows declared, one row of payload.+        let params = CcittParams { k: -1, columns: 8, rows: 3, ..CcittParams::default() };+        let packed = decode_ccitt(&data, 8, 3, &params).expect("one good row must still decode");+        assert_eq!(packed.len(), 3, "one byte per 8-column row, three rows");+        // /BlackIs1 false => a 1 bit is WHITE, so an unreached row must be all ones.+        assert_eq!(packed[1], 0xFF, "row 1 was never decoded and must read as white");+        assert_eq!(packed[2], 0xFF, "row 2 likewise");++        // /BlackIs1 true reverses which bit means white, so the background flips too.+        let params = CcittParams { black_is1: true, ..params };+        let packed = decode_ccitt(&data, 8, 3, &params).expect("decodes");+        assert_eq!(packed[1], 0x00, "with /BlackIs1 true a 0 bit is white");+        assert_eq!(packed[2], 0x00);+    }++    #[test]+    fn ccitt_pels_are_written_not_or_ed_into_the_white_background() {+        // The background fill only works if a decoded pel can CLEAR a bit as well as+        // set one; an OR-only fill would leave every pel white.+        let mut enc = fax::encoder::Encoder::new(fax::VecWriter::new());+        // 1010... so a bug that writes only one polarity is visible in one byte.+        let row: Vec<fax::Color> = (0..8)+            .map(|x| if x % 2 == 0 { fax::Color::Black } else { fax::Color::White })+            .collect();+        enc.encode_line(row.iter().copied(), 8).expect("infallible");+        let data = enc.finish().expect("infallible").finish();+        let params = CcittParams { k: -1, columns: 8, rows: 1, ..CcittParams::default() };+        let packed = decode_ccitt(&data, 8, 1, &params).expect("decodes");+        // /BlackIs1 false: black pel => 0 bit, white pel => 1 bit.+        assert_eq!(packed[0], 0b0101_0101, "alternating pels must survive the fill");+    }+     #[test] fn ascii_hex_basic() {         let out = decode_ascii_hex(b"48656C6C6F>");         assert_eq!(out, b"Hello");
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 498d1050c3..bacc488753 100644--- a/pdf/src/main/rust/src/fonts.rs+++ b/pdf/src/main/rust/src/fonts.rs@@ -405,7 +405,10 @@ fn named_base_encoding_names(doc: &Document, font: &lopdf::Dictionary) -> HashMa }  pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {-    let subtype = font.get(b"Subtype").ok().and_then(|o| o.as_name().ok());+    // Every one of these may be an indirect reference. An unresolved `/Subtype`+    // silently makes a Type0 font parse as a simple one — 2-byte codes read as+    // single bytes, so the whole string decodes to garbage.+    let subtype = font.get(b"Subtype").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_name().ok());     let two_byte = matches!(subtype, Some(b"Type0"));     let is_type3 = subtype == Some(b"Type3");     let to_unicode = font@@ -619,7 +622,7 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {     }      // --- Font style detection for bold/italic synthesis ----    let base_font_name = font.get(b"BaseFont").ok().and_then(|o| o.as_name().ok())+    let base_font_name = font.get(b"BaseFont").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_name().ok())         .map(|n| String::from_utf8_lossy(n).to_string())         .or_else(|| {             // Try descendant for Type0@@ -628,6 +631,7 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {                 .and_then(|o| deref(doc, o))                 .and_then(|o| o.as_dict().ok())                 .and_then(|d| d.get(b"BaseFont").ok())+                .and_then(|o| deref(doc, o))                 .and_then(|o| o.as_name().ok())                 .map(|n| String::from_utf8_lossy(n).to_string())         })@@ -726,6 +730,17 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {             // reachable by resolving the AFM name to Unicode and matching the             // encoding's code -> Unicode map. Built in sorted-name order so a             // Unicode collision resolves deterministically.+            //+            // Deterministic is NOT the same as correct, and the difference is worth+            // knowing before trusting a width that came from here. This map is keyed+            // by Unicode, so when several AFM glyphs share one character the code's+            // OWN glyph is not necessarily the one that wins — the alphabetically+            // first name does. Symbol's bracket build-up pieces are the live case:+            // if the encoding maps `parenlefttp` to '(' then that code inherits+            // `parenleft`'s advance. It stays a strictly better estimate than the+            // invented default this path exists to avoid, but a code whose true+            // advance is known should reach the exact-name lookup above instead of+            // arriving here.             let by_char: HashMap<char, f64> = {                 let mut names: Vec<&String> = afm.keys().collect();                 names.sort();@@ -743,6 +758,19 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {                     .cloned()                     .or_else(|| base_names.get(&code).cloned())                     .or_else(|| {+                        // Last resort, and it runs for EVERY face — including Symbol+                        // and ZapfDingbats, whose built-in encodings have nothing to+                        // do with StandardEncoding. That makes this a cross-file+                        // invariant with afm.rs, not a local choice: a Standard name+                        // that an AFM table also defines AT A DIFFERENT CODE would be+                        // charged here, silently, in preference to the encoding-derived+                        // match below. r5-fontprog enumerated the collision set for+                        // Symbol in R5 and it is EMPTY — Standard and Symbol share only+                        // fraction, florin, bullet and ellipsis, at the same code in+                        // both — so the guess is safe today. It is afm.rs's table+                        // contents that keep it safe, so anyone ADDING rows there has+                        // to re-check against `STANDARD_ENCODING`'s 0xA0-0xFF names,+                        // and anyone reordering this chain has to re-check the reverse.                         crate::type1::STANDARD_ENCODING                             .iter()                             .find(|(c, _)| *c as u32 == code)@@ -819,7 +847,7 @@ fn type3_widths(doc: &Document, font: &lopdf::Dictionary, fm_scale: f64) -> (Has     if let Some(Object::Array(arr)) = font.get(b"Widths").ok().and_then(|o| deref(doc, o)) {         for (i, w) in arr.iter().enumerate() {             if let Some(w) = deref(doc, w).and_then(num) {-                widths.insert(first_char + i as u32, w * fm_scale);+                widths.insert(first_char.saturating_add(i as u32), w * fm_scale);             }         }     }@@ -841,7 +869,11 @@ pub(crate) fn simple_widths(doc: &Document, font: &lopdf::Dictionary) -> (HashMa     if let Some(Object::Array(arr)) = font.get(b"Widths").ok().and_then(|o| deref(doc, o)) {         for (i, w) in arr.iter().enumerate() {             if let Some(w) = deref(doc, w).and_then(num) {-                widths.insert(first_char + i as u32, w / 1000.0);+                // `/FirstChar` is file-controlled and `num`'s `as u32` saturates at+                // u32::MAX, so `first_char + i` panics in debug and WRAPS in release+                // — putting the whole /Widths table on codes 0.. and charging every+                // glyph the wrong advance. Same hazard the `/W` array form carries.+                widths.insert(first_char.saturating_add(i as u32), w / 1000.0);             }         }     }@@ -1131,7 +1163,10 @@ pub(crate) mod ttf {                             let range_off = u16b(b, sh_off + 6) as usize;                             let glyph: u16 = if range_off == 0 {                                 let delta = u16b(b, sh_off + 4) as i16;-                                (sbyte as i16 + delta) as u16+                                // idDelta is modulo-65536 arithmetic (OpenType `cmap`,+                                // format 2/4). A plain `+` panics in debug on a crafted+                                // delta; format 4 below already wraps.+                                (sbyte as i16).wrapping_add(delta) as u16                             } else {                                 let addr = ghi_off + range_off;                                 u16b(b, addr)@@ -1160,7 +1195,7 @@ pub(crate) mod ttf {                     for low in 0u32..entry_count.min(256) {                         let code = (hi << 8) | (first_code + low);                         let gid = if range_off == 0 {-                            ((first_code + low) as i16 + delta) as u16+                            ((first_code + low) as i16).wrapping_add(delta) as u16                         } else {                             let addr = sub_header_off + sh_idx * 8 + 6 + range_off + (low as usize * 2);                             u16b(b, addr)@@ -1257,7 +1292,8 @@ pub(crate) mod ttf {                 for i in 0..count.min(0x20000) {                     let g = u16b(b, off + 20 + i * 2);                     if g != 0 {-                        out.push((first + i as u32, g));+                        // `first` is a file-supplied u32: `first + i` panics in debug.+                        out.push((first.saturating_add(i as u32), g));                     }                 }             }@@ -1275,7 +1311,10 @@ pub(crate) mod ttf {                         continue;                     }                     for c in sc..=ec {-                        out.push((c, (sg + (c - sc)) as u16));+                        // `sg` is a file-supplied u32 and startGlyphID is modulo+                        // arithmetic once truncated to a glyph id; a plain `+`+                        // panics in debug near u32::MAX.+                        out.push((c, sg.wrapping_add(c - sc) as u16));                     }                 }             }@@ -1473,6 +1512,50 @@ pub(crate) mod ttf {             assert!(pairs.contains(&(0x41, 7)));             assert!(pairs.contains(&(0x42, 8)));         }++        /// A `cmap` comes from an untrusted embedded font program, and the code+        /// arithmetic in formats 2, 10 and 12 is all file-supplied. Debug builds+        /// panic on integer overflow, so an unchecked `+` here is reachable by a+        /// crafted (or merely corrupt) /FontFile2. Format 4 was already hardened+        /// with `wrapping_add`; these three were not.+        #[test]+        fn hostile_cmap_subtables_do_not_overflow() {+            // Format 10 with startCharCode = u32::MAX.+            let mut b = Vec::new();+            b.extend_from_slice(&be16(10));+            b.extend_from_slice(&be16(0));+            b.extend_from_slice(&be32(0));+            b.extend_from_slice(&be32(0));+            b.extend_from_slice(&be32(u32::MAX));+            b.extend_from_slice(&be32(3));+            for g in 1..=3u16 {+                b.extend_from_slice(&be16(g));+            }+            assert!(!parse_subtable(&b, 0).is_empty());++            // Format 12 with startGlyphID = u32::MAX over a multi-code group.+            let mut b = Vec::new();+            b.extend_from_slice(&be16(12));+            b.extend_from_slice(&be16(0));+            b.extend_from_slice(&be32(0));+            b.extend_from_slice(&be32(0));+            b.extend_from_slice(&be32(1));+            b.extend_from_slice(&be32(0x41));+            b.extend_from_slice(&be32(0x43));+            b.extend_from_slice(&be32(u32::MAX));+            assert_eq!(parse_subtable(&b, 0).len(), 3);++            // Format 2 with an idDelta that overflows i16 for the mapped code.+            let mut b = vec![0u8; 6];+            b[0..2].copy_from_slice(&be16(2));+            b.extend_from_slice(&[0u8; 512]); // subHeaderKeys: all single-byte+            b.extend_from_slice(&be16(0));    // firstCode 0+            b.extend_from_slice(&be16(0));    // entryCount+            b.extend_from_slice(&be16(0x7FFF)); // idDelta+            b.extend_from_slice(&be16(0));    // idRangeOffset+            b.extend_from_slice(&[0u8; 8]);   // glyphIndexArray+            let _ = parse_subtable(&b, 0);+        }     } } @@ -1497,6 +1580,7 @@ pub(crate) mod encoding {         let base_font = font             .get(b"BaseFont")             .ok()+            .and_then(|o| deref(doc, o))             .and_then(|o| o.as_name().ok())             .map(|n| String::from_utf8_lossy(n).into_owned())             .unwrap_or_default();@@ -1508,6 +1592,7 @@ pub(crate) mod encoding {             Some(Object::Dictionary(d)) => d                 .get(b"BaseEncoding")                 .ok()+                .and_then(|o| deref(doc, o))                 .and_then(|o| o.as_name().ok())                 .map(|n| String::from_utf8_lossy(n).into_owned()),             _ => None,@@ -2125,6 +2210,129 @@ mod encoding_priority_tests {     } } +#[cfg(test)]+mod blind_reaudit_r5_width_tests {+    use super::*;++    /// `/FirstChar` is file-controlled and `num`'s `as u32` SATURATES at u32::MAX,+    /// so `first_char + i` panicked in debug and wrapped in release — silently+    /// dropping the whole /Widths table onto codes 0.. and charging every glyph of+    /// the string another glyph's advance. `/W`'s array form was hardened against+    /// exactly this; `/Widths` and Type 3's `/Widths` were not.+    #[test]+    fn a_hostile_first_char_cannot_overflow_the_simple_width_table() {+        let doc = Document::new();+        let font = dictionary! {+            "Type" => "Font", "Subtype" => "TrueType", "BaseFont" => "NotAStandardFace",+            "FirstChar" => 4_294_967_295u32,+            "Widths" => vec![500.into(), 600.into(), 700.into()],+        };+        let (widths, _) = simple_widths(&doc, &font);+        // No wrap: nothing may land on a low code that a real glyph would use.+        // The saturated entries collide on u32::MAX, which is harmless — a simple+        // font's codes are single bytes, so no showing operator can ever ask for it.+        assert_eq!(widths.get(&0), None, "an overflowed key would collide with code 0");+        assert_eq!(widths.get(&1), None);+        assert_eq!(widths.keys().copied().collect::<Vec<_>>(), vec![u32::MAX]);+    }++    #[test]+    fn a_hostile_first_char_cannot_overflow_the_type3_width_table() {+        let doc = Document::new();+        let font = dictionary! {+            "Type" => "Font", "Subtype" => "Type3",+            "FirstChar" => 4_294_967_295u32,+            "Widths" => vec![500.into(), 600.into()],+        };+        let (widths, _) = type3_widths(&doc, &font, 0.001);+        assert_eq!(widths.get(&0), None);+        assert_eq!(widths.keys().copied().collect::<Vec<_>>(), vec![u32::MAX]);+    }++    /// Any dictionary value may be an indirect reference (7.3.10). An unresolved+    /// `/BaseFont` is not a missing name, it is the WRONG one: a non-embedded+    /// Helvetica loses its Core-14 metrics and every glyph falls back to a flat+    /// 0.5 em, so the line drifts against the rules and boxes drawn around it.+    #[test]+    fn an_indirect_base_font_still_resolves_its_standard_14_metrics() {+        let mut doc = Document::new();+        let name = doc.add_object(Object::Name(b"Helvetica".to_vec()));+        let font = dictionary! {+            "Type" => "Font", "Subtype" => "Type1",+            "BaseFont" => Object::Reference(name),+            "Encoding" => "WinAnsiEncoding",+        };+        let fi = font_info(&doc, &font);+        assert_eq!(fi.widths.get(&65).copied(), Some(0.667), "Helvetica's real /A advance");+        assert_eq!(fi.widths.get(&105).copied(), Some(0.222), "…and its narrow /i");+    }++    /// The standard-14 code->name chain ends in a StandardEncoding guess that runs+    /// for EVERY face, including Symbol, whose built-in encoding has nothing to do+    /// with StandardEncoding. It is safe only because no Symbol AFM name is also a+    /// StandardEncoding name at a DIFFERENT code — a property of afm.rs's table+    /// contents, not of this file, so a row added there could break it silently and+    /// at a distance. This asserts the invariant instead of documenting it: wherever+    /// the Standard guess and the font's own encoding both yield a width, they must+    /// agree. r5-fontprog enumerated the collision set by hand in R5 and found it+    /// empty; this keeps it empty.+    #[test]+    fn the_standard_encoding_guess_never_contradicts_symbols_own_encoding() {+        let afm = crate::afm::standard_14_widths("Symbol").expect("Symbol is a Core-14 face");+        let enc = crate::glyphlist::symbol();+        // `by_char` exactly as `font_info` builds it: sorted names, first wins.+        let by_char: HashMap<char, f64> = {+            let mut names: Vec<&String> = afm.keys().collect();+            names.sort();+            let mut m = HashMap::new();+            for n in names {+                if let Some(c) = encoding::glyph_to_char(n) {+                    m.entry(c).or_insert(afm[n]);+                }+            }+            m+        };+        let mut checked = 0;+        for (code, name) in crate::type1::STANDARD_ENCODING {+            let Some(&guessed) = afm.get(*name) else { continue };+            let Some(&derived) = enc.get(&(*code as u32)).and_then(|c| by_char.get(c)) else {+                continue;+            };+            assert_eq!(+                guessed, derived,+                "code {code:#04x}: StandardEncoding names it {name:?} ({guessed}), but Symbol's \+                 own encoding puts a {derived}-wide glyph there. The name guess runs FIRST, so \+                 this code would be charged the wrong advance."+            );+            checked += 1;+        }+        assert!(checked > 20, "only {checked} codes compared — the fixture stopped working");+    }++    /// Likewise `/Subtype`: unresolved, a Type0 font parses as a simple one, so its+    /// 2-byte codes are read one byte at a time and the entire string decodes to+    /// unrelated glyphs at unrelated advances.+    #[test]+    fn an_indirect_subtype_is_resolved_before_choosing_the_code_width() {+        let mut doc = Document::new();+        let sub = doc.add_object(Object::Name(b"Type0".to_vec()));+        let desc = doc.add_object(dictionary! {+            "Type" => "Font", "Subtype" => "CIDFontType2", "DW" => 1000,+        });+        let font = dictionary! {+            "Type" => "Font",+            "Subtype" => Object::Reference(sub),+            "BaseFont" => "Test",+            "DescendantFonts" => vec![desc.into()],+        };+        let fi = font_info(&doc, &font);+        assert!(fi.two_byte, "an indirect /Type0 must still be a composite font");+        let mut codes = Vec::new();+        fi.for_each_code(&[0x00, 0x41], |c, _| codes.push(c));+        assert_eq!(codes, vec![0x0041], "one 2-byte code, not two 1-byte codes");+    }+}+ #[cfg(test)] mod type1_tests {     use super::*;
pdf/src/main/rust/src/forms.rs
diff --git a/pdf/src/main/rust/src/forms.rs b/pdf/src/main/rust/src/forms.rsindex f61430beeb..821b72ff65 100644--- a/pdf/src/main/rust/src/forms.rs+++ b/pdf/src/main/rust/src/forms.rs@@ -12,6 +12,15 @@ pub(crate) fn field_attr<'a>(doc: &'a Document, mut id: ObjectId, key: &[u8]) ->     None } +/// A numeric field key resolved as §12.7.3.1 requires for the entries it marks+/// "Optional; inheritable": the widget's own value if it has one, otherwise the+/// nearest ancestor's up the `/Parent` chain.+fn inherited_num(doc: &Document, id: ObjectId, key: &[u8]) -> Option<f64> {+    field_attr(doc, id, key)+        .and_then(|o| deref(doc, o).or(Some(o)))+        .and_then(num)+}+ /// The terminal field a widget belongs to: the nearest dictionary at or above it /// carrying `/FT` (§12.7.3.1). `/V`, `/I`, `/Ff`, `/Q` and `/MaxLen` are keys of /// THAT field, so writing them on the clicked widget (when the widget is a@@ -47,6 +56,20 @@ fn acroform(doc: &Document) -> Option<&Dictionary> {         .and_then(|o| o.as_dict().ok()) } +/// A variable-text field's `/Q` quadding (0 left, 1 centred, 2 right): the+/// field's own, inheritable up `/Parent` (§12.7.4.3 Table 222), else the+/// AcroForm document-wide default (§12.7.2 Table 218).+fn field_quadding(doc: &Document, id: ObjectId) -> i64 {+    inherited_num(doc, id, b"Q")+        .or_else(|| {+            acroform(doc)+                .and_then(|af| af.get(b"Q").ok())+                .and_then(|o| deref(doc, o).or(Some(o)))+                .and_then(num)+        })+        .unwrap_or(0.0) as i64+}+ /// The pieces of a `/DA` default appearance string that a generated field /// appearance needs (§12.7.3.3: "a sequence of valid page-content graphics or /// text state operators ... defining such properties as the field's text size@@ -500,12 +523,18 @@ fn build_text_appearance(         String::from_utf8_lossy(font)     )); -    if comb && max_len > 0 {-        // One glyph per cell, centered in each cell. The vertical offset has to-        // be repeated on every `Tm`: `Tm` REPLACES the text matrix rather than-        // concatenating (§9.4.2), so setting the baseline once up front and then-        // issuing per-cell `Tm`s dropped every glyph to y=0, sitting the row on-        // the bottom edge of the box with its descenders clipped.+    if comb && !multiline && max_len > 0 {+        // One glyph per cell, centered in each cell. §12.7.4.3 Table 226 bit 25+        // makes Comb "meaningful only if the MaxLen entry is present ... and if+        // the Multiline, Password, and FileSelect flags are clear", so a field+        // carrying both flags wraps rather than chopping the value into MaxLen+        // one-character cells on a single row.+        //+        // The vertical offset has to be repeated on every `Tm`: `Tm` REPLACES+        // the text matrix rather than concatenating (§9.4.2), so setting the+        // baseline once up front and then issuing per-cell `Tm`s dropped every+        // glyph to y=0, sitting the row on the bottom edge of the box with its+        // desce

Diff truncated.