Modern Apps git

← Modern-Apps.git

pdf: fix renderer misrendering and missing content (#321)

Commit
122c365a6bc39f28d2be24b5b89c54654f7c28fc
Author
vayun-mathur <[email protected]>
When
2026-08-29 16:12 UTC (3 months ago)
Parents
3e01be2

Diff

pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.ktindex bb6ec96f60..f2dcf2128b 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/CutGlueScreen.kt@@ -48,6 +48,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp@@ -275,7 +276,20 @@ private fun ComposePageThumb(             if (current == null || current.width <= 0f) {                 CircularProgressIndicator(Modifier.align(Alignment.Center))             } else {-                Canvas(Modifier.fillMaxSize()) { drawSafePage(current) }+                Canvas(Modifier.fillMaxSize()) {+                    // drawSafePage only drains its save/saveLayer levels on the normal path, so+                    // a throwing primitive would leave them open and corrupt the sibling+                    // thumbnails drawn after this one. Anchor on the entry count and restore to+                    // it either way, as SafePdfPageCanvas does for the reader.+                    val base = drawContext.canvas.nativeCanvas.saveCount+                    try {+                        drawSafePage(current)+                    } catch (t: Throwable) {+                        android.util.Log.w("CutGlueScreen", "drawSafePage failed", t)+                    } finally {+                        drawContext.canvas.nativeCanvas.restoreToCount(base)+                    }+                }             }         }         IconButton(
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 b75428ff37..d29b7bc789 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -93,6 +93,7 @@ import androidx.compose.ui.geometry.lerp import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.asAndroidPath import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.TransformOrigin@@ -1251,9 +1252,17 @@ fun PdfOutlineDrawer( fun SafePdfPageCanvas(     page: SafePdfPage?,     modifier: Modifier = Modifier,+    placeholderRatio: Float? = null,     overlays: @Composable BoxWithConstraintsScope.(cw: Float, ch: Float, scale: Float) -> Unit = { _, _, _ -> }, ) {-    val ratio = if (page != null && page.height > 0f) page.width / page.height else 612f / 792f+    // A wrong placeholder ratio makes the item change height the moment the page decodes,+    // which shifts every item below it. Use the page's real ratio when known (see+    // SafePdfDocument.knownAspectRatio) and only fall back to letter-portrait when it isn't.+    val ratio = when {+        page != null && page.height > 0f -> page.width / page.height+        placeholderRatio != null && placeholderRatio > 0f -> placeholderRatio+        else -> 612f / 792f+    }      BoxWithConstraints(         modifier@@ -1271,7 +1280,20 @@ fun SafePdfPageCanvas(          // Render the (static) page into its own graphics layer so that overlay         // redraws while drawing/dragging don't replay every page primitive.-        Canvas(Modifier.fillMaxSize().graphicsLayer { clip = true }) { drawSafePage(decoded) }+        Canvas(Modifier.fillMaxSize().graphicsLayer { clip = true }) {+            // One unrenderable primitive must not take down the frame, nor leave the live+            // canvas holding open save/saveLayer levels — that would corrupt every sibling+            // drawn after it. Restoring to the entry count unwinds clips, groups and+            // soft-mask layers alike, compositing each layer in inner-to-outer order.+            val base = drawContext.canvas.nativeCanvas.saveCount+            try {+                drawSafePage(decoded)+            } catch (t: Throwable) {+                android.util.Log.w("SafePdfViewer", "drawSafePage failed", t)+            } finally {+                drawContext.canvas.nativeCanvas.restoreToCount(base)+            }+        }          val cw = constraints.maxWidth.toFloat()         overlays(cw, constraints.maxHeight.toFloat(), cw / decoded.width)@@ -1331,7 +1353,7 @@ private fun SafePdfPageItem(         current?.width?.let { if (it > 0f) onPageWidth(it) }     } -    SafePdfPageCanvas(current) { cw, ch, scale ->+    SafePdfPageCanvas(current, placeholderRatio = document.knownAspectRatio(index)) { cw, ch, scale ->         // Non-null inside the overlay slot: SafePdfPageCanvas only invokes it once the page         // has been decoded.         val decoded = current!!@@ -1551,8 +1573,23 @@ private fun buildEmbeddedGlyphs(page: SafePdfPage, ch: Float, scale: Float): Lis         tmpPaint.textScaleX = prim.hScale.coerceIn(0.2f, 4f)         tmpPaint.textSize = prim.size * scale         val textStr = prim.text-        val measuredTotal = if (textStr.isNotEmpty()) tmpPaint.measureText(textStr) else prim.size * 0.5f-        val perGlyphMeasured = if (textStr.isNotEmpty()) measuredTotal / textStr.length else prim.size * 0.5f * scale+        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+        val advanceFit = if (alignToAdvance && measuredTotal > 0f && prim.advance > 0f) {+            prim.advance * scale / measuredTotal+        } else {+            1f+        }+        val perGlyphMeasured = measuredTotal * advanceFit / textStr.length         var curPxPage = prim.origin.x         for (c in textStr) {             val px = curPxPage@@ -2687,6 +2724,14 @@ private fun android.graphics.Paint.setBlend(blend: BlendMode) {     blendMode = if (blend == BlendMode.Normal) null else blend.toAndroid() } +/**+ * Cap on nested transparency-group layers. Each one is an offscreen buffer, so unlike a+ * plain clip save it has a real memory cost. Rust bounds group depth at 32; exceeding it+ * must never abandon the page, so the push is still accounted (its matching pop then+ * restores the right level) and only the layer itself is skipped.+ */+private const val MAX_GROUP_LAYER_DEPTH = 32+ /**  * Draw a page's primitives, mapping PDF page space (origin bottom-left) to the  * canvas (origin top-left) with a uniform fit-to-width scale + Y-flip.@@ -2719,17 +2764,35 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {     var saveCount = 0     val clipPath = android.graphics.Path()     var groupSaveCount = 0-    // Active ExtGState soft-mask brackets. Each frame tracks how many mask-    // layers were opened at the SoftMaskContent marker so SoftMaskPop can undo-    // exactly the content layer + mask (+ luma) layers.-    class SoftMaskFrame(val maskType: Int) { var maskLayers = 0 }+    // Active ExtGState soft-mask brackets.+    class SoftMaskFrame(val maskType: Int) {+        /** Canvas levels this bracket has opened, so SoftMaskPop restores exactly them. */+        var levels = 0+        /** False when the content layer could not be allocated, in which case the mask+         *  primitives must be discarded rather than painted onto the page. */+        var masked = true+        /** /TR as `gain * m + bias`; identity until a SoftMaskTransfer arrives. */+        var trGain = 1f+        var trBias = 0f+    }     val softMaskStack = ArrayDeque<SoftMaskFrame>() -    fun clipOffsetList(pts: List<Offset>): List<Offset> = pts.map { map(it) }+    // Reused across primitives: drawSafePage runs on every frame at every zoom level, so a+    // Path/Matrix/Paint per primitive is a per-frame allocation on a list that can hold+    // hundreds of thousands of them. Canvas.drawPath/drawBitmap and saveLayer copy what they+    // need into the display list, so reuse is safe.+    val reusePath = Path()+    val pathOpsPath = android.graphics.Path()+    val imgMatrix = android.graphics.Matrix()+    val imgSrc = FloatArray(8)+    val imgDst = FloatArray(8)+    val groupPaint = android.graphics.Paint()+    val tilePaint = android.graphics.Paint()      // Bezier-retentive clip path (v4) and text-clip accumulation (Tr 4-7).     fun pathOpsToPath(ops: List<PathOp>): android.graphics.Path {-        val p = android.graphics.Path()+        val p = pathOpsPath+        p.reset()         for (op in ops) {             when (op) {                 is PathOp.Move -> { val o = map(Offset(op.x, op.y)); p.moveTo(o.x, o.y) }@@ -2751,14 +2814,10 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {     val tmpGlyphPath = android.graphics.Path()      for (prim in page.primitives) {-        // Primitive count guard double-check (OOM avoidance if Rust guard fails)-        if (saveCount > 64 || groupSaveCount > 32) {-            android.util.Log.w("SafePdfViewer", "Clip/group depth guard, skipping remaining prims")-            break-        }         when (prim) {             is PdfPrimitive.FillPath -> {-                val path = Path()+                val path = reusePath+                path.reset()                 var any = false                 for (contour in prim.contours) {                     if (contour.size < 2) continue@@ -2784,20 +2843,23 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {             }              is PdfPrimitive.StrokePath -> {-                val path = prim.points.toPath(::map) ?: continue-                // Fix double-scale bug: Rust already scales dash by CTM avg; Kotlin should NOT re-scale by *scale again for width? Per plan 2104-2105 double-scale.-                // We keep dash scaling by *scale for canvas space but avoid double scaling width which Rust already did.-                // Actually width already device-scaled in Rust via CTM avg, so we should NOT multiply by scale again beyond min clamp?-                // To preserve visual, we use prim.width directly coerceAtLeast(1f) but also consider canvas scale? We'll use prim.width * scale for stroke width only if width < threshold, else prim.width.-                // Correct logic: width from Rust is already CTM-scaled to page space * device? For fidelity we map as width * scale (page->canvas) as before, but dash was also scaled - need to ensure dash not double-scaled.-                // Rust: dash = gs.dash * CTM_avg_scale (device). Kotlin: dash * scale maps page->canvas. That's actually double scaling? Plan says dash scaling double-scale bug 2104-2105.-                // Fix: dash already scaled in Rust, so we should use dash directly, not *scale. Similarly width already scaled? But width scaling via CTM is needed for page->canvas.-                // We'll implement: width = prim.width * scale, dash = prim.dash (not multiplied) + phase = prim.dashPhase (not *scale) unless phase small.-                val dash = prim.dash-                val pathEffect = if (dash.size >= 2) {+                if (prim.points.size < 2) continue+                val path = reusePath+                path.reset()+                val start = map(prim.points[0])+                path.moveTo(start.x, start.y)+                for (i in 1 until prim.points.size) {+                    val p = map(prim.points[i])+                    path.lineTo(p.x, p.y)+                }+                // Rust emits width, dash lengths and dash phase all in page space+                // (draw.rs scales each by the CTM), so all three take the same+                // page->canvas factor. The miter limit is a ratio of miter length to+                // line width (PDF 32000-1 8.4.3.5) and must NOT be scaled.+                val pathEffect = if (prim.dash.size >= 2) {                     androidx.compose.ui.graphics.PathEffect.dashPathEffect(-                        dash,-                        prim.dashPhase,+                        FloatArray(prim.dash.size) { prim.dash[it] * scale },+                        prim.dashPhase * scale,                     )                 } else {                     null@@ -2812,7 +2874,7 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                     2 -> androidx.compose.ui.graphics.StrokeJoin.Bevel                     else -> androidx.compose.ui.graphics.StrokeJoin.Miter                 }-                // Miter limit is in line-width units per spec, not device pixels — do NOT scale by canvas scale (was a bug at 2104-2105).+                // Miter limit is in line-width units per spec, not device pixels.                 drawPath(                     path,                     Color(prim.color),@@ -2835,7 +2897,13 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                 val origin = map(prim.origin)                 val ts = (prim.size * scale).coerceAtLeast(1f)                 val rm = prim.renderMode-                val isStrokeOnly = prim.strokeColor != null && prim.color == prim.strokeColor+                // Tr decides whether the fill is painted (PDF 32000-1 9.3.6). Comparing+                // fill and stroke colour misfires for mode 2 with a single colour — the+                // standard faux-bold — and rendered it hollow. Only suppress the fill when+                // a stroke will actually be painted, since Rust's no-metrics path emits+                // mode 1 with no stroke colour and must still show something.+                val willStroke = prim.strokeColor != null && prim.strokeWidth > 0f+                val isStrokeOnly = willStroke && (rm == 1 || rm == 5)                  // v8: substitute the embedded font with a system typeface matching the                 // generic family (sans/serif/mono) + bold/italic recovered by Rust. Rust@@ -2863,9 +2931,10 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                 glyphPathPaint.textScaleX = hs                 glyphPathPaint.isFakeBoldText = fakeBold -                // Paint the glyphs unless this is a clip-only run (Tr 7).-                if (rm != 7) {-                    if (prim.strokeColor != null && prim.strokeWidth > 0f) {+                // Mode 3 paints nothing (it is how scanned PDFs carry an invisible OCR+                // text layer) and mode 7 is clip-only.+                if (rm != 3 && rm != 7) {+                    if (willStroke) {                         textStrokePaint.color = prim.strokeColor                         textStrokePaint.textSize = ts                         textStrokePaint.strokeWidth = (prim.strokeWidth * scale).coerceAtLeast(0.5f)@@ -2894,9 +2963,7 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {             }              is PdfPrimitive.Image -> {-                val bmp = prim.bitmap ?: continue-                // Placeholder for JBIG2 failure: instead of continue show gray box with warning per Phase 6-                // decodeBitmap now returns placeholder gray bitmap when unknown format+                val bmp = prim.bitmap?.takeUnless { it.isRecycled } ?: continue                 val matrixAlpha = prim.alpha.coerceIn(0f,1f)                 if (matrixAlpha < 1f) {                     imagePaint.alpha = (matrixAlpha*255).toInt()@@ -2904,6 +2971,12 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                     imagePaint.alpha = 255                 }                 val m = prim.ctm+                // PDF 32000-1 §8.9.5.1 Table 89: /Interpolate defaults to false, and bilevel+                // art (stencil masks, 1-bit scans, fax) must never be smoothed — bilinear+                // filtering turns crisp black-and-white line art into grey fringes. Rust makes+                // the per-image decision in image_should_interpolate; honour it here instead of+                // filtering everything.+                imagePaint.isFilterBitmap = prim.interpolate                 fun unitToCanvas(u: Float, v: Float): Offset {                     val pageX = m[0] * u + m[2] * v + m[4]                     val pageY = m[1] * u + m[3] * v + m[5]@@ -2911,20 +2984,90 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                 }                 val bw = bmp.width.toFloat()                 val bh = bmp.height.toFloat()-                val src = floatArrayOf(0f, 0f, bw, 0f, bw, bh, 0f, bh)+                imgSrc[0] = 0f; imgSrc[1] = 0f; imgSrc[2] = bw; imgSrc[3] = 0f+                imgSrc[4] = bw; imgSrc[5] = bh; imgSrc[6] = 0f; imgSrc[7] = bh                 val c00 = unitToCanvas(0f, 1f)                 val c10 = unitToCanvas(1f, 1f)                 val c11 = unitToCanvas(1f, 0f)                 val c01 = unitToCanvas(0f, 0f)-                val dst = floatArrayOf(c00.x, c00.y, c10.x, c10.y, c11.x, c11.y, c01.x, c01.y)-                val mat = android.graphics.Matrix()-                mat.setPolyToPoly(src, 0, dst, 0, 4)+                imgDst[0] = c00.x; imgDst[1] = c00.y; imgDst[2] = c10.x; imgDst[3] = c10.y+                imgDst[4] = c11.x; imgDst[5] = c11.y; imgDst[6] = c01.x; imgDst[7] = c01.y+                // setPolyToPoly leaves the matrix untouched when the destination quad is+                // degenerate (zero-area or collinear), so it must be reset first: a stale or+                // identity matrix would paint the bitmap unscaled at the canvas origin over+                // real content. A zero-area image is unpaintable per PDF 32000-1 8.9.5.2.+                imgMatrix.reset()+                if (!imgMatrix.setPolyToPoly(imgSrc, 0, imgDst, 0, 4)) continue                 imagePaint.setBlend(prim.blend)-                nativeCanvas.drawBitmap(bmp, mat, imagePaint)+                nativeCanvas.drawBitmap(bmp, imgMatrix, imagePaint)                 imagePaint.setBlend(BlendMode.Normal)                 imagePaint.alpha = 255             } +            is PdfPrimitive.ImageTiled -> {+                val bmp = prim.bitmap?.takeUnless { it.isRecycled } ?: continue+                val m = prim.ctm+                fun cellToCanvas(u: Float, v: Float): Offset {+                    val pageX = m[0] * u + m[2] * v + m[4]+                    val pageY = m[1] * u + m[3] * v + m[5]+                    return map(Offset(pageX, pageY))+                }+                val bw = bmp.width.toFloat()+                val bh = bmp.height.toFloat()+                // Same unit-square convention as Image: bitmap row 0 is the top, which is+                // v = 1 in PDF space. This matrix maps cell bitmap pixels to the canvas, and+                // TileMode.REPEAT then extends it along the bitmap's own axes — which under+                // this matrix are the pattern lattice's axes, so rotation and shear come free.+                imgSrc[0] = 0f; imgSrc[1] = 0f; imgSrc[2] = bw; imgSrc[3] = 0f+                imgSrc[4] = bw; imgSrc[5] = bh; imgSrc[6] = 0f; imgSrc[7] = bh+                val t00 = cellToCanvas(0f, 1f)+                val t10 = cellToCanvas(1f, 1f)+                val t11 = cellToCanvas(1f, 0f)+                val t01 = cellToCanvas(0f, 0f)+                imgDst[0] = t00.x; imgDst[1] = t00.y; imgDst[2] = t10.x; imgDst[3] = t10.y+                imgDst[4] = t11.x; imgDst[5] = t11.y; imgDst[6] = t01.x; imgDst[7] = t01.y+                imgMatrix.reset()+                if (!imgMatrix.setPolyToPoly(imgSrc, 0, imgDst, 0, 4)) continue+                if (prim.nx <= 0 || prim.ny <= 0) continue++                // The shader repeats without bound, so the lattice extent only decides the+                // region to cover. Under a rotated or sheared ctm that region is a+                // parallelogram, not a rect, so fill the mapped quad rather than its bounds.+                val u0 = prim.i0.toFloat()+                val v0 = prim.j0.toFloat()+                val u1 = u0 + prim.nx.toFloat()+                val v1 = v0 + prim.ny.toFloat()+                val r00 = cellToCanvas(u0, v0)+                val r10 = cellToCanvas(u1, v0)+                val r11 = cellToCanvas(u1, v1)+                val r01 = cellToCanvas(u0, v1)+                reusePath.reset()+                reusePath.moveTo(r00.x, r00.y)+                reusePath.lineTo(r10.x, r10.y)+                reusePath.lineTo(r11.x, r11.y)+                reusePath.lineTo(r01.x, r01.y)+                reusePath.close()++                val shader = runCatching {+                    android.graphics.BitmapShader(+                        bmp,+                        android.graphics.Shader.TileMode.REPEAT,+                        android.graphics.Shader.TileMode.REPEAT,+                    ).also { it.setLocalMatrix(imgMatrix) }+                }.onFailure {+                    android.util.Log.w("SafePdfViewer", "tiling pattern shader failed", it)+                }.getOrNull() ?: continue++                tilePaint.reset()+                tilePaint.isAntiAlias = true+                tilePaint.isFilterBitmap = true+                tilePaint.shader = shader+                tilePaint.alpha = (prim.alpha.coerceIn(0f, 1f) * 255).toInt()+                tilePaint.setBlend(prim.blend)+                nativeCanvas.drawPath(reusePath.asAndroidPath(), tilePaint)+                tilePaint.shader = null+            }+             is PdfPrimitive.ClipPush -> {                 // Save and apply clip; prefer the bezier-retentive path (v4) for                 // accurate curved clips, falling back to the flattened polyline.@@ -2937,10 +3080,11 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                     nativeCanvas.clipPath(cp)                 } else if (prim.points.size >= 3) {                     clipPath.reset()-                    val mapped = clipOffsetList(prim.points)-                    clipPath.moveTo(mapped[0].x, mapped[0].y)-                    for (i in 1 until mapped.size) {-                        clipPath.lineTo(mapped[i].x, mapped[i].y)+                    val p0 = map(prim.points[0])+                    clipPath.moveTo(p0.x, p0.y)+                    for (i in 1 until prim.points.size) {+                        val p = map(prim.points[i])+                        clipPath.lineTo(p.x, p.y)                     }                     clipPath.close()                     clipPath.fillType = if (prim.evenOdd) android.graphics.Path.FillType.EVEN_ODD else android.graphics.Path.FillType.WINDING@@ -2968,69 +3112,116 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {             }              is PdfPrimitive.GroupPush -> {-                // Transparency group with alpha + blend. Isolated groups are the-                // default with saveLayer (a fresh backdrop-free layer); knockout-                // groups are not directly expressible with Canvas layers and are-                // approximated as non-knockout.+                // Transparency group with alpha + blend, composited via an offscreen layer.+                //+                // KNOWN LIMITATION: neither /I (isolated) nor /K (knockout) is honoured.+                // Canvas.saveLayer always yields an isolated, non-knockout layer. A+                // non-isolated group would have to see the existing backdrop inside the+                // layer so its blend mode composites against it (PDF 32000-1 11.4.5), and a+                // knockout group needs each element composited against the group's initial+                // backdrop rather than the running result (11.4.6). Neither is expressible+                // with Canvas layers, so both are approximated as isolated non-knockout.                 val alpha = prim.alpha.coerceIn(0f,1f)                 val blend = prim.blend-                try {-                    val paint = android.graphics.Paint()-                    paint.alpha = (alpha*255).toInt()-                    if (blend != BlendMode.Normal) {-                        paint.blendMode = blend.toAndroid()-                    }-                    nativeCanvas.saveLayer(null, paint)-                    groupSaveCount++-                    // Also track in saveCount for balanced restore? Keep separate.-                } catch (t: Throwable) {-                    android.util.Log.w("SafePdfViewer", "GroupPush saveLayer failed", t)-                    nativeCanvas.save()-                    saveCount+++                val layered = if (groupSaveCount >= MAX_GROUP_LAYER_DEPTH) {+                    android.util.Log.w("SafePdfViewer", "group layer depth cap reached, drawing inline")+                    false+                } else {+                    runCatching {+                        groupPaint.reset()+                        groupPaint.alpha = (alpha*255).toInt()+                        if (blend != BlendMode.Normal) {+                            groupPaint.blendMode = blend.toAndroid()+                        }+                        nativeCanvas.saveLayer(null, groupPaint)+                    }.onFailure {+                        android.util.Log.w("SafePdfViewer", "GroupPush saveLayer failed", it)+                    }.isSuccess                 }+                // Account a level either way, so the matching GroupPop restores this push+                // and never a sibling clip's save.+                if (!layered) nativeCanvas.save()+                groupSaveCount++             }              is PdfPrimitive.GroupPop -> {                 if (groupSaveCount > 0) {                     nativeCanvas.restore()                     groupSaveCount---                } else if (saveCount >0) {-                    // fallback balanced if group tracking drifted-                    nativeCanvas.restore()-                    saveCount--                 }             }              is PdfPrimitive.SoftMaskPush -> {-                // Open the layer that will hold the masked content.-                nativeCanvas.saveLayer(null, null)-                softMaskStack.addLast(SoftMaskFrame(prim.maskType))+                // A soft-mask layer is an offscreen buffer, exactly like a transparency-group+                // layer, so it takes the same depth cap. Over the cap — or if the allocation+                // fails — fall back to a plain save so the matching pop still balances, and+                // record that the mask itself has to be discarded rather than painted.+                val frame = SoftMaskFrame(prim.maskType)+                val layered = softMaskStack.size < MAX_GROUP_LAYER_DEPTH &&+                    runCatching { nativeCanvas.saveLayer(null, null) }.onFailure {+                        android.util.Log.w("SafePdfViewer", "SoftMaskPush saveLayer failed", it)+                    }.isSuccess+                if (!layered) {+                    nativeCanvas.save()+                    frame.masked = false+                }+                frame.levels = 1+                softMaskStack.addLast(frame)+            }++            is PdfPrimitive.SoftMaskTransfer -> {+                // §11.6.5.2: the mask value passes through /TR. Folded into the matrix that+                // already turns the mask into alpha (see SoftMaskContent), so it is free.+                if (prim.affine) {+                    softMaskStack.lastOrNull()?.let { it.trGain = prim.gain; it.trBias = prim.bias }+                }             }              is PdfPrimitive.SoftMaskContent -> {                 val frame = softMaskStack.lastOrNull()-                if (frame != null) {+                if (frame != null && !frame.masked) {+                    // There is no content layer to mask into, so the mask primitives have+                    // nowhere to go. Clip them away — letting them paint would draw the mask+                    // itself on top of the page, which is worse than an unmasked group.+                    nativeCanvas.save()+                    nativeCanvas.clipRect(0f, 0f, 0f, 0f)+                    frame.levels+++                } else if (frame != null) {                     // The mask layer composites onto the content layer with                     // DST_IN, so the content is kept only where the mask has alpha.                     val maskPaint = android.graphics.Paint()                     maskPaint.blendMode = android.graphics.BlendMode.DST_IN                     nativeCanvas.saveLayer(null, maskPaint)-                    frame.maskLayers = 1-                    // Luminosity masks: convert the mask's luminance to alpha-                    // (RGB -> 0, A = Rec.709 luma) as the luma layer composites down.-                    if (frame.maskType == 1) {-                        val lumaPaint = android.graphics.Paint()-                        val lm = android.graphics.ColorMatrix(+                    frame.levels+++                    // Turn the mask into alpha as its layer composites down: Rec.709 luma for+                    // a luminosity mask, or the existing alpha, either way through /TR+                    // (gain·m + bias). An alpha mask with an identity /TR needs no layer.+                    val g = frame.trGain+                    val bias = frame.trBias * 255f+                    val lm = when {+                        frame.maskType == 1 -> android.graphics.ColorMatrix(+                            floatArrayOf(+                                0f, 0f, 0f, 0f, 0f,+                                0f, 0f, 0f, 0f, 0f,+                                0f, 0f, 0f, 0f, 0f,+                                g * 0.2126f, g * 0.7152f, g * 0.0722f, 0f, bias,+                            )+                        )+                        g != 1f || bias != 0f -> android.graphics.ColorMatrix(                             floatArrayOf(                                 0f, 0f, 0f, 0f, 0f,                                 0f, 0f, 0f, 0f, 0f,                                 0f, 0f, 0f, 0f, 0f,-                                0.2126f, 0.7152f, 0.0722f, 0f, 0f,+                                0f, 0f, 0f, g, bias,                             )                         )+                        else -> null+                    }+                    if (lm != null) {+                        val lumaPaint = android.graphics.Paint()                         lumaPaint.colorFilter = android.graphics.ColorMatrixColorFilter(lm)                         nativeCanvas.saveLayer(null, lumaPaint)-                        frame.maskLayers = 2+                        frame.levels++                     }                 }             }@@ -3038,18 +3229,17 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {             is PdfPrimitive.SoftMaskPop -> {                 val frame = softMaskStack.removeLastOrNull()                 if (frame != null) {-                    // Restore the mask (+luma) layers, then the content layer.-                    repeat(frame.maskLayers) { nativeCanvas.restore() }-                    nativeCanvas.restore()+                    repeat(frame.levels) { nativeCanvas.restore() }                 }             }         }     }-    // Ensure balanced restore+    // Ensure balanced restore. NOTE: this is the normal-path drain only — it does NOT run if a+    // primitive throws, so a caller must anchor on `nativeCanvas.saveCount` and+    // `restoreToCount` it in a finally. Both callers do: SafePdfPageCanvas and CutGlueScreen.     while (softMaskStack.isNotEmpty()) {         val frame = softMaskStack.removeLast()-        repeat(frame.maskLayers) { nativeCanvas.restore() }-        nativeCanvas.restore()+        repeat(frame.levels) { nativeCanvas.restore() }     }     while (groupSaveCount > 0) {         nativeCanvas.restore()@@ -3061,18 +3251,6 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {     } } -private inline fun List<Offset>.toPath(map: (Offset) -> Offset): Path? {-    if (size < 2) return null-    val path = Path()-    val first = map(this[0])-    path.moveTo(first.x, first.y)-    for (i in 1 until size) {-        val p = map(this[i])-        path.lineTo(p.x, p.y)-    }-    return path-}- private class JpegImage(val bytes: ByteArray, val width: Int, val height: Int)  /** Read [uri] and re-encode it as JPEG for a stamp; null on failure. */
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 29bfe9f6f6..1a6386ae31 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -19,27 +19,51 @@ class SafePdfDocument private constructor(     private val handle: Long,     val pageCount: Int, ) {-    // Bounded LRU to avoid OOM; P0 fix #2 critical: cachedPixels budget drift on auto-eviction-    private var cachedPixels: Long = 0L+    // Bounded LRU to avoid OOM. Accounted in BYTES via [pageWeightBytes] — see the note on+    // [MAX_CACHED_BYTES] for why counting only bitmap pixels was blind to the pages that+    // actually cause the OOM. Every add/subtract goes through the one helper, because the+    // original budget-drift bug came from four hand-duplicated copies of the arithmetic.+    private var cachedBytes: Long = 0L+    /**+     * Every page dimension ever decoded, keyed by page index. Deliberately NOT evicted with+     * [cache]: it is two floats per page, and the placeholder shown before a page is decoded+     * needs its true aspect ratio. Sizing an undecoded page as letter-portrait and then+     * resizing it once the real dimensions arrive changes the item's height mid-scroll, which+     * moves everything below it — very visible in a document with a landscape insert, or when+     * scrolling back to a page the LRU has dropped.+     */+    private val pageSizes = java.util.concurrent.ConcurrentHashMap<Int, FloatArray>()++    // Evicting a page must NOT recycle its bitmaps: the same SafePdfPage instance is+    // still referenced by whatever composable is drawing it, and Canvas.drawBitmap+    // throws "Cannot draw recycled bitmaps" from the draw phase. Dropping the last+    // reference is enough — the GC reclaims the pixels.     private val cache: MutableMap<Int, SafePdfPage> = object : LinkedHashMap<Int, SafePdfPage>(16, 0.75f, true) {         override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Int, SafePdfPage>?): Boolean {             if (size <= MAX_CACHED_PAGES) return false-            // P0 fix #2 critical: previously recycled eldest bitmap but never subtracted cachedPixels, permanent drift-            eldest?.value?.let { page ->-                page.primitives.forEach { prim ->-                    if (prim is PdfPrimitive.Image) {-                        val b = prim.bitmap-                        if (b != null) {-                            cachedPixels = (cachedPixels - b.width.toLong() * b.height.toLong()).coerceAtLeast(0L)-                        }-                        runCatching { prim.bitmap?.recycle() }-                    }-                }-            }+            eldest?.value?.let { cachedBytes = (cachedBytes - pageWeightBytes(it)).coerceAtLeast(0L) }             return true         }     } +    /**+     * Rough retained size of [page] in bytes. Decoded bitmaps are exact (ARGB_8888, four bytes+     * per pixel); everything else is charged a flat [PRIMITIVE_WEIGHT_BYTES] estimate, which is+     * deliberately an order-of-magnitude figure rather than a measurement — the point is to+     * bound the primitive COUNT, not to predict the heap precisely.+     */+    private fun pageWeightBytes(page: SafePdfPage): Long {+        var bytes = 0L+        for (prim in page.primitives) {+            bytes += PRIMITIVE_WEIGHT_BYTES+            if (prim is PdfPrimitive.Image) {+                val b = prim.bitmap+                if (b != null) bytes += b.width.toLong() * b.height.toLong() * 4L+            }+        }+        return bytes+    }+     /** Decode page [index] (0-based), or `null` if the native render fails. */     suspend fun renderPage(index: Int): SafePdfPage? = withContext(Dispatchers.IO) {         synchronized(cache) { cache[index] }?.let { return@withContext it }@@ -47,27 +71,26 @@ class SafePdfDocument private constructor(         // side throws a RuntimeException on an uncaught panic (see the         // catch_unwind boundary in jni_bindings.rs), and a corrupt wire buffer         // could throw during parse. Degrade either to a skipped (null) page.-        val bytes = runCatching { PdfNative.renderPage(handle, index) }.getOrNull()-            ?: return@withContext null-        val page = runCatching { SafePdfParser.parse(bytes) }.getOrNull()+        val bytes = runCatching { PdfNative.renderPage(handle, index) }+            .onFailure { android.util.Log.w(TAG, "native renderPage threw for page $index", it) }+            .getOrNull()+        if (bytes == null) {+            android.util.Log.w(TAG, "native renderPage returned no data for page $index")+            return@withContext null+        }+        val page = runCatching { SafePdfParser.parse(bytes) }+            .onFailure {+                android.util.Log.w(TAG, "wire parse failed for page $index (${bytes.size} bytes)", it)+            }+            .getOrNull()             ?: return@withContext null+        pageSizes[index] = floatArrayOf(page.width, page.height)         synchronized(cache) {-            // Budget-based eviction in addition to count-based-            var pixels = page.primitives.sumOf { prim ->-                if (prim is PdfPrimitive.Image) {-                    prim.bitmap?.let { it.width.toLong() * it.height.toLong() } ?: 0L-                } else 0L-            }-            cachedPixels += pixels-            while (cachedPixels > MAX_CACHED_PIXELS && cache.isNotEmpty()) {+            cachedBytes += pageWeightBytes(page)+            while (cachedBytes > MAX_CACHED_BYTES && cache.isNotEmpty()) {                 val eldest = cache.entries.iterator().next()                 cache.remove(eldest.key)?.let { evicted ->-                    evicted.primitives.forEach { p ->-                        if (p is PdfPrimitive.Image) {-                            cachedPixels -= p.bitmap?.let { b -> b.width.toLong() * b.height.toLong() } ?: 0L-                            runCatching { p.bitmap?.recycle() }-                        }-                    }+                    cachedBytes = (cachedBytes - pageWeightBytes(evicted)).coerceAtLeast(0L)                 }             }             cache[index] = page@@ -75,29 +98,26 @@ class SafePdfDocument private constructor(         page     } +    /**+     * Width/height ratio of page [index] if it has been decoded at least once, else `null`.+     * Lets the viewer lay out a not-yet-decoded page at its real height instead of guessing.+     */+    fun knownAspectRatio(index: Int): Float? =+        pageSizes[index]?.takeIf { it[0] > 0f && it[1] > 0f }?.let { it[0] / it[1] }+     /** Release native resources. Idempotent-safe to call once. */     fun close() {         synchronized(cache) {-            cache.values.forEach { page ->-                page.primitives.forEach { prim ->-                    if (prim is PdfPrimitive.Image) runCatching { prim.bitmap?.recycle() }-                }-            }             cache.clear()-            cachedPixels = 0L+            cachedBytes = 0L         }         PdfNative.closeDocument(handle)     }      private fun invalidate(index: Int) {         synchronized(cache) {-            cache.remove(index)?.let { page ->-                page.primitives.forEach { prim ->-                    if (prim is PdfPrimitive.Image) {-                        cachedPixels -= prim.bitmap?.let { b -> b.width.toLong() * b.height.toLong() } ?: 0L-                        runCatching { prim.bitmap?.recycle() }-                    }-                }+            cache.remove(index)?.let {+                cachedBytes = (cachedBytes - pageWeightBytes(it)).coerceAtLeast(0L)             }         }     }@@ -240,12 +260,12 @@ class SafePdfDocument private constructor(      /** Serialize with streams compressed + unused objects pruned - wrapper for saveCompressed native */     suspend fun saveCompressed(): ByteArray? = withContext(Dispatchers.IO) {-        PdfNative.saveCompressed(handle).also { synchronized(cache) { cache.clear(); cachedPixels = 0L } }+        PdfNative.saveCompressed(handle).also { synchronized(cache) { cache.clear(); cachedBytes = 0L } }     }      /** Flatten annotations into page content - wrapper for flattenDocument native */     suspend fun flattenDocument(): Boolean = withContext(Dispatchers.IO) {-        PdfNative.flattenDocument(handle).also { synchronized(cache) { cache.clear(); cachedPixels = 0L } }+        PdfNative.flattenDocument(handle).also { synchronized(cache) { cache.clear(); cachedBytes = 0L } }     }      /** Extract page [index] into standalone one-page PDF bytes */@@ -267,7 +287,7 @@ class SafePdfDocument private constructor(      /** Permanently remove content under redaction annotations. */     suspend fun applyRedactions(): Boolean = withContext(Dispatchers.IO) {-        PdfNative.applyRedactions(handle).also { synchronized(cache) { cache.clear(); cachedPixels = 0L } }+        PdfNative.applyRedactions(handle).also { synchronized(cache) { cache.clear(); cachedBytes = 0L } }     }      /** Whether any redaction annotations exist (to show the Apply-redactions action). */@@ -304,8 +324,32 @@ class SafePdfDocument private constructor(         withContext(Dispatchers.IO) { PdfNative.saveEncrypted(handle, userPw, ownerPw) }      companion object {+        private const val TAG = "SafePdfDocument"         private const val MAX_CACHED_PAGES = 12-        private const val MAX_CACHED_PIXELS = 64 * 1024 * 1024L // ~64 MP aggregate budget+        /**+         * Rough per-primitive retained cost, in bytes. `FillPath` holds `List<List<Offset>>`+         * and `Offset` boxes inside a List, so a four-point fill is already ~176 bytes once+         * the object, both lists and the boxed points are counted; a short `Text` is similar.+         * An order-of-magnitude estimate, not a measurement.+         */+        private const val PRIMITIVE_WEIGHT_BYTES = 128L+        /**+         * Aggregate retained budget for [cache], in BYTES.+         *+         * This used to count only decoded-bitmap PIXELS, which was blind in both directions.+         * Bitmaps are four bytes per pixel, so a nominal "64 MP" cap actually permitted ~256 MB+         * — more than the whole heap on most devices, so it never fired. Worse, a vector page+         * contributed ZERO, so a document of dense drawings could hold twelve 300k-primitive+         * pages (~450 MB of Kotlin objects) with the budget reading zero and+         * [MAX_CACHED_PAGES] as the only bound. That is the more likely OOM of the two, and it+         * got three times worse when `MAX_CONTENT_OPS` was raised, making Rust's 300k+         * `MAX_PRIMITIVES` reachable where a page previously topped out near 100k.+         *+         * Evicting a page that is currently on screen is harmless: the composable holds its own+         * reference to the decoded page and `produceState` does not re-run, so eviction costs at+         * most a re-render if that page is requested again. The budget can therefore be tight.+         */+        private const val MAX_CACHED_BYTES = 96L * 1024 * 1024         /**          * Open [uri] as a safe PDF, or return `null` when the native lib is          * unavailable, the bytes can't be read, or parsing fails. Encrypted PDFs
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 fc254dfccc..c3574f7458 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt@@ -86,6 +86,40 @@ sealed interface PdfPrimitive {         val bitmap: android.graphics.Bitmap?,         val alpha: Float = 1f,         val blend: BlendMode = BlendMode.Normal,+        /**+         * Whether to smooth the image when it is scaled up (wire v11). PDF 32000-1 §8.9.5.1+         * Table 89: `/Interpolate` defaults to **false**, and bilevel art must never be+         * smoothed — Rust decides this per image in `image_should_interpolate`. Defaults to+         * true so an older wire behaves exactly as before the flag existed.+         */+        val interpolate: Boolean = true,+    ) : PdfPrimitive++    /**+     * A tiling pattern drawn as ONE repeating cell rather than one [Image] per tile (wire+     * tag 14). [ctm] maps the unit square onto one cell — one period of the lattice — so the+     * bitmap's own dimensions ARE the repeat period; Rust rasterizes the cell at `/XStep` x+     * `/YStep`, not at the pattern `/BBox`, with transparent padding where the step is larger.+     * [xstep]/[ystep] are carried only so the renderer can assert that correspondence.+     *+     * [i0]/[j0]/[nx]/[ny] are the lattice extent in cell indices relative to [ctm]'s origin.+     * A `REPEAT` shader tiles infinitely, so these only determine the region to fill.+     *+     * Only emitted for NON-overlapping patterns: PDF 32000-1 §8.7.3.1 permits `/XStep` smaller+     * than the BBox with later tiles painted over earlier, and a periodic repeat cannot express+     * overlap, so Rust routes that case to the per-tile path instead.+     */+    data class ImageTiled(+        val ctm: FloatArray,+        val bitmap: android.graphics.Bitmap?,+        val xstep: Float,+        val ystep: Float,+        val i0: Int,+        val j0: Int,+        val nx: Int,+        val ny: Int,+        val alpha: Float = 1f,+        val blend: BlendMode = BlendMode.Normal,     ) : PdfPrimitive      /**@@ -131,6 +165,19 @@ sealed interface PdfPrimitive {     /** Marker: switch from drawing the masked content to drawing the mask (v5). */     data object SoftMaskContent : PdfPrimitive +    /**+     * The /TR transfer function of the enclosing [SoftMaskPush] (wire tag 13), reduced to+     * `gain * m + bias` over the mask value m in 0..1. [affine] is false when the transmitted+     * 256-entry LUT is too far from a straight line for that form to represent it, in which+     * case the mask is left untransformed — see [SafePdfParser] for why an affine fit is the+     * only shape that can be applied to a Canvas layer.+     */+    data class SoftMaskTransfer(+        val gain: Float,+        val bias: Float,+        val affine: Boolean,+    ) : PdfPrimitive+     /** End a soft-masked region: composite the mask onto the content (v5). */     data object SoftMaskPop : 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 b36c6a85ad..c4b48baca7 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -8,16 +8,17 @@ import java.nio.ByteOrder  * Decodes the compact little-endian primitive buffer produced by the native  * renderer ([PdfNative.renderPage]) into a [SafePdfPage].  *- * Wire format v9 (must stay in sync with `pdf/rust/src/wire.rs`):+ * Wire format v11 (must stay in sync with `pdf/src/main/rust/src/wire.rs`):  * ```- * header: u32 MAGIC=0x50444657, u32 VERSION=9, f32 pageWidth, f32 pageHeight, u32 primitiveCount+ * header: u32 MAGIC=0x50444657, u32 VERSION (11 is the newest understood; Rust emits 10),+ *         f32 pageWidth, f32 pageHeight, u32 primitiveCount  *  Legacy v1 fallback: header is f32 W,H,u32 count (no magic)- *  v2..v9 fallbacks: same layout with fewer trailing fields for older cached pages+ *  v2..v10 fallbacks: same layout with fewer trailing fields for older cached pages  * per primitive: u8 tag, then payload  *   1 Text:   f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8 bytes], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5), f32 advance (v7), u8 fontFlags (v8 bold italic), f32 hScale (v8)  *   2 Fill:   u32 argb, u8 evenOdd, u16 nContours, [u16 nPts, [f32 x,y]...]... (v6), u8 blend (v5)  *   3 Stroke: u32 argb, f32 width, u8 nDash, [f32 dash]..., f32 phase, u8 cap, u8 join, f32 miter, u16 nPts, [f32 x, y]..., u8 blend (v5)- *   4 Image:  6*f32 ctm, u32 w, u32 h, u8 format, f32 alpha (v9), u8 blend (v10), u32 len, [bytes]+ *   4 Image:  6*f32 ctm, u32 w, u32 h, u8 format, f32 alpha (v9), u8 blend (v10), u8 interpolate (v11), u32 len, [bytes]  *   5 ClipPush: u8 evenOdd, u16 nPts, [f32 x,y]..., u16 nPathOps, [...] (v4)  *   6 ClipPop: empty  *   7 GroupPush: u8 isolated, u8 knockout, f32 alpha, u8 blend@@ -26,11 +27,28 @@ import java.nio.ByteOrder  *   10 SoftMaskPush: u8 maskType (0 alpha, 1 lum) (v5)  *   11 SoftMaskContent: empty (v5)  *   12 SoftMaskPop: empty (v5)+ *   13 SoftMaskTransfer: 256 * u8 LUT over the mask value (v11) — the /TR of the immediately+ *      preceding SoftMaskPush. Handled regardless of the declared wire version, so Rust may+ *      start emitting it without a version bump and an older stream that never contains it is+ *      unaffected.+ *   14 ImageTiled: 6*f32 ctm, u32 w, u32 h, f32 xstep, f32 ystep, i32 i0, i32 j0, u32 nx,+ *      u32 ny, f32 alpha, u8 blend, u32 len, [RGBA8888 bytes] — one repeating cell for a+ *      tiling pattern. No format byte; the payload is always raw RGBA8888. Tag-gated, so an+ *      absent emitter is a no-op.  * ```- * Pure function -> unit-testable. Guards via MAX_PRIMITIVES avoid OOM. v9 adds per-image alpha.+ * Pure function -> unit-testable. v9 adds per-image alpha, v10 per-image blend mode, v11 the+ * per-image /Interpolate flag. Rust still declares v10 until it writes that byte, at which+ * point the two must be bumped together — see the note on WIRE_VERSION in wire.rs.+ *+ * Robustness contract: a single malformed or over-sized primitive must never discard the+ * page. [parse] returns whatever decoded cleanly, because the caller+ * ([SafePdfDocument.renderPage]) can only turn a thrown exception into a null page, which+ * the UI shows as an indefinite loading spinner.  */ object SafePdfParser { +    private const val TAG = "SafePdfParser"+     private const val TAG_TEXT = 1     private const val TAG_FILL = 2     private const val TAG_STROKE = 3@@ -43,6 +61,8 @@ object SafePdfParser {     private const val TAG_SMASK_PUSH = 10     private const val TAG_SMASK_CONTENT = 11     private const val TAG_SMASK_POP = 12+    private const val TAG_SMASK_TRANSFER = 13+    private const val TAG_IMAGE_TILED = 14      private const val PATHOP_MOVE = 0     private const val PATHOP_LINE = 1@@ -50,7 +70,19 @@ object SafePdfParser {     private const val PATHOP_CLOSE = 3      const val WIRE_MAGIC: Int = 0x50444657 // 'PDFW' little-endian as u32-    const val WIRE_VERSION: Int = 10+    /**+     * Highest wire version this parser understands — NOT the version the producer emits.+     * `WIRE_VERSION` in `pdf/src/main/rust/src/wire.rs` is the emitted one and currently+     * declares 10; it may lag this constant, because every field newer than what it+     * declares stays gated off below, but it must never exceed it. A higher version is not+     * rejected here — [parse] warns and carries on with those gates closed, so it reads too+     * few bytes per primitive and desyncs the rest of the buffer.+     *+     * Rust's `wire::tests::wire_version_is_not_ahead_of_the_kotlin_parser` reads these two+     * declarations straight out of this file to assert that, so keep each of them on one+     * line in exactly the form `const val WIRE_VERSION: Int = <n>` / `= 0x<hex>`.+     */+    const val WIRE_VERSION: Int = 11     private const val WIRE_VERSION_V2 = 2     private const val WIRE_VERSION_V4 = 4     private const val WIRE_VERSION_V5 = 5@@ -59,9 +91,104 @@ object SafePdfParser {     private const val WIRE_VERSION_V8 = 8     private const val WIRE_VERSION_V9 = 9     private const val WIRE_VERSION_V10 = 10-    const val MAX_PRIMITIVES = 50000+    private const val WIRE_VERSION_V11 = 11+    /**+     * Upper bound on primitives decoded from one page — a BACKSTOP against a corrupt count+     * field, not a truncation policy. Over the bound we clamp and render a partial page,+     * never throw, because a throw here discards the whole page.+     *+     * It must sit comfortably ABOVE Rust's own ceiling, which is what actually bounds the+     * stream. Rust enforces `MAX_PRIMITIVES = 300000` (graphics_state.rs:166) at every+     * content-emitting push — guards at ~57 sites across interpret.rs, draw.rs and+     * annotations.rs, plus a hard `prims.truncate` in draw.rs.+     *+     * DO NOT LOWER THIS TO MATCH 300000. The guards protect content-emitting pushes, but the+     * bracket BOOKKEEPING around them is emitted for structural correctness whether or not the+     * cap has been reached — dropping a `ClipPop` would leave its clip un-restored and blank+     * the rest of the page, so several of those pushes and pops are deliberately unguarded+     * (e.g. interpret.rs:247, :1145-1148, :1555). The emitted count can therefore exceed+     * 300000, and a clamp set to exactly 300000 would cut exactly that bookkeeping.+     *+     * The excess is NOT limited to closers. `exceeding_the_primitive_cap_keeps_the_bracket_+     * structure_intact` measures three shapes: overshoot 1 at one fill per tile, 2 at forty+     * fills per tile, and 6 for a form XObject crossing the cap mid-operator, where the excess+     * is ["ClipPop", "ClipPop", "ClipPush", "ClipPop", "ClipPop", "ClipPop"] — a `Do` still+     * pushes its mandatory `/BBox` clip (§8.10.2) and pops it again even though it emits no+     * content. So it is bracket bookkeeping, pushes included, not bracket closers.+     *+     * No tight upper bound on the overshoot has been established, and two attempts to derive+     * one from bracket depth were wrong. Do not replace this constant with a formula: it is a+     * backstop against a corrupt count field, so the correct posture is generous headroom+     * (~700k here) rather than a bound we would have to keep re-proving.+     *+     * NOTE: this clamp is not the tightest bound anywhere. `MAX_CONTENT_OPS`+     * (graphics_state.rs:250, applied at interpret.rs:274 as `ops.iter().take(..)`) was raised+     * from 200000 to 1000000 once it was established that `ops` is a fully-materialised Vec, so+     * `take` frees no memory and the constant was a time guard being used as a memory guard.+     * Rust's `MAX_PRIMITIVES = 300000` is now the binding producer bound. Covered executably by+     * `golden_tests::content_beyond_the_caps_truncates_to_a_valid_page`, which derives its+     * content size from whichever cap is smaller rather than hard-coding one.+     */+    const val MAX_PRIMITIVES = 1_000_000     const val MAX_ANNOTATIONS = 10000 +    /** A /TR transfer function is transmitted as this many u8 samples over the mask value. */+    private const val TRANSFER_LUT_SIZE = 256+    /**+     * Cap on a tiling pattern's lattice extent per axis. The extent only decides how large a+     * region the REPEAT shader is asked to cover, so a big count is not itself expensive, but+     * an absurd one would push the region path's coordinates past what Skia can represent.+     */+    private const val MAX_LATTICE_CELLS = 100_000+    /**+     * Largest deviation from a straight line, in 8-bit mask levels, still treated as affine.+     * Three levels is below the visible threshold for a mask edge.+     */+    private const val TRANSFER_FIT_TOLERANCE = 3f / 255f++    /**+     * Reduce a /TR LUT to `gain * m + bias` by least squares, marking the result non-affine+     * when the fit is worse than [TRANSFER_FIT_TOLERANCE].+     *+     * PDF 32000-1 §11.6.5.2 requires the mask value to pass through /TR, and an inverting /TR+     * is the standard idiom for "mask out where the group is bright" — so ignoring it hides+     * exactly the wrong half. A soft mask is drawn into a `Canvas.saveLayer`, and the only+     * per-pixel transform available on that composite is a `ColorMatrixColorFilter`, which is+     * affine. Inverting and gain/bias curves fit exactly and so are applied exactly. A+     * genuinely non-linear /TR (gamma, threshold, sampled type-0) cannot be: Android has no+     * LUT colour filter, a saveLayer has no readable pixel buffer to run a table over, and+     * `RuntimeShader`/AGSL cannot act as the filter on a saveLayer composite. Running the+     * table per pixel per frame is not viable either, since drawSafePage re-runs on every+     * frame at every zoom level. Those are reported as non-affine and left untransformed+     * rather than approximated, because a wrong curve hides the wrong half of the group —+     * the exact fault this exists to fix. KNOWN LIMITATION.+     */+    private fun fitTransferLut(lut: ByteArray): PdfPrimitive.SoftMaskTransfer {+        val n = lut.size+        var sx = 0.0; var sy = 0.0; var sxx = 0.0; var sxy = 0.0+        for (i in 0 until n) {+            val x = i / (n - 1).toDouble()+            val y = (lut[i].toInt() and 0xFF) / 255.0+            sx += x; sy += y; sxx += x * x; sxy += x * y+        }+        val denom = n * sxx - sx * sx+        // Degenerate only if every sample x is identical, which cannot happen for n > 1.+        val gain = if (denom != 0.0) (n * sxy - sx * sy) / denom else 0.0+        val bias = (sy - gain * sx) / n+        var maxErr = 0.0+        for (i in 0 until n) {+            val x = i / (n - 1).toDouble()+            val y = (lut[i].toInt() and 0xFF) / 255.0+            val e = kotlin.math.abs(gain * x + bias - y)+            if (e > maxErr) maxErr = e+        }+        val affine = maxErr <= TRANSFER_FIT_TOLERANCE+        if (!affine) {+            android.util.Log.w(TAG, "soft-mask /TR is not affine (max err $maxErr), leaving mask untransformed")+        }+        return PdfPrimitive.SoftMaskTransfer(gain.toFloat(), bias.toFloat(), affine)+    }+     fun parse(bytes: ByteArray): SafePdfPage {         val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)         if (buf.remaining() < 12) throw IllegalArgumentException("Buffer too small")@@ -73,7 +200,7 @@ object SafePdfParser {         val countRaw: Int          if (firstInt == WIRE_MAGIC) {-            if (buf.remaining() < 12) throw IllegalArgumentException("v2/v3 header truncated")+            if (buf.remaining() < 16) throw IllegalArgumentException("v2/v3 header truncated")             wireVersion = buf.int             width = buf.float             height = buf.float@@ -90,8 +217,12 @@ object SafePdfParser {         if (width <= 0f || height <= 0f || width > 20000f || height > 20000f) {             throw IllegalArgumentException("Invalid page dimensions $width x $height")         }-        if (countRaw < 0 || countRaw > MAX_PRIMITIVES) {-            throw IllegalArgumentException("Primitive count out of bounds: $countRaw")+        if (countRaw < 0) {+            throw IllegalArgumentException("Negative primitive count: $countRaw")+        }+        val count = countRaw.coerceAtMost(MAX_PRIMITIVES)+        if (count < countRaw) {+            android.util.Log.w(TAG, "primitive count $countRaw exceeds $MAX_PRIMITIVES, rendering the first $count")         }          val isV2OrV3 = wireVersion >= WIRE_VERSION_V2@@ -102,6 +233,7 @@ object SafePdfParser {         val isV8 = wireVersion >= WIRE_VERSION_V8         val isV9 = wireVersion >= WIRE_VERSION_V9         val isV10 = wireVersion >= WIRE_VERSION_V10+        val isV11 = wireVersion >= WIRE_VERSION_V11         // Accept v1 (legacy), v2, v3 and v4. Newer versions are tolerated via         // forward-compat parsing as long as the tags are known.         if (wireVersion !in 1..WIRE_VERSION) {@@ -112,9 +244,14 @@ object SafePdfParser {             }         } -        val primitives = ArrayList<PdfPrimitive>(countRaw.coerceAtLeast(0))-        repeat(countRaw) {-            if (!buf.hasRemaining()) return@repeat+        val primitives = ArrayList<PdfPrimitive>(count.coerceAtMost(4096))+        // Depth of the soft-mask bracket currently open, and the index at which the+        // outermost still-unterminated one began, so a page cut short can be trimmed back+        // to a well-formed boundary instead of left with a half-applied mask.+        var softMaskDepth = 0+        var outermostSoftMaskStart = -1+        for (primIndex in 0 until count) {+            if (!buf.hasRemaining()) break             when (val tag = buf.get().toInt() and 0xFF) {                 TAG_TEXT -> {                     val x = buf.float@@ -122,7 +259,9 @@ object SafePdfParser {                     val size = buf.float                     val argb = buf.int                     val len = buf.short.toInt() and 0xFFFF-                    if (len < 0 || len > 4096) throw IllegalArgumentException("Text length out of bounds $len")+                    // No upper-bound rejection: len is u16-bounded and Rust truncates at+                    // MAX_TEXT_BYTES (65535), so anything up to that is legitimate. The old+                    // 4096 cap threw and destroyed the entire page over one long run.                     if (buf.remaining() < len) throw IllegalArgumentException("Text length truncated")                     val strBytes = ByteArray(len)                     buf.get(strBytes)@@ -208,7 +347,6 @@ object SafePdfParser {                     val evenOdd = buf.get().toInt() != 0                     val contours = if (isV6) {                         val n = buf.short.toInt() and 0xFFFF-                        if (n > MAX_PRIMITIVES) throw IllegalArgumentException("Fill contour count out of bounds $n")                         (0 until n).map { readPoints(buf) }                     } else {                         // v5 and earlier: a single polygon per fill.@@ -224,8 +362,10 @@ 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.                     val nDash = buf.get().toInt() and 0xFF-                    if (nDash < 0 || nDash > 32) throw IllegalArgumentException("Dash count out of bounds $nDash")                     if (buf.remaining() < nDash*4+4) throw IllegalArgumentException("Stroke dash truncated")                     val dash = FloatArray(nDash) { buf.float }                     val dashPhase = buf.float@@ -254,25 +394,24 @@ object SafePdfParser {                     val ctm = FloatArray(6) { buf.float }                     val w = buf.int                     val h = buf.int-                    if (w <= 0 || h <= 0 || w > 20000 || h > 20000) {-                        if (buf.remaining() >= 5) {-                            buf.get() // fmt-                            if (isV9 && buf.remaining() >= 4) buf.float // alpha v9-                            if (isV10 && buf.remaining() >= 1) buf.get() // blend v10-                            val len = buf.int-                            if (len >=0 && buf.remaining() >= len) buf.position(buf.position()+len)-                        }-                        return@repeat-                    }-                    if (w.toLong()*h.toLong() > 16*1024*1024) {-                        if (buf.remaining() >= 5) {-                            buf.get()-                            if (isV9 && buf.remaining() >= 4) buf.float-                            if (isV10 && buf.remaining() >= 1) buf.get()-                            val len = buf.int-                            if (len >=0 && buf.remaining() >= len) buf.position(buf.position()+len)-                        }-                        return@repeat+                    if (w <= 0 || h <= 0 || w > 20000 || h > 20000 ||+                        w.toLong() * h.toLong() > 16 * 1024 * 1024+                    ) {+                        // Unusable dimensions: consume this payload EXACTLY so the stream+                        // stays in sync, then drop the primitive. If it cannot be skipped+                        // cleanly the buffer is untrustworthy, so stop rather than decode+                        // garbage from a desynced offset.+                        val fixed = 1 + (if (isV9) 4 else 0) + (if (isV10) 1 else 0) ++                            (if (isV11) 1 else 0) + 4+                        if (buf.remaining() < fixed) break+                        buf.get() // format+                        if (isV9) buf.float // alpha+                        if (isV10) buf.get() // blend+                        if (isV11) buf.get() // interpolate+                        val skipLen = buf.int+                        if (skipLen < 0 || buf.remaining() < skipLen) break+                        buf.position(buf.position() + skipLen)+                        continue                     }                     val format = buf.get().toInt()                     val imgAlpha = if (isV9) {@@ -283,23 +422,32 @@ object SafePdfParser {                         if (buf.remaining() < 1) throw IllegalArgumentException("Image v10 blend truncated")                         BlendMode.fromCode(buf.get().toInt() and 0xFF)                     } else BlendMode.Normal+                    // v11: PDF 32000-1 §8.9.5.1 Table 89 — /Interpolate defaults to false and+                    // bilevel art must never be smoothed. Rust decides per image; an older+                    // wire has no opinion, so default to smoothing as before.+                    val imgInterpolate = if (isV11) {+                        if (buf.remaining() < 1) throw IllegalArgumentException("Image v11 interpolate truncated")+                        buf.get().toInt() != 0+                    } else true                     val len = buf.int                     if (len < 0 || len > 16*1024*1024) throw IllegalArgumentException("Image data length out of bounds $len")                     if (buf.remaining() < len) throw IllegalArgumentException("Image data truncated")                     val data = ByteArray(len)                     buf.get(data)                     val bmp = decodeBitmap(w, h, format, data)-                    primitives.add(PdfPrimitive.Image(ctm, bmp, imgAlpha, imgBlend))+                    primitives.add(PdfPrimitive.Image(ctm, bmp, imgAlpha, imgBlend, imgInterpolate))                 }                  TAG_CLIP_PUSH -> {                     val evenOdd = buf.get().toInt() != 0                     val pts = readPoints(buf)                     val pathOps = if (isV4) readPathOps(buf) else null-                    // Degenerate clip guard (shoelace <1e-3 or <3 pts) already enforced in Rust, but double-guard in Kotlin saveCount restore.-                    if (pts.size >= 3 || (pathOps != null && pathOps.isNotEmpty())) {-                        primitives.add(PdfPrimitive.ClipPush(evenOdd, pts, pathOps))-                    }+                    // Always emit, even when the geometry is degenerate. Rust increments its+                    // clip depth for such a push and so still sends the matching ClipPop;+                    // dropping the push here left that pop unmatched, and it then released an+                    // ENCLOSING clip early — content bleeding outside its box. drawSafePage+                    // already handles a degenerate push by saving without narrowing the clip.+                    primitives.add(PdfPrimitive.ClipPush(evenOdd, pts, pathOps))                 }                  TAG_CLIP_POP -> {@@ -311,7 +459,7 @@ object SafePdfParser {                 }                  TAG_GROUP_PUSH -> {-                    if (buf.remaining() < 6) throw IllegalArgumentException("GroupPush truncated")+                    if (buf.remaining() < 7) throw IllegalArgumentException("GroupPush truncated")                     val isolated = buf.get().toInt() != 0                     val knockout = buf.get().toInt() != 0                     val alpha = buf.float.coerceIn(0f,1f)@@ -326,6 +474,8 @@ object SafePdfParser {                 TAG_SMASK_PUSH -> {                     if (buf.remaining() < 1) throw IllegalArgumentException("SoftMaskPush truncated")                     val maskType = buf.get().toInt() and 0xFF+                    if (softMaskDepth == 0) outermostSoftMaskStart = primitives.size+                    softMaskDepth++                     primitives.add(PdfPrimitive.SoftMaskPush(maskType))                 } @@ -335,16 +485,83 @@ object SafePdfParser {                  TAG_SMASK_POP -> {                     primitives.add(PdfPrimitive.SoftMaskPop)+                    if (softMaskDepth > 0) softMaskDepth--+                }++                TAG_SMASK_TRANSFER -> {+                    // Consistent with the robustness contract above: a truncated tail means+                    // the buffer ended, so keep the prefix that decoded rather than throwing+                    // and losing the whole page over the last primitive.+                    if (buf.remaining() < TRANSFER_LUT_SIZE) {+                        android.util.Log.w(TAG, "SoftMaskTransfer truncated, truncating page")+                        break+                    }+                    val lut = ByteArray(TRANSFER_LUT_SIZE)+                    buf.get(lut)+                    primitives.add(fitTransferLut(lut))+                }++                TAG_IMAGE_TILED -> {+                    val ctm = FloatArray(6) { buf.float }+                    val w = buf.int+                    val h = buf.int+                    val xstep = buf.float+                    val ystep = buf.float+                    val i0 = buf.int+                    val j0 = buf.int+                    val nxRaw = buf.int+                    val nyRaw = buf.int+                    if (buf.remaining() < 5) throw IllegalArgumentException("ImageTiled truncated")+                    val tileAlpha = buf.float.coerceIn(0f, 1f)+                    val tileBlend = BlendMode.fromCode(buf.get().toInt() and 0xFF)+                    val len = buf.int+                    if (len < 0 || len > 16*1024*1024) throw IllegalArgumentException("ImageTiled data length out of bounds $len")+                    if (buf.remaining() < len) throw IllegalArgumentException("ImageTiled data truncated")+                    val data = ByteArray(len)+                    buf.get(data)+                    // Format 0: the cell is always raw RGBA8888, so there is no format byte.+                    val bmp = decodeBitmap(w, h, 0, data)+                    // The lattice extent only sizes the filled region — a REPEAT shader tiles+                    // infinitely — so an absurd count costs nothing to draw, but clamp it so it+                    // cannot produce non-finite path coordinates.+                    val nx = nxRaw.coerceIn(0, MAX_LATTICE_CELLS)+                    val ny = nyRaw.coerceIn(0, MAX_LATTICE_CELLS)+                    primitives.add(+                        PdfPrimitive.ImageTiled(ctm, bmp, xstep, ystep, i0, j0, nx, ny, tileAlpha, tileBlend)+                    )                 }                  else -> {-                    // P1 fix (#12 Kotlin audit): unknown tag should skip not crash whole page (forward compat)-                    android.util.Log.w("SafePdfParser", "Unknown primitive tag $tag wireVersion=$wireVersion width=$width — skipping")-                    // We cannot know payload length, so just skip this primitive+                    // The payload length of an unknown tag is unknowable, so the read+                    // position is now inside a payload and every later tag byte would be+                    // random data — which decodes into plausible-looking garbage primitives.+                    // Kotlin knows all 12 tags Rust emits, so an unknown tag means the stream+                    // has desynced: keep what decoded cleanly and stop.+                    android.util.Log.w(+                        TAG,+                        "unknown tag $tag at offset ${buf.position()} (wire v$wireVersion), " ++                            "prim $primIndex of $count — wire desync, truncating page",+                    )+                    break                 }             }         } +        // A page cut short — by the count clamp, a desync, or a truncated buffer — can end+        // inside a soft-mask bracket, which renders actively WRONG rather than merely+        // partial: with no mask ever composited the masked content draws fully opaque+        // (a vignette becomes a hard block), and a half-drawn mask erases a ragged region.+        // Trim back to before the bracket, unless that would cost most of the page.+        if (softMaskDepth > 0 && outermostSoftMaskStart >= 0) {+            val dropped = primitives.size - outermostSoftMaskStart+            if (outermostSoftMaskStart >= primitives.size / 2) {+                android.util.Log.w(TAG, "page ended inside a soft-mask bracket, dropping $dropped trailing prims")+                primitives.subList(outermostSoftMaskStart, primitives.size).clear()+            } else {+                android.util.Log.w(TAG, "page ended inside a soft-mask bracket spanning most of the page, keeping it")+            }+        }+         return SafePdfPage(width, height, primitives)     } 
pdf/src/main/rust/README.md
diff --git a/pdf/src/main/rust/README.md b/pdf/src/main/rust/README.mdindex 4c0bad4fae..37a8bdf251 100644--- a/pdf/src/main/rust/README.md+++ b/pdf/src/main/rust/README.md@@ -13,7 +13,7 @@ The point of "safe": all untrusted binary parsing happens in memory-safe Rust, and the JNI boundary only ever passes a flat little-endian buffer of geometry + UTF-8 text, so Kotlin never touches the raw PDF bytes. -## Scope (v5 — implemented)+## Scope (implemented)  - **PDF functions** (`functions.rs`): a full evaluator for all four function   types — Type 0 sampled (multilinear interpolation), Type 2 exponential, Type 3@@ -23,13 +23,69 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes. - **Text** with `/ToUnicode` decoding (1-byte simple fonts and 2-byte   Identity-H / Type0), full base encodings (WinAnsi, **real MacRoman**, Standard,   Symbol, ZapfDingbats), a comprehensive Adobe Glyph List, and embedded-program-  encoding recovery: TrueType `cmap` (formats 0/4/6/10/12/13), **Type 1 `/FontFile`** clear-text+  encoding recovery: TrueType `cmap` (formats 0/2/4/6/8/10/12/13/14), **Type 1 `/FontFile`** clear-text   `/Encoding` scan, and **CFF `/FontFile3`** charset+Encoding recovery-  (`cff.rs`). Text render modes 0–7 including the clip modes (4–7). Accurate+  (`cff.rs`). Text render modes 0–7 including the clip modes (4–7) and the+  invisible mode 3, which emits a non-painting record so a scanned page's OCR+  layer stays selectable and searchable. Accurate   glyph advance from `/Widths`/`/W`/`/DW` + `Tc`/`Tw`/`Th`.+- **Encoding resolution follows the spec's priority order** (9.6.6.1): for a+  symbolic font that declares neither `/Encoding` nor `/BaseEncoding`, the font+  program's **built-in** encoding outranks any implicit base encoding, and+  `/Differences` is layered on top of whichever base applies. StandardEncoding /+  WinAnsi is backfilled only for codes the built-in encoding does not cover, so a+  font whose symbolic flag is set spuriously still decodes. Previously the+  implicit WinAnsi base populated every printable code and shadowed the built-in+  encoding entirely, which made symbolic fonts render — and copy, and index —+  Latin letters where the document wanted symbols. For symbolic TrueType the+  `cmap` subtable precedence is also the spec's (9.6.6.4): **(3,0) Microsoft+  Symbol before (1,0) Macintosh**, rather than whichever subtable the font+  happened to store first. A symbolic font that carries only a (3,0)/(1,0)+  subtable and **no Unicode subtable** no longer yields an empty map: `gid →+  unicode` is recovered from the `post` table's glyph names through the Adobe+  Glyph List, so such fonts are still selectable and searchable. Glyph names are+  an authoritative Unicode source; Unicode is never invented from the raw+  character code, which would corrupt the text index.+- **Font parsing is cached per operation** (`FontCacheScope`): `FontInfo` — which+  owns the whole decompressed embedded font program — used to be rebuilt on every+  `interpret_content` call, so a font shared by *N* pages was parsed *N* times to+  render and another *N* times to build the search index. The cache is keyed by+  the font dictionary's object id and is scoped to a single top-level operation,+  then dropped: an object id is only a complete key while the document is+  unmutated, so a short-lived cache is correct where a global one would serve+  stale fonts after a `docedit`. Direct (non-indirect) font dictionaries are+  never cached.+- **Embedded glyph outlines**: TrueType/OpenType, bare CFF (`/Type1C`,+  `/CIDFontType0C`) and bare Type 1 programs are parsed and their real glyph+  contours are emitted as vector fills/strokes (`outlines.rs`), so paint modes+  0–2 draw the document's own typeface rather than a substitute. Type 2+  charstrings (including the `flex`/`flex1`/`hflex`/`hflex1` operators of Adobe+  TN#5177 §4.2) are interpreted by `ttf-parser`; the Type 1 interpreter in+  `type1.rs` implements the equivalent `OtherSubrs` 0/1/2 flex protocol itself,+  where the seven reference points must not restart the contour and the end point+  must be returned for the trailing `pop pop setcurrentpoint`. `/CIDToGIDMap`+  (`/Identity` or a stream) is applied when selecting CID glyphs, and a+  present-but-zero entry — or a CID past the end of the stream — is honored as+  `.notdef` (9.7.4.2) rather than falling through to identity and drawing an+  unrelated glyph. Outline emission is never gated on a successful Unicode+  mapping: a glyph with no `/ToUnicode` entry still paints. Fonts without a+  usable program fall back to a substitute system typeface positioned by the+  PDF's own metrics.+- **Vertical writing** (`WMode 1`): the writing mode is taken from the `/Encoding`+  CMap name, the Type0 dict and the descendant, and `/W2` //`DW2` drive the+  vertical advance and position vector. - **Type 3 fonts**: glyph CharProc content streams are interpreted and drawn   (`draw.rs::show_string_type3`), mapped through the font matrix and bounded by-  `MAX_TYPE3_GLYPHS` / `MAX_TYPE3_PRIMS_PER_GLYPH`.+  `MAX_TYPE3_GLYPHS` / `MAX_TYPE3_PRIMS_PER_GLYPH`. Hitting the per-glyph bound+  cuts at the cap and appends whatever clip/group closers the cut orphaned+  (innermost first), so an over-long glyph loses its tail rather than being dropped+  and cannot leave the renderer's save/restore stack unbalanced for the rest of the+  page. A soft-mask bracket is handled specially rather than truncated, because its+  mask is the content that *follows* `SoftMaskContent` and appending a bare+  `SoftMaskPop` would leave an empty mask: if the cap falls in the masked content the+  surplus is dropped and the mask moved back on, so the glyph keeps both its content+  and its real mask; if the cap falls inside the mask itself the bracket is completed+  instead. - **Vector paths**: lines, rectangles, filled/stroked paths, flattened beziers   for drawing; clip paths retain the exact beziers via `PathOp`   (Move/Line/Cubic/Close) and are drawn in Kotlin with `cubicTo` (wire v4).@@ -70,17 +126,30 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes. - **Encryption** (`crypto.rs` + `decrypt.rs`): open and save with the Standard   security handler — RC4-128 and **AES-128 (V4/R4)** and **AES-256 (V5/R6)**.   `save_encrypted` defaults to AES-128.-- **Wire format v5**: header `MAGIC 0x50444657 VERSION=5 f32 w,h u32 count`;+- **Wire format v10**: header `MAGIC 0x50444657 VERSION=10 f32 w,h u32 count`;   tags 1 Text, 2 Fill, 3 Stroke, 4 Image, 5 ClipPush (with a bezier-retentive   path-ops section), 6 ClipPop, 7 GroupPush, 8 GroupPop, 9 TextClipApply,-  10 SoftMaskPush, 11 SoftMaskContent, 12 SoftMaskPop. Text carries its render-  mode; Text/Fill/Stroke each carry a per-primitive blend byte (v5).-  `SafePdfParser.kt` parses v5 and keeps v1–v4 as fallbacks.+  10 SoftMaskPush, 11 SoftMaskContent, 12 SoftMaskPop, 13 SoftMaskTransfer (a+  256-byte `/TR` LUT, emitted only for a non-identity `/TR`), 14 ImageTiled (a+  rasterized tiling-pattern cell plus its step and lattice extent, so a periodic+  fill costs one bitmap rather than one image per tile). Tags 13 and 14 are+  *tag*-gated rather than version-gated — a decoder that never sees one is+  unaffected — so the declared version stays 10. Text carries its render+  mode (v4); Text/Fill/Stroke each carry a per-primitive blend byte (v5); Text+  also carries its device advance (v7) and bold/italic/family/outline flags plus+  the horizontal scale (v8); images carry per-image alpha (v9) and blend (v10).+  `SafePdfParser.kt` parses v10 and keeps the earlier versions as fallbacks. It is+  also written to consume a **v11** that adds the per-image `/Interpolate` byte, but+  that read is gated on v11 and Rust still declares v10, so the byte is neither+  written nor read; the two sides are consistent, not desynchronized. Whoever bumps+  Rust to v11 must start writing the byte in the same change (see the `/Interpolate`+  limitation). - **Blend modes**: honored not just on transparency groups but on individual-  fills, strokes and text (the graphics-state `/BM` travels with each Text/Fill/-  Stroke primitive and is applied per-draw in Kotlin via `Paint.blendMode`-  (API 29+) / Compose `BlendMode`, with a Porter-Duff fallback for the separable-  modes on older devices).+  fills, strokes and text — the graphics-state `/BM` travels with each Text/Fill/+  Stroke primitive and is applied per-draw in Kotlin via `android.graphics.BlendMode`.+  All separable and non-separable modes are supported natively with no per-device+  caveat: the module's `minSdk` is 31 and that API is 29, so no fallback path is+  needed. - **ExtGState soft masks** (`/SMask`): luminosity and alpha soft masks set via   `gs` apply to all subsequent drawing while active — fills, strokes, text,   images, shadings, and Form XObjects — not only forms. Rust brackets each@@ -89,14 +158,11 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   as a backdrop rectangle so uncovered areas take the backdrop luminance. Kotlin   composites with nested `saveLayer`s — a `DST_IN` mask layer, plus a   luminance→alpha `ColorMatrix` layer for luminosity masks. `/SMask /None`-  clears the mask. (`/TR` transfer functions are not applied — see limitations.)-- **Overprint** (`/OP`, `/op`, `/OPM`): overprint state is tracked and-  approximated on the RGB compositor as a Multiply blend (white/zero-ink-  channels leave the backdrop unchanged), applied when no explicit `/BM` is set.+  clears the mask. An affine `/TR` is applied; see limitations for non-linear ones. - **Kotlin drawing**: bezier clips via `cubicTo`; text-clip modes accumulate   glyph outlines (`Paint.getTextPath`) and intersect them into the clip at the-  `TextClipApply` marker; blend modes use `Paint.blendMode` on API 29+ and fall-  back to `PorterDuffXfermode` (Multiply/Screen/Darken/Lighten) on older devices.+  `TextClipApply` marker; each blend mode maps directly to+  `android.graphics.BlendMode`. - **Search**: a per-page text index stores both a lowercased (byte-aligned) and   original-case string, so case-sensitive and case-insensitive search are both   exact.@@ -112,42 +178,241 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.  ## Genuinely unsupported (documented, not silently skipped) +> ### WARNING: Redaction does not remove content — it covers it+>+> **Do not rely on `/Redact` to scrub sensitive data.** Applying a redaction+> paints an opaque box and deletes a text-showing operator only when its *start+> point* falls inside the redaction rect. Everything else survives in the saved+> file and stays extractable by any other tool: images, vector art, and any text+> that begins outside the box and runs into it. The pre-redaction content stream+> is left in the document.+>+> This is a **security** limitation, not a fidelity one — the page looks redacted+> while the data is still there. The removal is a heuristic over text-showing+> operators, not a content-stream rewrite. There is currently no user-facing+> warning on the apply action. It also compounds with the stale search index below:+> in the same session, search can still surface and highlight the text you just+> redacted.++ - **Public-key / certificate encryption** (`/Filter /Adobe.PubSec`): decryption   requires the recipient's private key, which the viewer does not possess.   Reported as `DecryptStatus::Unsupported`.-- **Type 1 / CFF glyph *outline* vector rendering**: the renderer emits Unicode-  text runs drawn with system fonts, so embedded Type 1/CFF programs are parsed-  only for code→Unicode recovery, not redrawn as vector outlines. (Text-clip-  modes therefore clip with the system-font outlines via `Paint.getTextPath`.)-- **Exotic font code→Unicode paths**: TrueType `cmap` subtable formats 0/4/6/10/-  12/13 are parsed; formats 2 (CJK high-byte), 8 (mixed 16/32), and 14 (variation-  selectors) are not. Type0 fonts assume an Identity-H/V CMap (2-byte codes);-  named/embedded non-Identity CMaps and `/CIDToGIDMap` are not applied (embedded-  glyphs are not rendered and text is recovered via `/ToUnicode`). Vertical-  writing mode (`WMode 1`, `/W2`, `/DW2`) is not supported — glyphs lay out-  horizontally. These affect only exotic embedded fonts lacking `/ToUnicode`.-- **Non-separable blend modes on API < 29** (Hue/Saturation/Color/Luminosity,-  and Overlay/ColorDodge/…): no native pre-29 support; they fall back to Normal.-- **Knockout transparency groups**: not expressible with Canvas layers;-  approximated as non-knockout.-- **Soft-mask `/TR` transfer functions**: the mask luminance/alpha is used-  directly; a `/TR` remapping function is not applied (rare; usually Identity).-- **Overprint compositing**: approximated as Multiply on the RGB compositor-  rather than true per-colorant ink overprinting (there are no device-  separations to overprint onto in an RGB viewer).+- **Predefined *named* non-Identity CMaps** (`90ms-RKSJ-H`, `GBK-EUC-H`,+  `ETen-B5-H`, `KSCms-UHC-H`, ...): the code→CID table of a predefined CMap is an+  external Adobe resource that cannot be embedded, so CID lookups fall back to+  identity and *glyph selection* for these encodings is wrong.+  What *is* handled: the **codespace ranges** of every mixed-width family are+  installed, so 1-byte and 2-byte codes are segmented correctly and the byte+  stream no longer desynchronizes (9.7.6.2). This is the difference between "some+  wrong glyphs" and "every character after the first 1-byte code is garbage",+  because a mis-sized code shifts the whole remainder of the string. It also makes+  `/ToUnicode` (which is keyed by *code*, not CID) resolve, so text extraction,+  search and substitute-font painting work even where the embedded glyphs do not.+  Covered families: Shift-JIS (`*-RKSJ-*`), Japanese EUC (`EUC-H/V`), GBK+  (`GBK*`), EUC-CN (`GB*-EUC-*`), Big5 (`*-B5-*`, `B5pc-*`), Korean UHC/EUC-KR+  (`*UHC*`, `KSC*`), and the variable-length `Uni*-UTF8-*` (1–4 byte) and+  `Uni*-UTF16-*` (2/4-byte surrogate) families. `Identity-H/V`, the pure-2-byte+  `Uni*-UCS2-*` families and the `<2121>`–`<7E7E>` ISO-2022 families (`H`, `V`,+  `Add-H`, `Ext-H`) need no codespace and are fully segmented already.+  `usecmap` is honored, inheriting the referenced predefined CMap's codespace.+  **Embedded** CMap *streams* are parsed for real code→CID ranges, variable-length+  codespaces and `/WMode`, and are fully supported.+  Two known gaps: shipping the ~40 compiled predefined code→CID tables is the+  remaining work (they are registry-specific integer tables that must be copied+  from the Adobe resources — inventing values would silently select confidently+  wrong glyphs, which is worse than the identity fallback); and `GBK2K-H`+  (GB18030) has a 4-byte plane distinguished only by the *second* byte, which the+  first-byte-only code-length dispatch cannot see, so those rare codes still+  mis-segment.+- **Vertical writing position vector `v_y` per CID**: `/W2` and `/DW2` are parsed+  and applied — the vertical advance `w1_y`, the horizontal offset `v_x` and the+  `[880 -1000]` `/DW2` default all drive layout — but a *CID-specific* `v_y` is+  discarded and the `/DW2` value is used for every glyph. Also note the vertical+  advance keeps applying `Tc`/`Tw` in the direction that widens the gap, which+  deviates from the literal formula in 9.4.4 (where a positive `Tc` would tighten+  negative-`w1` vertical text) in favour of matching the horizontal behaviour.+- **CFF2 and other font programs `ttf-parser` cannot open**: an unparseable+  `/FontFile[23]` yields no outline program, and the glyph falls back to being+  painted with a substitute system typeface using the PDF's own widths. Text is+  still positioned, selectable and searchable; only the glyph shapes are+  approximate.+- **Composite fonts with no `/ToUnicode`**: for a Type0 font that embeds no+  outline program and supplies no `/ToUnicode`, the character codes are CIDs with+  no recoverable Unicode meaning, so the extracted text is not trustworthy. The+  proper fix is the predefined `Adobe-Japan1-UCS2`-style CID→Unicode tables,+  which is the same compiled-table work as the entry above.+- **Search matches the exact Unicode the PDF supplies, with no normalization**:+  case folding is applied (and only where it preserves byte length, so the+  lowercased and original-case page strings stay aligned for one span table), but+  **ligatures are not expanded and diacritics are not folded**. Searching `find`+  will not match text typeset with the `fi` ligature (U+FB01), and `café` will not+  match `cafe`. The ligature case is the one users hit, because professionally+  typeset PDFs use `fi`/`fl` routinely and whether the ligature survives into the+  text depends entirely on what the font's `/ToUnicode` maps it to.+- **Embedded font programs are never rasterized by the renderer**: glyphs either+  arrive as real outline fills from the core, or are drawn with a substitute+  system typeface chosen by generic family (sans/serif/mono) with synthesized+  bold/italic. Positioning stays correct because the core supplies a per-glyph+  origin and advance, but letterforms differ where no embedded outline is+  available.+- **Text clipping (`Tr` 4–7) clips with the substitute typeface's outline**, not+  the embedded glyph outline, so a text-clipped region has the right position and+  size but the wrong letterform edges.+- **Transparency group `/K` (knockout) is ignored**: a knockout group renders as+  if non-knockout, so overlapping elements inside one incorrectly show through+  each other instead of each replacing the last (11.4.6 / 11.6.6).+  `Canvas.saveLayer` composites each element against the running result rather+  than against the group's initial backdrop, which is what knockout requires.+- **Transparency group `/I false` (non-isolated) is ignored**: a non-isolated+  group renders as isolated, so a group carrying a non-Normal blend mode fails to+  blend with the page backdrop and looks flat or too opaque (11.4.5).+  `saveLayer` always yields an isolated layer and there is no way to seed it with+  the existing backdrop.+  Both flags *are* parsed and carried over the wire (`u8 isolated, u8 knockout`);+  neither variant is expressible with Canvas layers.+- **Soft-mask `/TR` transfer functions are applied only when affine** (11.6.5.2):+  the mask value is passed through `/TR`, carried to the renderer as a 256-entry+  LUT (wire tag 13) and least-squares fitted to `gain * m + bias` in Kotlin.+  Inverting and gain/bias curves fit exactly and are applied exactly — which+  covers the case that matters, since an inverting `/TR` is the standard idiom for+  "mask out where the group is bright" and ignoring it hid exactly the wrong half.+  A *nearly* linear curve is accepted and applied as its best-fit line, the+  tolerance being a maximum absolute error of `3/255`. Only a genuinely+  non-linear `/TR` (gamma, threshold, sampled Type 0) is refused: it is detected,+  logged once at parse time, and left **untransformed** rather than approximated,+  because a wrong curve hides the wrong half of the group — the exact fault this+  exists to prevent. What a user sees in that case is a mask with the wrong+  falloff — a vignette that fades over the wrong distance, or a mask with visibly+  wrong contrast — rather than a subtly approximated one, since the mask is applied+  as though `/TR` were identity. An identity `/TR` never reaches the wire; it is+  dropped in Rust, which is cheaper and indistinguishable from applying it.+  The remaining gap is a platform one: a soft mask is composited in a+  `Canvas.saveLayer`, whose only per-pixel hook is the affine+  `ColorMatrixColorFilter`; Android has no alpha-LUT filter, a `saveLayer` exposes+  no readable pixel buffer, and `RuntimeShader` cannot act as that filter.+- **Overprint** (`/OP`, `/op`, `/OPM`): parsed into the graphics state but+  deliberately not applied. Overprint controls which *device colorants* are left+  unmarked (8.6.7) and has no meaning on an additive RGB compositor with no+  separations. It was previously approximated as a Multiply blend, which was+  actively harmful: `white MULTIPLY dst == dst` turned white knockout rectangles+  into no-ops and let content that should have been covered show through. - **Incremental save / detached-signature verification**: `save_to` always   rewrites the whole document (no `/Prev` xref append), so cryptographic   signature *verification* and byte-range-preserving incremental updates are not   implemented. Signing scaffolding (`prepare_signature`) and detached CMS   creation exist, but existing signatures are not validated on open.-- **True redaction**: `/Redact` handling removes a text-show operator only when-  its origin falls inside the redaction rect and otherwise covers the area with-  an opaque box. Partial-overlap text, images and vector art are *covered*, not-  removed from the content stream — do not rely on it to scrub sensitive data.-- **CCITTFax `/EncodedByteAlign` and mixed 1-D/2-D G3 (`K > 0`)**: the `fax`-  crate decodes pure G3 (1-D) and G4 (2-D) from a continuous bitstream and does-  not expose per-row byte alignment or K>0 mode switching, so these two CCITT-  options are not honored. Pure G3/G4 (the common cases) decode correctly.+- **`/Interpolate` is decided but never transmitted** (8.9.5.1): an image that asks+  for smoothing and one that asks for none are filtered identically, so a magnified+  QR code, barcode, scanned fax or 1-bit stencil turns into grey mush.+  `image_should_interpolate` computes the right answer in Rust, but `Prim::Image`+  has no field for it, the Image arm writes no interpolate byte, and the renderer+  filters unconditionally. The same root cause has a second surface: a rasterized+  tiling-pattern cell (`ImageTiled`) is drawn with bitmap filtering hard-coded on,+  so a bilevel hatch pattern blurs when zoomed.+  The two sides are consistent about it rather than desynchronized: the wire spec+  defines the byte at v11 and the Kotlin decoder is written to consume it, but that+  read is gated on v11 and Rust still declares v10 — so the byte is never written+  and never read, and the gate fails safe. This is the same half-wired shape `/TR`+  had before it was completed, which is why it can look finished from either side+  alone. Whoever bumps Rust to v11 **must** write the byte in the same change;+  `wire.rs` says so at the constant.+- **A very dense page is truncated at 300,000 drawing primitives**: past that the+  rest of the page is not emitted, so a large-format vector drawing — a map, CAD+  sheet or dense chart — renders only partially. This is a memory floor rather+  than a tunable: a `Prim` costs ~120–180 bytes in practice, so 300,000 is roughly+  40–55 MB held simultaneously with the ~15 MB serialized wire copy, and a Rust+  OOM is an uncatchable process abort. The cap is enforced at every+  content-emitting push. The truncation is **silent**: nothing on the wire flags+  it and the viewer surfaces no message, so the page simply renders its top+  portion and looks as though it finished normally. The separate operator ceiling+  (`MAX_CONTENT_OPS`, a *time* guard) sits deliberately above it at 1,000,000 so+  it only catches pathological streams — it was formerly 200,000, which made it+  the binding constraint and cut an ordinary dense vector page off at ~100,000+  primitives, a third of what was already sanctioned.+- **No per-page cap on shading memory**: a page with very many gradients can use a+  lot of memory. Each shading raster is capped individually — 256 KB for+  axial/radial gradients, 1 MB for function-based and mesh shadings — but nothing+  bounds their total, so a page with hundreds of gradients holds every one at once.+- **Some tiling patterns are drawn at reduced density over a large area**+  (8.7.3.3): most tiled fills now repeat across the whole region at full density —+  a cell made only of fills and strokes is rasterized **once** and emitted as a+  periodic bitmap, so the tile count stops mattering. That includes *overlapping*+  patterns, where `/XStep` or `/YStep` is smaller than the `/BBox` (8.7.3.1): such a+  pattern is still periodic with period `(XStep, YStep)`, and the cell is drawn at+  every lattice offset that reaches one period window, so the spill from+  neighbouring cells is composited in rather than lost.+  Two cases still fall back to replaying the cell per tile, where past 20,000 tiles+  the lattice is thinned uniformly (stride = `ceil(sqrt(need / 20000))`) to stay+  inside the primitive budget — the region remains **fully covered**, just coarser+  than the document asks for: a cell containing **text**, an **image** or its own+  **clipping/group** (the cell rasterizer has no glyph rasterizer and ignores+  images, clips and groups, so rasterizing it would silently drop that content);+  and a pattern overlapping so heavily that one period needs more than 64 cell+  copies to resolve, which is bounded because the cost is per-period, not per-tile.+- **Overlapping shapes under one soft mask blend slightly wrong**: where many+  shapes overlap beneath a single partially-transparent `/SMask`, the composite in+  the overlap region is a little off, because consecutive paints under the same+  mask are coalesced into ONE masked layer and therefore composited as a group+  rather than individually. The coalescing is deliberate and not a shortcut: one+  bracket per painting operator re-expanded the mask for every operator and pushed+  pages past the primitive cap, truncating real content — a visibly worse outcome+  than a slight blend error.+- **The search index is never invalidated after a document edit**: redacting,+  adding or deleting an annotation, filling a form field, or moving, removing or+  rotating a page does **not** rebuild the text index for the rest of the session.+  Search then returns hits computed from the pre-edit text and highlights+  rectangles that point at content which has moved or no longer exists. The+  privacy-relevant case compounds with the redaction warning above: **search can+  still surface and highlight text that was just redacted.** `invalidate_index`+  exists and is correct, but has no callers — the mutators take the registry lock+  directly rather than through a single accessor, so there is no one place that+  observes "this document changed", and the ~25 handle-taking mutators across+  `docedit.rs`, `annotations.rs` and `forms.rs` would each have to remember to call+  it. Closing an unused document is the only thing that currently evicts an index.+- **Form fields with no appearance stream are invisible**: a field that relies on+  the viewer to build its own appearance (`/NeedAppearances` set, no `/AP`)+  renders as nothing at all rather than as a box showing its value, because+  appearance generation runs only when the user edits a field, not on load.+- **Non-ASCII text typed into a form field or text annotation is mangled in the+  saved file**: it displays correctly inside this app, but the generated+  appearance stream writes UTF-8 bytes into a Latin-1 encoded font, so every other+  viewer shows `é` where `é` was typed. The text is not lost, but the file is+  wrong everywhere except here.+- **Overlapping strokes in a translucent annotation darken where they cross**: a+  semi-transparent Ink or Highlight annotation whose own strokes overlap is+  composited per-stroke rather than as a single group, so intersections come out+  darker than the author intended (11.6.2 wants group semantics).+- **Multi-select list boxes collapse to a single selection**: choosing several+  options stores only one, because the value setter takes a single string.+- **Rich-text field formatting is dropped**: a field with `/RV` shows its plain+  text — correct content, but no bold, italic or colour runs.+- **Standard stamp annotations show their wording in a plain outlined box** instead+  of real artwork: an Approved stamp renders as the word APPROVED in a rectangle,+  because Acrobat's stamp graphics are not shipped.+- **Pushbuttons are presented as toggleable checkboxes** even though a pushbutton+  has no value.+- **Physical page sizing (`/UserUnit`) is not surfaced**; page layout and+  rendering are unaffected by it.+- **True redaction**: see the highlighted warning at the top of this section —+  `/Redact` covers content rather than removing it.+- **Large JBIG2 images render as nothing at all**: a JBIG2 image wider or taller+  than 20,000px, or over 16 megapixels, comes out fully transparent — a deliberate+  memory guard in `jbig2.rs` with no partial-decode path.+- **JBIG2 decode failures are silent**: an image that fails to decode renders as an+  invisible gap rather than a placeholder, so a failure is indistinguishable from a+  legitimately blank region. Deliberate (the red placeholder was removed), but it+  means nothing signals the loss.+- **CCITTFax `/EncodedByteAlign` and mixed 1-D/2-D G3 (`K > 0`)**: a G3/G4 fax+  image with `/EncodedByteAlign true` renders as diagonal streaks or noise, since+  each row must restart on a byte boundary. This is genuinely blocked by the `fax`+  crate's API rather than merely unimplemented: `ByteReader`'s `partial`/`valid`+  fields and `fill()` are private, its only public surface is `new` plus two debug+  printers, and `Group3Decoder`/`Group4Decoder` own their reader internally, so+  there is no way to realign the bit reader. `K > 0` is likewise a best-effort+  attempt (try G3, then fall back to G4) rather than real per-row mode switching,+  so a genuinely mixed page can decode partially or not at all. Pure G3/G4 — the+  common cases — decode correctly.  ## Prerequisites (local + CI) @@ -164,7 +429,11 @@ cargo test Covers PDF function evaluation (all four types), radial-shading parameterization, mesh-shading rasterization, stroke-outline quad generation, Type 3 glyph emission, image colorspace conversion, LZW/TIFF predictors, RC4/AES-128/AES-256-save round-trips, CFF/Type 1 encoding recovery, case-sensitive search, and the-wire round-trip (including per-primitive blend and soft-mask markers).+save round-trips, CFF/Type 1 encoding recovery, Type 1 charstring `flex`+(one contour, correct current point), mixed-width predefined-CMap codespace+segmentation, the per-operation font cache (shared inside a scope, uncached+without one), `Tw` applying only to single-byte code 32, the untrusted-font-data+loop clamps, case-sensitive search, and the wire round-trip (including+per-primitive blend and soft-mask markers).  [`lopdf`]: https://crates.io/crates/lopdf
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 1e917bedbc..0edc401682 100644--- a/pdf/src/main/rust/src/afm.rs+++ b/pdf/src/main/rust/src/afm.rs@@ -121,6 +121,7 @@ fn build_courier() -> HashMap<String, f64> { // ---------------------------------------------------------------------------  static HELVETICA: &[(&str, u16)] = &[+    ("Euro", 556),     ("space", 278), ("exclam", 278), ("quotedbl", 355), ("numbersign", 556),     ("dollar", 556), ("percent", 889), ("ampersand", 667), ("quotesingle", 191),     ("quoteright", 222), ("parenleft", 333), ("parenright", 333), ("asterisk", 389),@@ -181,6 +182,7 @@ static HELVETICA: &[(&str, u16)] = &[ ];  static HELVETICA_BOLD: &[(&str, u16)] = &[+    ("Euro", 556),     ("space", 278), ("exclam", 333), ("quotedbl", 474), ("numbersign", 556),     ("dollar", 556), ("percent", 889), ("ampersand", 722), ("quotesingle", 238),     ("quoteright", 278), ("parenleft", 333), ("parenright", 333), ("asterisk", 389),@@ -240,6 +242,7 @@ static HELVETICA_BOLD: &[(&str, u16)] = &[ ];  static TIMES_ROMAN: &[(&str, u16)] = &[+    ("Euro", 500),     ("space", 250), ("exclam", 333), ("quotedbl", 408), ("numbersign", 500),     ("dollar", 500), ("percent", 833), ("ampersand", 778), ("quotesingle", 180),     ("quoteright", 333), ("parenleft", 333), ("parenright", 333), ("asterisk", 500),@@ -299,6 +302,7 @@ static TIMES_ROMAN: &[(&str, u16)] = &[ ];  static TIMES_BOLD: &[(&str, u16)] = &[+    ("Euro", 500),     ("space", 250), ("exclam", 333), ("quotedbl", 555), ("numbersign", 500),     ("dollar", 500), ("percent", 1000), ("ampersand", 833), ("quotesingle", 278),     ("quoteright", 333), ("parenleft", 333), ("parenright", 333), ("asterisk", 500),@@ -358,6 +362,7 @@ static TIMES_BOLD: &[(&str, u16)] = &[ ];  static TIMES_ITALIC: &[(&str, u16)] = &[+    ("Euro", 500),     ("space", 250), ("exclam", 333), ("quotedbl", 420), ("numbersign", 500),     ("dollar", 500), ("percent", 833), ("ampersand", 778), ("quotesingle", 214),     ("quoteright", 333), ("parenleft", 333), ("parenright", 333), ("asterisk", 500),@@ -417,6 +422,7 @@ static TIMES_ITALIC: &[(&str, u16)] = &[ ];  static TIMES_BOLD_ITALIC: &[(&str, u16)] = &[+    ("Euro", 500),     ("space", 250), ("exclam", 389), ("quotedbl", 555), ("numbersign", 500),     ("dollar", 500), ("percent", 833), ("ampersand", 778), ("quotesingle", 278),     ("quoteright", 333), ("parenleft", 333), ("parenright", 333), ("asterisk", 500),
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 04c6c24b97..5e3eaf6ebf 100644--- a/pdf/src/main/rust/src/annotations.rs+++ b/pdf/src/main/rust/src/annotations.rs@@ -32,6 +32,33 @@ pub(crate) fn appearance_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) ->     mat_mul(&matrix, &fit) } +/// Whether an annotation should be painted on screen. Shared by the renderer and+/// by `flatten_document`, which must not bake in anything invisible.+///+/// Per §12.5.3 Table 165 the `/F` flags are tested by VALUE: Hidden is bit+/// position 2 (value 2), NoView is bit position 6 (value 32). Also honors+/// optional content (§8.11.2) and skips `/Popup`, whose appearance is shown only+/// via its parent's open state (§12.5.6.14).+pub(crate) fn annot_visible_on_screen(doc: &Document, dict: &lopdf::Dictionary) -> bool {+    let flags = dict+        .get(b"F")+        .ok()+        .and_then(|o| deref(doc, o).or(Some(o)))+        .and_then(num)+        .unwrap_or(0.0) as i64;+    if flags & 0b10 != 0 || flags & 0b10_0000 != 0 {+        return false;+    }+    if dict.get(b"OC").ok().map(|oc| crate::oc_object_hidden(doc, oc)).unwrap_or(false) {+        return false;+    }+    dict.get(b"Subtype")+        .ok()+        .and_then(|o| deref(doc, o).or(Some(o)))+        .and_then(|o| o.as_name().ok())+        != Some(b"Popup")+}+ /// Render each visible page annotation's normal appearance (`/AP /N`) into /// primitives, mapping the appearance BBox into the annotation Rect, then /// through `base` (page rotation / origin) into displayed space.@@ -51,18 +78,7 @@ pub(crate) fn render_annotations(doc: &Document, page_id: ObjectId, base: &Mat,             Some(d) => d,             None => continue,         };-        // Skip Hidden (bit 2) and NoView (bit 6) annotations.-        let flags = dict.get(b"F").ok().and_then(num).unwrap_or(0.0) as i64;-        if flags & 0b10 != 0 || flags & 0b10_0000 != 0 {-            continue;-        }-        // Skip annotations on an optional-content group that is turned OFF.-        if dict.get(b"OC").ok().map(|oc| crate::oc_object_hidden(doc, oc)).unwrap_or(false) {-            continue;-        }-        // Popup annotations are only shown when their parent is open; don't paint-        // them inline on the page.-        if dict.get(b"Subtype").ok().and_then(|o| o.as_name().ok()) == Some(b"Popup") {+        if !annot_visible_on_screen(doc, dict) {             continue;         }         render_annotation(doc, dict, base, prims);@@ -89,14 +105,25 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:     let normal = match ap.get(b"N").ok().and_then(|o| deref(doc, o)) {         Some(Object::Stream(s)) => s,         Some(Object::Dictionary(states)) => {-            // The appearance sub-state is selected by /AS. When /AS is missing or-            // doesn't match, fall back to the "Off" state (a button's default) —-            // NOT an arbitrary first entry, which is nondeterministic (HashMap order)-            // and can render an unchecked box as checked.             let as_name = dict.get(b"AS").ok().and_then(|o| o.as_name().ok());-            let picked = as_name-                .and_then(|n| states.get(n).ok())-                .or_else(|| states.get(b"Off").ok());+            let picked = match as_name {+                // /AS present: it selects the state. If it names a state that is+                // absent, fall back to "Off" (a button's default) and otherwise+                // draw nothing — NOT an arbitrary entry, which is+                // nondeterministic and would render an unchecked box as checked.+                Some(n) => states.get(n).ok().or_else(|| states.get(b"Off").ok()),+                // /AS absent is malformed (§12.5.5, Table 168 requires it when /N+                // is a subdictionary). Prefer "Off"; failing that, a single entry+                // is unambiguous, so use the real appearance rather than+                // synthesizing a crude one over the top of it.+                None => states.get(b"Off").ok().or_else(|| {+                    if states.len() == 1 {+                        states.iter().next().map(|(_, v)| v)+                    } else {+                        None+                    }+                }),+            };             match picked.and_then(|o| deref(doc, o)) {                 Some(Object::Stream(s)) => s,                 _ => {@@ -111,12 +138,12 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:         }     }; -    let bbox = normal+    let bbox_raw = normal         .dict         .get(b"BBox")         .ok()-        .and_then(|o| read_rect(doc, o))-        .unwrap_or([0.0, 0.0, 1.0, 1.0]);+        .and_then(|o| read_rect(doc, o));+    let bbox = bbox_raw.unwrap_or([0.0, 0.0, 1.0, 1.0]);     let matrix = normal         .dict         .get(b"Matrix")@@ -131,32 +158,74 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:         .and_then(|o| o.as_dict().ok())         .cloned(); -    let bytes = stream_data_with_doc(doc, normal);-    let ops = match Content::decode(&bytes) {-        Ok(c) => c.operations,-        Err(_) => return,-    };+    let ops = crate::content::stream_operations(doc, normal);+    if ops.is_empty() {+        return;+    }++    let ctm = mat_mul(&appearance_matrix(rect, bbox, matrix), base);++    // §8.10.2: a form XObject's /BBox "shall be used to clip" its contents, and+    // §12.5.5 defines an appearance stream as a form XObject. Without this an+    // appearance paints outside its own Rect. Clip to the /Matrix-transformed+    // BBox QUAD rather than the axis-aligned box §12.5.5 derives for the /Rect+    // fit — the latter is too loose and lets a rotated appearance spill. The+    // same `ctm` is reused for the clip and the content, so the form's /Matrix+    // (already folded into it by appearance_matrix) cannot be applied twice.+    // A degenerate BBox is skipped: a collapsed quad would swallow the whole+    // annotation, turning a spill into a vanish.+    let clip = bbox_raw+        .map(normalize_rect)+        .filter(|b| b[2] - b[0] > 0.0 && b[3] - b[1] > 0.0);+    if let Some(b) = clip {+        let pts: Vec<(f32, f32)> = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])]+            .iter()+            .map(|&(x, y)| {+                let (dx, dy) = transform(&ctm, x, y);+                (dx as f32, dy as f32)+            })+            .collect();+        let mut path_ops = vec![PathOp::Move(pts[0].0, pts[0].1)];+        path_ops.extend(pts[1..].iter().map(|&(x, y)| PathOp::Line(x, y)));+        path_ops.push(PathOp::Close);+        prims.push(Prim::ClipPush { even_odd: false, pts, path_ops: Some(path_ops) });+    }      let gs = GraphicsState {-        ctm: mat_mul(&appearance_matrix(rect, bbox, matrix), base),+        ctm,         ..Default::default()     };     let start = prims.len();     interpret_content(doc, &ops, res.as_ref(), gs, prims, 1, false);      // Honor the annotation's constant opacity (/CA) over its rendered prims.-    let ca = dict.get(b"CA").ok().and_then(num).unwrap_or(1.0);+    let ca = dict.get(b"CA").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(num).unwrap_or(1.0);     if ca < 1.0 {         for p in prims[start..].iter_mut() {             scale_prim_alpha(p, ca);         }     }+    // Unconditional pop (mirrors the `Do` arm): interpret_content always returns+    // with a balanced clip depth, so this keeps the canvas clip stack balanced+    // even if the content hit the primitive cap.+    if clip.is_some() {+        prims.push(Prim::ClipPop);+    } }  /// Read an annotation color array (`/C`, `/IC`) as ARGB, or `None` when the /// array is empty (meaning "no color" / transparent) or absent.-fn markup_color(dict: &lopdf::Dictionary, key: &[u8]) -> Option<u32> {-    let arr = dict.get(key).ok()?.as_array().ok()?;+///+/// The array is dereferenced: §7.3.10 lets any object be indirect, and an+/// indirect `/C` previously read as "no colour", silently substituting the+/// default instead of the author's.+fn markup_color(doc: &Document, dict: &lopdf::Dictionary, key: &[u8]) -> Option<u32> {+    let arr = dict+        .get(key)+        .ok()+        .and_then(|o| deref(doc, o).or(Some(o)))?+        .as_array()+        .ok()?;     let c: Vec<f64> = arr.iter().filter_map(num).collect();     match c.len() {         1 => Some(gray_to_argb(c[0])),@@ -200,9 +269,19 @@ fn annot_border_dash(doc: &Document, dict: &lopdf::Dictionary) -> Vec<f64> {     Vec::new() } -/// Synthesize a basic appearance for common annotation types that lack an `/AP`-/// stream, emitting primitives directly (Square/Circle/Line/Ink and the text-/// markup types via `/QuadPoints`). Unknown types are skipped.+/// Synthesize a basic appearance for annotation types that lack an `/AP` stream.+///+/// Only shapes the file actually specifies are drawn: Square/Circle from `/Rect`,+/// Line from `/L` (with `/LE` endings), Ink from `/InkList`, Polygon/PolyLine+/// from `/Vertices`, the text markup types from `/QuadPoints`, Caret as an+/// insertion wedge and Stamp as its `/Name` wording in a box.+///+/// Everything else — Widget, Link, FileAttachment, Sound, Movie, Screen, and any+/// of the above missing its defining geometry — draws NOTHING. A crude wrong+/// shape is worse than an absent one: a bare `/Rect` outline is+/// indistinguishable from a Square annotation and asserts a geometry the file+/// never gave. In particular Link must never draw chrome of its own (§12.5.6.5+/// leaves the border to `/Border`, honoured only inside a real `/AP`). pub(crate) fn synthesize_annotation_appearance(     doc: &Document,     dict: &lopdf::Dictionary,@@ -214,9 +293,15 @@ pub(crate) fn synthesize_annotation_appearance(         Some(s) => s.to_vec(),         None => return,     };-    let ca = dict.get(b"CA").ok().and_then(num).unwrap_or(1.0).clamp(0.0, 1.0);-    let stroke = markup_color(dict, b"C");-    let fill = markup_color(dict, b"IC");+    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);+    let stroke = markup_color(doc, dict, b"C");+    let fill = markup_color(doc, dict, b"IC");     let bw = annot_border_width(doc, dict);     let dev = |x: f64, y: f64| -> (f64, f64) { transform(base, x, y) };     // Device half-width for strokes (approx via base scale).@@ -271,12 +356,34 @@ pub(crate) fn synthesize_annotation_appearance(             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());             if let Some(n) = l_arr {                 if n.len() >= 4 {-                    let seg = vec![dev(n[0],n[1]), dev(n[2],n[3])];+                    let (p0, p1) = ((n[0], n[1]), (n[2], n[3]));+                    let seg = vec![dev(p0.0, p0.1), dev(p1.0, p1.1)];                     let mut sgs = gs.clone(); sgs.stroke = stroke.unwrap_or(0xFF00_0000);                     let d = annot_border_dash(doc, dict);                     if !d.is_empty() { sgs.dash = d; }-                    // Line ending styles omitted — render as straight segment                     emit_stroke(prims, std::slice::from_ref(&seg), &sgs);+                    // §12.5.6.7: /LE is [startStyle endStyle] and each ending+                    // points OUTWARD along the line, so the start ending's+                    // direction is p1 -> p0 and the end ending's is p0 -> p1.+                    let (dx, dy) = (p1.0 - p0.0, p1.1 - p0.1);+                    let len = (dx * dx + dy * dy).sqrt();+                    if len > 1e-6 {+                        let u = (dx / len, dy / len);+                        let le: Vec<Vec<u8>> = dict+                            .get(b"LE")+                            .ok()+                            .and_then(|o| deref(doc, o))+                            .and_then(|o| o.as_array().ok())+                            .map(|a| a.iter().filter_map(|o| o.as_name().ok().map(|n| n.to_vec())).collect())+                            .unwrap_or_default();+                        let le_size = (bw.max(1.0) * 4.0).clamp(4.0, 24.0);+                        if let Some(s) = le.first() {+                            emit_line_ending(prims, base, p0, (-u.0, -u.1), s, le_size, &sgs, fill, ca);+                        }+                        if let Some(s) = le.get(1) {+                            emit_line_ending(prims, base, p1, u, s, le_size, &sgs, fill, ca);+                        }+                    }                 }             }         }@@ -294,23 +401,25 @@ pub(crate) fn synthesize_annotation_appearance(         }         b"Highlight" => {             let color = stroke.unwrap_or(0xFFFF_FF00); // default yellow-            if !quads.is_empty() && prims.len() + quads.len() < MAX_PRIMITIVES {-                // Precise quad fill per QuadPoints instead of bbox rect-                for q in &quads {-                    let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();-                    if poly.len() >= 4 {-                        emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);-                    }-                }-            } else if quads.is_empty() {+            if quads.is_empty() {                 let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];                 emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);             } else {+                // §12.5.6.10 orders the vertices UL, UR, LL, LR — a "Z", not a+                // ring — so traversing them in file order self-intersects into a+                // bow-tie. Reorder to UL, UR, LR, LL. Kept as a quad rather than+                // its bbox so rotated/skewed text quads stay correct.+                //+                // Over the primitive cap the loop simply stops. The previous+                // fallback swapped to axis-aligned bbox rects instead, which both+                // emitted the same number of primitives it was trying to avoid+                // AND drew the wrong shape for rotated text.                 for q in &quads {-                    let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();-                    let bx = bbox_of(&poly);-                    let rectp = vec![(bx[0],bx[1]),(bx[2],bx[1]),(bx[2],bx[3]),(bx[0],bx[3])];-                    emit_fill(prims, std::slice::from_ref(&rectp), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);+                    if prims.len() >= MAX_PRIMITIVES {+                        break;+                    }+                    let poly: Vec<(f64,f64)> = [q[0], q[1], q[3], q[2]].iter().map(|&(x,y)| dev(x,y)).collect();+                    emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);                 }             }         }@@ -319,61 +428,112 @@ pub(crate) fn synthesize_annotation_appearance(             let mut sgs = gs.clone(); sgs.stroke = color;             let d = annot_border_dash(doc, dict);             if !d.is_empty() { sgs.dash = d; }-            if subtype == b"Squiggly" {-                // Zig-zag approximate underline-                for q in &quads {-                    let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();-                    let bx = bbox_of(&poly);-                    let base_y = bx[1];-                    let amp = (bx[3] - bx[1]) * 0.08;-                    let step = (bx[2] - bx[0]) / 8.0;-                    let mut zig: Vec<(f64,f64)> = Vec::new();+            // §12.5.6.10 quad order is UL, UR, LL, LR. Work along the quad's own+            // edges in PAGE space and map each point through `base`, instead of+            // taking the device-space bbox: the bbox is axis-aligned, so on a+            // rotated page (or over rotated text) it drew a horizontal rule+            // across the glyphs rather than a rule following the baseline.+            if subtype != b"Squiggly" {+                sgs.line_width = (bw.max(1.0)) / scale.max(1e-6); // ~1px device+            }+            // Fraction of the quad height at which the rule sits, measured from+            // the bottom edge towards the top.+            let t = if subtype == b"StrikeOut" { 0.5 } else { 0.10 };+            for q in &quads {+                if prims.len() >= MAX_PRIMITIVES {+                    break;+                }+                let (ul, ur, ll, lr) = (q[0], q[1], q[2], q[3]);+                // Baseline-parallel start/end, lifted off the bottom edge.+                let a = (ll.0 + (ul.0 - ll.0) * t, ll.1 + (ul.1 - ll.1) * t);+                let b = (lr.0 + (ur.0 - lr.0) * t, lr.1 + (ur.1 - lr.1) * t);+                if subtype == b"Squiggly" {+                    // Zig-zag between the rule line and a line 8% of the quad+                    // height above it, so the wave follows the text direction.+                    let up = ((ul.0 - ll.0) * 0.08, (ul.1 - ll.1) * 0.08);+                    let mut zig: Vec<(f64, f64)> = Vec::with_capacity(9);                     for i in 0..=8 {-                        let x = bx[0] + i as f64 * step;-                        let y = if i % 2 == 0 { base_y } else { base_y + amp };-                        zig.push((x, y));+                        let f = i as f64 / 8.0;+                        let (x, y) = (a.0 + (b.0 - a.0) * f, a.1 + (b.1 - a.1) * f);+                        let (x, y) = if i % 2 == 0 { (x, y) } else { (x + up.0, y + up.1) };+                        zig.push(dev(x, y));                     }-                    if zig.len() >= 2 { emit_stroke(prims, std::slice::from_ref(&zig), &sgs); }-                }-            } else {-                sgs.line_width = (bw.max(1.0)) / scale.max(1e-6); // ~1px device-                for q in &quads {-                    let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();-                    let bx = bbox_of(&poly);-                    let y = if subtype == b"StrikeOut" { (bx[1]+bx[3])/2.0 } else { bx[1] + (bx[3]-bx[1]) * 0.10 };-                    let seg = vec![(bx[0], y), (bx[2], y)];+                    emit_stroke(prims, std::slice::from_ref(&zig), &sgs);+                } else {+                    let seg = vec![dev(a.0, a.1), dev(b.0, b.1)];                     emit_stroke(prims, std::slice::from_ref(&seg), &sgs);                 }             }         }-        b"Polygon" | b"PolyLine" | b"Caret" | b"Stamp" | b"FileAttachment" => {-            // Best-effort synthesis for these subtypes via vertices or rect+        b"Polygon" | b"PolyLine" => {+            // §12.5.6.9: the shape IS /Vertices. Without it there is no shape, so+            // 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();                 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";+                    // /IC is the interior colour and only a closed Polygon has an+                    // interior; on a PolyLine it colours the line endings, so it+                    // must not become the stroke colour (§12.5.6.9).                     if closed {                         if let Some(f) = fill {                             emit_fill(prims, std::slice::from_ref(&pts), apply_alpha_to_argb(f, ca), false, 1.0, BlendMode::Normal);                         }                     }-                    if let Some(s) = stroke.or(fill) {+                    if let Some(s) = stroke {                         let mut ring = pts.clone();                         if closed { ring.push(pts[0]); }                         let mut sgs = gs.clone(); sgs.stroke = s;+                        let d = annot_border_dash(doc, dict);+                        if !d.is_empty() { sgs.dash = d; }                         emit_stroke(prims, std::slice::from_ref(&ring), &sgs);                     }                 }-            } else {-                // Fallback to rect box-                let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];-                if let Some(f) = fill { emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(f, ca), false, 1.0, BlendMode::Normal); }-                if let Some(s) = stroke {-                    let mut ring = poly.clone(); ring.push(poly[0]);-                    let mut sgs = gs.clone(); sgs.stroke = s;-                    emit_stroke(prims, std::slice::from_ref(&ring), &sgs);-                }+            }+        }+        b"Caret" => {+            // §12.5.6.11: a caret marks a text insertion point. Synthesize the+            // upward wedge, which says "inserted here"; the old /Rect outline was+            // indistinguishable from a Square annotation.

Diff truncated.