Modern Apps git

← Modern-Apps.git

pdf: add more pdf renderer features

Commit
5cb95940df6bb836ec690dd9943237c50efa0d7a
Author
Vayun Mathur <[email protected]>
When
2026-07-24 23:06 UTC (4 months ago)
Parents
d9020e6

Diff

pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.ktindex cb35c7844a..f9a4b7c1c5 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -2081,6 +2081,66 @@ private fun StyleDialog(     ) } +/** Map the renderer's [BlendMode] to a Compose blend mode (SrcOver = normal). */+private fun BlendMode.toCompose(): androidx.compose.ui.graphics.BlendMode = when (this) {+    BlendMode.Normal -> androidx.compose.ui.graphics.BlendMode.SrcOver+    BlendMode.Multiply -> androidx.compose.ui.graphics.BlendMode.Multiply+    BlendMode.Screen -> androidx.compose.ui.graphics.BlendMode.Screen+    BlendMode.Overlay -> androidx.compose.ui.graphics.BlendMode.Overlay+    BlendMode.Darken -> androidx.compose.ui.graphics.BlendMode.Darken+    BlendMode.Lighten -> androidx.compose.ui.graphics.BlendMode.Lighten+    BlendMode.ColorDodge -> androidx.compose.ui.graphics.BlendMode.ColorDodge+    BlendMode.ColorBurn -> androidx.compose.ui.graphics.BlendMode.ColorBurn+    BlendMode.HardLight -> androidx.compose.ui.graphics.BlendMode.Hardlight+    BlendMode.SoftLight -> androidx.compose.ui.graphics.BlendMode.Softlight+    BlendMode.Difference -> androidx.compose.ui.graphics.BlendMode.Difference+    BlendMode.Exclusion -> androidx.compose.ui.graphics.BlendMode.Exclusion+    BlendMode.Hue -> androidx.compose.ui.graphics.BlendMode.Hue+    BlendMode.Saturation -> androidx.compose.ui.graphics.BlendMode.Saturation+    BlendMode.Color -> androidx.compose.ui.graphics.BlendMode.Color+    BlendMode.Luminosity -> androidx.compose.ui.graphics.BlendMode.Luminosity+}++/** The API 29+ [android.graphics.BlendMode] for a renderer [BlendMode]. */[email protected](29)+private fun BlendMode.toAndroid(): android.graphics.BlendMode = when (this) {+    BlendMode.Normal -> android.graphics.BlendMode.SRC_OVER+    BlendMode.Multiply -> android.graphics.BlendMode.MULTIPLY+    BlendMode.Screen -> android.graphics.BlendMode.SCREEN+    BlendMode.Overlay -> android.graphics.BlendMode.OVERLAY+    BlendMode.Darken -> android.graphics.BlendMode.DARKEN+    BlendMode.Lighten -> android.graphics.BlendMode.LIGHTEN+    BlendMode.ColorDodge -> android.graphics.BlendMode.COLOR_DODGE+    BlendMode.ColorBurn -> android.graphics.BlendMode.COLOR_BURN+    BlendMode.HardLight -> android.graphics.BlendMode.HARD_LIGHT+    BlendMode.SoftLight -> android.graphics.BlendMode.SOFT_LIGHT+    BlendMode.Difference -> android.graphics.BlendMode.DIFFERENCE+    BlendMode.Exclusion -> android.graphics.BlendMode.EXCLUSION+    BlendMode.Hue -> android.graphics.BlendMode.HUE+    BlendMode.Saturation -> android.graphics.BlendMode.SATURATION+    BlendMode.Color -> android.graphics.BlendMode.COLOR+    BlendMode.Luminosity -> android.graphics.BlendMode.LUMINOSITY+}++/** Pre-29 Porter-Duff fallback for the separable blend modes; null otherwise. */+private fun BlendMode.toPorterDuffOrNull(): android.graphics.PorterDuff.Mode? = when (this) {+    BlendMode.Multiply -> android.graphics.PorterDuff.Mode.MULTIPLY+    BlendMode.Screen -> android.graphics.PorterDuff.Mode.SCREEN+    BlendMode.Darken -> android.graphics.PorterDuff.Mode.DARKEN+    BlendMode.Lighten -> android.graphics.PorterDuff.Mode.LIGHTEN+    else -> null+}++/** Set (or clear) the blend mode on a reused native [android.graphics.Paint]. */+private fun android.graphics.Paint.setBlend(blend: BlendMode) {+    if (android.os.Build.VERSION.SDK_INT >= 29) {+        blendMode = if (blend == BlendMode.Normal) null else blend.toAndroid()+    } else {+        xfermode = if (blend == BlendMode.Normal) null+        else blend.toPorterDuffOrNull()?.let { android.graphics.PorterDuffXfermode(it) }+    }+}+ /**  * 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.@@ -2109,6 +2169,11 @@ 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 }+    val softMaskStack = ArrayDeque<SoftMaskFrame>()      fun clipOffsetList(pts: List<Offset>): List<Offset> = pts.map { map(it) } @@ -2145,7 +2210,7 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {             is PdfPrimitive.FillPath -> {                 val path = prim.points.toPath(::map) ?: continue                 if (prim.evenOdd) path.fillType = androidx.compose.ui.graphics.PathFillType.EvenOdd-                drawPath(path, Color(prim.color), style = Fill)+                drawPath(path, Color(prim.color), style = Fill, blendMode = prim.blend.toCompose())             }              is PdfPrimitive.StrokePath -> {@@ -2187,6 +2252,7 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                         join = join,                         pathEffect = pathEffect,                     ),+                    blendMode = prim.blend.toCompose(),                 )             } @@ -2205,11 +2271,13 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                         textStrokePaint.strokeWidth = (prim.strokeWidth * scale).coerceAtLeast(0.5f)                         textStrokePaint.strokeCap = android.graphics.Paint.Cap.ROUND                         textStrokePaint.strokeJoin = android.graphics.Paint.Join.ROUND+                        textStrokePaint.setBlend(prim.blend)                         nativeCanvas.drawText(prim.text, origin.x, origin.y, textStrokePaint)                     }                     if (!isStrokeOnly) {                         textPaint.color = prim.color                         textPaint.textSize = ts+                        textPaint.setBlend(prim.blend)                         nativeCanvas.drawText(prim.text, origin.x, origin.y, textPaint)                     }                 }@@ -2373,9 +2441,62 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                     saveCount--                 }             }++            is PdfPrimitive.SoftMaskPush -> {+                // Open the layer that will hold the masked content.+                nativeCanvas.saveLayer(null, null)+                softMaskStack.addLast(SoftMaskFrame(prim.maskType))+            }++            is PdfPrimitive.SoftMaskContent -> {+                val frame = softMaskStack.lastOrNull()+                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()+                    if (android.os.Build.VERSION.SDK_INT >= 29) {+                        maskPaint.blendMode = android.graphics.BlendMode.DST_IN+                    } else {+                        maskPaint.xfermode =+                            android.graphics.PorterDuffXfermode(android.graphics.PorterDuff.Mode.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(+                            floatArrayOf(+                                0f, 0f, 0f, 0f, 0f,+                                0f, 0f, 0f, 0f, 0f,+                                0f, 0f, 0f, 0f, 0f,+                                0.2126f, 0.7152f, 0.0722f, 0f, 0f,+                            )+                        )+                        lumaPaint.colorFilter = android.graphics.ColorMatrixColorFilter(lm)+                        nativeCanvas.saveLayer(null, lumaPaint)+                        frame.maskLayers = 2+                    }+                }+            }++            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()+                }+            }         }     }     // Ensure balanced restore+    while (softMaskStack.isNotEmpty()) {+        val frame = softMaskStack.removeLast()+        repeat(frame.maskLayers) { nativeCanvas.restore() }+        nativeCanvas.restore()+    }     while (groupSaveCount > 0) {         nativeCanvas.restore()         groupSaveCount--
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 1158bcb962..714a8a5d71 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt@@ -37,6 +37,7 @@ sealed interface PdfPrimitive {         val strokeWidth: Float = 0f,         val advance: Float = size * 0.5f * text.length,         val renderMode: Int = 0,+        val blend: BlendMode = BlendMode.Normal,     ) : PdfPrimitive      /** A filled polygon (one subpath). */@@ -44,6 +45,7 @@ sealed interface PdfPrimitive {         val color: Int,         val evenOdd: Boolean,         val points: List<Offset>,+        val blend: BlendMode = BlendMode.Normal,     ) : PdfPrimitive      /** A stroked polyline (one subpath). [dash] is empty for a solid line. */@@ -56,6 +58,7 @@ sealed interface PdfPrimitive {         val cap: Int = 0,         val join: Int = 0,         val miter: Float = 10f,+        val blend: BlendMode = BlendMode.Normal,     ) : PdfPrimitive      /**@@ -100,6 +103,20 @@ sealed interface PdfPrimitive {      /** Pop transparency group - restores layer */     data object GroupPop : PdfPrimitive++    /**+     * Begin an ExtGState soft-masked region (v5). [maskType] is 0 for an alpha+     * mask or 1 for a luminosity mask. The primitives up to [SoftMaskContent]+     * are the masked content; the primitives from [SoftMaskContent] to+     * [SoftMaskPop] are the mask itself.+     */+    data class SoftMaskPush(val maskType: Int) : PdfPrimitive++    /** Marker: switch from drawing the masked content to drawing the mask (v5). */+    data object SoftMaskContent : PdfPrimitive++    /** End a soft-masked region: composite the mask onto the content (v5). */+    data object SoftMaskPop : PdfPrimitive }  /** A bezier-retentive clip path operation (wire v4), in page space. */
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 0162e9db84..5589ea1d72 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -8,20 +8,24 @@ import java.nio.ByteOrder  * Decodes the compact little-endian primitive buffer produced by the native  * renderer ([PdfNative.renderPage]) into a [SafePdfPage].  *- * Wire format v3 (must stay in sync with `pdf/rust/src/lib.rs` `wire` module):+ * Wire format v5 (must stay in sync with `pdf/rust/src/wire.rs`):  * ```- * header: u32 MAGIC=0x50444657, u32 VERSION=3, f32 pageWidth, f32 pageHeight, u32 primitiveCount+ * header: u32 MAGIC=0x50444657, u32 VERSION=5, f32 pageWidth, f32 pageHeight, u32 primitiveCount  *  Legacy v1 fallback: header is f32 W,H,u32 count (no magic)- *  v2 fallback: VERSION=2 (same as v2 spec)+ *  v2/v3/v4 fallbacks: same layout with fewer trailing per-primitive fields  * 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- *   2 Fill:   u32 argb, u8 evenOdd, u16 nPts, [f32 x, f32 y]...- *   3 Stroke: u32 argb, f32 width, u8 nDash, [f32 dash]..., f32 phase, u8 cap, u8 join, f32 miter, u16 nPts, [f32 x, f32 y]...+ *   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)+ *   2 Fill:   u32 argb, u8 evenOdd, u16 nPts, [f32 x, f32 y]..., 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, f32 y]..., u8 blend (v5)  *   4 Image:  6*f32 ctm, u32 w, u32 h, u8 format, u32 len, [bytes]- *   5 ClipPush: u8 evenOdd, u16 nPts, [f32 x,y]...+ *   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  *   8 GroupPop: empty+ *   9 TextClipApply: empty (v4)+ *   10 SoftMaskPush: u8 maskType (0 alpha, 1 luminosity) (v5)+ *   11 SoftMaskContent: empty (v5)+ *   12 SoftMaskPop: empty (v5)  * ```  * Pure function -> unit-testable with no Android dependencies beyond [Offset].  * Enforces count guards to avoid OOM: max 50k primitives.@@ -37,6 +41,9 @@ object SafePdfParser {     private const val TAG_GROUP_PUSH = 7     private const val TAG_GROUP_POP = 8     private const val TAG_TEXT_CLIP_APPLY = 9+    private const val TAG_SMASK_PUSH = 10+    private const val TAG_SMASK_CONTENT = 11+    private const val TAG_SMASK_POP = 12      private const val PATHOP_MOVE = 0     private const val PATHOP_LINE = 1@@ -44,9 +51,10 @@ object SafePdfParser {     private const val PATHOP_CLOSE = 3      const val WIRE_MAGIC: Int = 0x50444657 // 'PDFW' little-endian as u32-    const val WIRE_VERSION: Int = 4+    const val WIRE_VERSION: Int = 5     private const val WIRE_VERSION_V2 = 2     private const val WIRE_VERSION_V4 = 4+    private const val WIRE_VERSION_V5 = 5     const val MAX_PRIMITIVES = 50000     const val MAX_ANNOTATIONS = 10000 @@ -84,6 +92,7 @@ object SafePdfParser {          val isV2OrV3 = wireVersion >= WIRE_VERSION_V2         val isV4 = wireVersion >= WIRE_VERSION_V4+        val isV5 = wireVersion >= WIRE_VERSION_V5         // 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) {@@ -130,6 +139,10 @@ object SafePdfParser {                         if (buf.remaining() < 1) throw IllegalArgumentException("Text v4 renderMode truncated")                         buf.get().toInt() and 0xFF                     } else 0+                    val blend = if (isV5) {+                        if (buf.remaining() < 1) throw IllegalArgumentException("Text v5 blend truncated")+                        BlendMode.fromCode(buf.get().toInt() and 0xFF)+                    } else BlendMode.Normal                     // For accurate search rect, use advance estimated from size*charCount but refined later with Paint.measureText in Kotlin UI.                     val txt = String(strBytes, Charsets.UTF_8)                     val adv = size * 0.5f * txt.length.coerceAtLeast(1)@@ -143,6 +156,7 @@ object SafePdfParser {                             strokeWidth = strokeWidth,                             advance = adv,                             renderMode = renderMode,+                            blend = blend,                         )                     )                 }@@ -150,7 +164,12 @@ object SafePdfParser {                 TAG_FILL -> {                     val argb = buf.int                     val evenOdd = buf.get().toInt() != 0-                    primitives.add(PdfPrimitive.FillPath(argb, evenOdd, readPoints(buf)))+                    val points = readPoints(buf)+                    val blend = if (isV5) {+                        if (buf.remaining() < 1) throw IllegalArgumentException("Fill v5 blend truncated")+                        BlendMode.fromCode(buf.get().toInt() and 0xFF)+                    } else BlendMode.Normal+                    primitives.add(PdfPrimitive.FillPath(argb, evenOdd, points, blend))                 }                  TAG_STROKE -> {@@ -172,8 +191,13 @@ object SafePdfParser {                     } else {                         cap = 0; join = 0; miter = 10f                     }+                    val points = readPoints(buf)+                    val blend = if (isV5) {+                        if (buf.remaining() < 1) throw IllegalArgumentException("Stroke v5 blend truncated")+                        BlendMode.fromCode(buf.get().toInt() and 0xFF)+                    } else BlendMode.Normal                     primitives.add(-                        PdfPrimitive.StrokePath(argb, strokeWidth, dash, dashPhase, readPoints(buf), cap, join, miter)+                        PdfPrimitive.StrokePath(argb, strokeWidth, dash, dashPhase, points, cap, join, miter, blend)                     )                 } @@ -241,6 +265,20 @@ object SafePdfParser {                     primitives.add(PdfPrimitive.GroupPop)                 } +                TAG_SMASK_PUSH -> {+                    if (buf.remaining() < 1) throw IllegalArgumentException("SoftMaskPush truncated")+                    val maskType = buf.get().toInt() and 0xFF+                    primitives.add(PdfPrimitive.SoftMaskPush(maskType))+                }++                TAG_SMASK_CONTENT -> {+                    primitives.add(PdfPrimitive.SoftMaskContent)+                }++                TAG_SMASK_POP -> {+                    primitives.add(PdfPrimitive.SoftMaskPop)+                }+                 else -> throw IllegalArgumentException("Unknown primitive tag: $tag wireVersion=$wireVersion width=$width")             }         }
pdf/src/main/rust/README.md
diff --git a/pdf/src/main/rust/README.md b/pdf/src/main/rust/README.mdindex 76066cd869..5439194a0d 100644--- a/pdf/src/main/rust/README.md+++ b/pdf/src/main/rust/README.md@@ -4,15 +4,16 @@ Parses PDFs entirely in Rust with [`lopdf`] (no pdfium / no system PDF stack) and reduces each page to plain drawing primitives — text runs (with accurate advance), filled/stroked polygons, raster images (JPEG, JPEG2000 via openjp2, JBIG2 via hayro-jbig2, CCITTFax G3/G4 via the `fax` crate), clipping with bezier-retention, axial/radial and mesh shadings, tiling/shading patterns, Type 3-fonts, and transparency groups — for the "Open PDF (safe)" viewer. Built into-`libpdf_render.so` and called from Kotlin via `PdfNative`.+retention, axial/radial and mesh shadings, tiling/shading patterns (for both+fills and strokes), Type 3 fonts, transparency groups, and ExtGState soft masks —+for the "Open PDF (safe)" viewer. Built into `libpdf_render.so` and called from+Kotlin via `PdfNative`.  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 (v4 — implemented)+## Scope (v5 — implemented)  - **PDF functions** (`functions.rs`): a full evaluator for all four function   types — Type 0 sampled (multilinear interpolation), Type 2 exponential, Type 3@@ -42,13 +43,17 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   axial, Type 3 radial (all using `PdfFunction`), and real mesh shadings —   Type 4 free-form Gouraud (flag-driven triangle strips), Type 5 lattice   (`/VerticesPerRow`), and Type 6/7 Coons/tensor patches subdivided from their-  actual boundary Bézier curves. A byte-accurate `BitReader` handles arbitrary-  `BitsPerCoordinate/Component/Flag`.+  actual boundary Bézier curves. Radial (Type 3) shadings solve the true+  circle-family parameter per pixel (honoring `/Extend` and non-negative radii),+  rather than approximating them as axial. A byte-accurate `BitReader` handles+  arbitrary `BitsPerCoordinate/Component/Flag`. - **Patterns** (`interpret.rs`): PatternType 2 (shading) patterns are rasterized   with the pattern `/Matrix` and clipped to the fill region; PatternType 1   (tiling) patterns replay their content stream tiled across the fill bbox   (colored and uncolored `/PaintType`), bounded by `MAX_PATTERN_RECURSION` and a-  per-pattern tile cap.+  per-pattern tile cap. Both tiling and shading patterns are honored for+  **strokes** too: the stroked path is converted to outline quads and the+  pattern is painted within each segment (`paint_pattern_stroke`). - **Filters** (`filters.rs`): ASCIIHex, ASCII85, RunLength, LZW and Flate, both   now with PNG (Predictor 10–15) **and TIFF (Predictor 2)** support; CCITT   G3/G4; JBIG2 and DCT/JPX passthrough. Decode failures for JPX/CCITT/DCT no@@ -56,11 +61,23 @@ 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 v4**: header `MAGIC 0x50444657 VERSION=4 f32 w,h u32 count`;-  tags 1 Text, 2 Fill, 3 Stroke, 4 Image, 5 ClipPush (now carrying a-  bezier-retentive path-ops section), 6 ClipPop, 7 GroupPush, 8 GroupPop,-  9 TextClipApply. Text carries its render mode. `SafePdfParser.kt` parses v4 and-  keeps v1/v2/v3 as fallbacks.+- **Wire format v5**: header `MAGIC 0x50444657 VERSION=5 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.+- **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).+- **ExtGState soft masks** (`/SMask`): luminosity and alpha soft masks set via+  `gs` are applied around the following Form XObject. Rust brackets the masked+  content and the `/G` group content with SoftMaskPush/Content/Pop; Kotlin+  composites them with nested `saveLayer`s — a `DST_IN` mask layer, plus a+  luminance→alpha `ColorMatrix` layer for luminosity masks. `/SMask /None`+  clears the mask. - **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@@ -98,9 +115,10 @@ cd pdf/src/main/rust cargo test ``` -Covers PDF function evaluation (all four types), mesh-shading rasterization,-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.+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).  [`lopdf`]: https://crates.io/crates/lopdf
pdf/src/main/rust/src/draw.rs
diff --git a/pdf/src/main/rust/src/draw.rs b/pdf/src/main/rust/src/draw.rsindex c698be33ed..be251e5c75 100644--- a/pdf/src/main/rust/src/draw.rs+++ b/pdf/src/main/rust/src/draw.rs@@ -53,12 +53,13 @@ pub(crate) fn emit_stroke(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], g                 join: gs.line_join,                 miter: gs.miter_limit as f32,                 pts: sp.iter().map(|&(x, y)| (x as f32, y as f32)).collect(),+                blend: gs.blend_mode,             });         }     } } -pub(crate) fn emit_fill(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], argb: u32, even_odd: bool, alpha_fill: f64) {+pub(crate) fn emit_fill(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], argb: u32, even_odd: bool, alpha_fill: f64, blend: BlendMode) {     let argb = apply_alpha_to_argb(argb, alpha_fill);     for sp in subpaths {         if sp.len() >= 3 {@@ -66,6 +67,7 @@ pub(crate) fn emit_fill(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], arg                 argb,                 even_odd,                 pts: sp.iter().map(|&(x, y)| (x as f32, y as f32)).collect(),+                blend,             });         }     }@@ -115,6 +117,7 @@ pub(crate) fn show_string(                         stroke_width: None,                         advance: size,                         render_mode: gs.render_mode as u8,+                        blend: gs.blend_mode,                     });                 }             }@@ -168,6 +171,7 @@ pub(crate) fn show_string(                             stroke_argb: if has_stroke { Some(apply_alpha_to_argb(gs.stroke, stroke_alpha)) } else { None },                             stroke_width: if has_stroke { Some(device_stroke_w) } else { None },                             render_mode: rm,+                            blend: gs.blend_mode,                         });                     } else if has_stroke {                         prims.push(Prim::Text {@@ -180,6 +184,7 @@ pub(crate) fn show_string(                             stroke_argb: Some(apply_alpha_to_argb(gs.stroke, stroke_alpha)),                             stroke_width: Some(device_stroke_w),                             render_mode: rm,+                            blend: gs.blend_mode,                         });                     } else if clip_only {                         // Mode 7: no paint, but carry the glyph so Kotlin can add@@ -194,6 +199,7 @@ pub(crate) fn show_string(                             stroke_argb: None,                             stroke_width: None,                             render_mode: 7,+                            blend: gs.blend_mode,                         });                     }                 }
pdf/src/main/rust/src/graphics_state.rs
diff --git a/pdf/src/main/rust/src/graphics_state.rs b/pdf/src/main/rust/src/graphics_state.rsindex d698df2e8f..180c9d350d 100644--- a/pdf/src/main/rust/src/graphics_state.rs+++ b/pdf/src/main/rust/src/graphics_state.rs@@ -82,6 +82,9 @@ pub(crate) struct GraphicsState {     /// Active fill/stroke pattern (object id) when the colorspace is `/Pattern`.     pub(crate) fill_pattern: Option<ObjectId>,     pub(crate) stroke_pattern: Option<ObjectId>,+    /// Active ExtGState soft mask: (`/G` group stream id, mask type where+    /// 0 = alpha, 1 = luminosity). `None` when `/SMask` is `/None`.+    pub(crate) soft_mask: Option<(ObjectId, u8)>, }  impl Default for GraphicsState {@@ -111,6 +114,7 @@ impl Default for GraphicsState {             blend_mode: BlendMode::Normal,             fill_pattern: None,             stroke_pattern: None,+            soft_mask: None,         }     } }
pdf/src/main/rust/src/images.rs
diff --git a/pdf/src/main/rust/src/images.rs b/pdf/src/main/rust/src/images.rsindex b399927450..feac9552da 100644--- a/pdf/src/main/rust/src/images.rs+++ b/pdf/src/main/rust/src/images.rs@@ -734,6 +734,51 @@ pub(crate) fn extract_inline_image(doc: &Document, stream: &lopdf::Stream, _fill     Some(ImageData { w, h, format: 0, data: rgba }) } +/// Radial (Type 3) shading parameter at a point in shading space.+///+/// The gradient is defined by the family of circles C(s) centered at+/// c0 + s·(c1−c0) with radius r0 + s·(r1−r0), for `coords` = [x0 y0 r0 x1 y1 r1].+/// For a point (fx,fy) this returns the largest `s` such that the point lies on+/// C(s) with a non-negative radius, honoring the two `/Extend` flags (`e0` past+/// s<0, `e1` past s>1). Solving |p − c(s)| = r(s) yields the quadratic+/// a·s² − 2b·s + c = 0. Returns `None` when no circle covers the point (the+/// caller leaves that pixel transparent).+pub(crate) fn radial_shading_param(coords: &[f64], e0: bool, e1: bool, fx: f64, fy: f64) -> Option<f64> {+    if coords.len() < 6 { return None; }+    let (x0, y0, r0) = (coords[0], coords[1], coords[2]);+    let (x1, y1, r1) = (coords[3], coords[4], coords[5]);+    let dx = x1 - x0;+    let dy = y1 - y0;+    let dr = r1 - r0;+    let px = fx - x0;+    let py = fy - y0;+    let a = dx*dx + dy*dy - dr*dr;+    let b = px*dx + py*dy + r0*dr;+    let c = px*px + py*py - r0*r0;++    let mut best: Option<f64> = None;+    let mut consider = |s: f64| {+        // The interpolated circle radius must be non-negative.+        if r0 + s*dr < 0.0 { return; }+        // Respect the shading domain unless extended past an end.+        let in_range = (s >= 0.0 && s <= 1.0) || (s < 0.0 && e0) || (s > 1.0 && e1);+        if !in_range { return; }+        best = Some(match best { Some(cur) if cur >= s => cur, _ => s });+    };+    if a.abs() < 1e-9 {+        // Degenerate to a linear equation: -2b·s + c = 0.+        if b.abs() > 1e-12 { consider(c / (2.0*b)); }+    } else {+        let disc = b*b - a*c;+        if disc >= 0.0 {+            let sq = disc.sqrt();+            consider((b + sq)/a);+            consider((b - sq)/a);+        }+    }+    best+}+ pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm: &Mat, cs_resources: &HashMap<Vec<u8>, ObjectId>, size: u32) -> Option<(Mat, u32, u32, Vec<u8>)> {     // A shading may be a plain dictionary (Type 1-3) or a stream (Type 4-7,     // whose mesh data lives in the stream body).@@ -808,19 +853,22 @@ pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm:                     }                 } else { 0.0 }             } else {-                // Radial: coords [x0 y0 r0 x1 y1 r1]; compute t by interpolating distance between circles approx+                // Radial (Type 3): solve for the gradient parameter at (fx,fy).                 if coords.len()>=6 {-                    let x0=coords[0]; let y0=coords[1]; let _r0=coords[2];-                    let x1=coords[3]; let y1=coords[4]; let _r1=coords[5];-                    // Simplified: project onto line between centers-                    let dx = x1 - x0;-                    let dy = y1 - y0;-                    let len2 = dx*dx+dy*dy;-                    let t = if len2<1e-12 { 0.0 } else { ((fx - x0)*dx + (fy - y0)*dy)/len2 };-                    t+                    radial_shading_param(+                        &coords,+                        extend.get(0).copied().unwrap_or(true),+                        extend.get(1).copied().unwrap_or(true),+                        fx, fy,+                    ).unwrap_or(f64::NAN)                 } else { 0.0 }             }; +            // Radial pixels not covered by any circle stay transparent.+            if t.is_nan() {+                continue;+            }+             // Extend handling             let t_clamped = if t<0.0 {                 if extend.get(0).copied().unwrap_or(true) { 0.0 } else {@@ -1244,3 +1292,42 @@ pub(crate) fn read_smask(doc: &Document, dict: &lopdf::Dictionary, w: u32, h: u3     }     Some(alpha) }++#[cfg(test)]+mod radial_tests {+    use super::radial_shading_param;++    // A concentric radial gradient (same center, r0=0..r1=50) must vary with+    // distance from the center — the old axial approximation collapsed it to a+    // single value because the centers coincide.+    #[test]+    fn concentric_radial_varies_with_radius() {+        let coords = [50.0, 50.0, 0.0, 50.0, 50.0, 50.0];+        let center = radial_shading_param(&coords, true, true, 50.0, 50.0).unwrap();+        let mid = radial_shading_param(&coords, true, true, 75.0, 50.0).unwrap();+        let edge = radial_shading_param(&coords, true, true, 100.0, 50.0).unwrap();+        assert!((center - 0.0).abs() < 1e-6, "center s={center}");+        assert!((mid - 0.5).abs() < 1e-6, "mid s={mid}");+        assert!((edge - 1.0).abs() < 1e-6, "edge s={edge}");+        assert!(center < mid && mid < edge);+    }++    // Outside the outer circle with Extend[1]=false there is no covering circle.+    #[test]+    fn outside_without_extend_is_none() {+        let coords = [50.0, 50.0, 0.0, 50.0, 50.0, 50.0];+        assert!(radial_shading_param(&coords, false, false, 200.0, 50.0).is_none());+        // With Extend[1]=true the far point still maps (s>1 allowed).+        let s = radial_shading_param(&coords, false, true, 200.0, 50.0).unwrap();+        assert!(s > 1.0, "expected extended s>1, got {s}");+    }++    // Offset circles (different centers) still resolve on the axis.+    #[test]+    fn offset_circles_resolve_on_axis() {+        let coords = [0.0, 0.0, 10.0, 100.0, 0.0, 10.0];+        // On the segment between centers, near the start circle boundary.+        let s = radial_shading_param(&coords, true, true, 10.0, 0.0).unwrap();+        assert!(s >= 0.0 && s <= 1.0, "s={s}");+    }+}
pdf/src/main/rust/src/interpret.rs
diff --git a/pdf/src/main/rust/src/interpret.rs b/pdf/src/main/rust/src/interpret.rsindex c22c63a67d..00f0a68474 100644--- a/pdf/src/main/rust/src/interpret.rs+++ b/pdf/src/main/rust/src/interpret.rs@@ -290,6 +290,24 @@ pub(crate) fn interpret_content(                                 }                             }                         }+                        // Soft mask: /SMask /None clears; a dict << /S /Luminosity|/Alpha+                        // /G <group stream ref> >> sets a luminosity/alpha soft mask.+                        if let Some(sm_raw) = dict.get(b"SMask").ok() {+                            if let Ok(n) = sm_raw.as_name() {+                                if n == b"None" { gs.soft_mask = None; }+                            } else if let Some(sm) = deref(doc, sm_raw).or(Some(sm_raw)) {+                                if let Ok(smdict) = sm.as_dict() {+                                    let mask_type = match smdict.get(b"S").ok().and_then(|o| o.as_name().ok()) {+                                        Some(b"Luminosity") => 1u8,+                                        _ => 0u8, // Alpha (default)+                                    };+                                    // /G must be an indirect reference to the group stream.+                                    if let Some(Object::Reference(gid)) = smdict.get(b"G").ok() {+                                        gs.soft_mask = Some((*gid, mask_type));+                                    }+                                }+                            }+                        }                     };                     if let Some(&id) = extgstates.get(name) {                         if let Ok(dict) = doc.get_dictionary(id) {@@ -413,7 +431,11 @@ pub(crate) fn interpret_content(                     }                 }                 if !text_only && !oc_stack.last().copied().unwrap_or(false) {-                    if prims.len() < MAX_PRIMITIVES { emit_stroke(prims, &subpaths, &gs); }+                    if let Some(pid) = gs.stroke_pattern {+                        paint_pattern_stroke(doc, pid, &subpaths, &gs, &pattern_base_ctm, prims, depth);+                    } else if prims.len() < MAX_PRIMITIVES {+                        emit_stroke(prims, &subpaths, &gs);+                    }                 }                 subpaths.clear(); clip_path_ops.clear();             }@@ -434,7 +456,7 @@ pub(crate) fn interpret_content(                     if let Some(pid) = gs.fill_pattern {                         paint_pattern_fill(doc, pid, &subpaths, op.operator == "f*", &pattern_base_ctm, gs.fill, prims, depth);                     } else if prims.len() < MAX_PRIMITIVES {-                        emit_fill(prims, &subpaths, gs.fill, op.operator == "f*", gs.alpha_fill);+                        emit_fill(prims, &subpaths, gs.fill, op.operator == "f*", gs.alpha_fill, gs.blend_mode);                     }                 }                 subpaths.clear(); clip_path_ops.clear();@@ -461,9 +483,13 @@ pub(crate) fn interpret_content(                     if let Some(pid) = gs.fill_pattern {                         paint_pattern_fill(doc, pid, &subpaths, op.operator.ends_with('*'), &pattern_base_ctm, gs.fill, prims, depth);                     } else if prims.len() < MAX_PRIMITIVES {-                        emit_fill(prims, &subpaths, gs.fill, op.operator.ends_with('*'), gs.alpha_fill);+                        emit_fill(prims, &subpaths, gs.fill, op.operator.ends_with('*'), gs.alpha_fill, gs.blend_mode);+                    }+                    if let Some(pid) = gs.stroke_pattern {+                        paint_pattern_stroke(doc, pid, &subpaths, &gs, &pattern_base_ctm, prims, depth);+                    } else if prims.len() < MAX_PRIMITIVES {+                        emit_stroke(prims, &subpaths, &gs);                     }-                    if prims.len() < MAX_PRIMITIVES { emit_stroke(prims, &subpaths, &gs); }                 }                 subpaths.clear(); clip_path_ops.clear();             }@@ -549,7 +575,20 @@ pub(crate) fn interpret_content(                                         } else { (false,false,false) }                                     } else { (false,false,false) }                                 };-                                let should_emit_group = is_transparency_group && !text_only && !oc_stack.last().copied().unwrap_or(false) && depth < crate::MAX_PATTERN_RECURSION as u32;+                                // ExtGState soft mask active at this Do: bracket+                                // the form as the masked content and emit the /G+                                // group as the mask. The soft-mask layer provides+                                // isolation, so skip the form's own group push.+                                let active_smask = gs.soft_mask;+                                let use_smask = active_smask.is_some()+                                    && !text_only+                                    && !oc_stack.last().copied().unwrap_or(false)+                                    && prims.len() < crate::MAX_PRIMITIVES+                                    && depth < crate::MAX_PATTERN_RECURSION as u32;+                                if let (true, Some((_g, mtype))) = (use_smask, active_smask) {+                                    prims.push(Prim::SoftMaskPush { mask_type: mtype });+                                }+                                let should_emit_group = is_transparency_group && !use_smask && !text_only && !oc_stack.last().copied().unwrap_or(false) && depth < crate::MAX_PATTERN_RECURSION as u32;                                 if should_emit_group {                                     if prims.len() < crate::MAX_PRIMITIVES && group_depth < 32 {                                         prims.push(Prim::GroupPush { isolated, knockout, alpha: gs.alpha_fill as f32 * gs.alpha_stroke as f32, blend: gs.blend_mode });@@ -559,6 +598,8 @@ pub(crate) fn interpret_content(                                 if let Ok(sub) = Content::decode(&stream_data_with_doc(doc, &stream)) {                                         let mut sub_gs = gs.clone();                                         sub_gs.ctm = mat_mul(&form_matrix, &gs.ctm);+                                        // The mask does not apply to nested Do's inside the masked content.+                                        sub_gs.soft_mask = None;                                         let res_ref = form_res.as_ref().or(resources);                                         interpret_content(                                             doc,@@ -570,6 +611,36 @@ pub(crate) fn interpret_content(                                             text_only,                                         );                                 }+                                // Emit the mask group content, then close the bracket.+                                if let (true, Some((g_id, _mtype))) = (use_smask, active_smask) {+                                    prims.push(Prim::SoftMaskContent);+                                    if let Ok(Object::Stream(mstream)) = doc.get_object(g_id) {+                                        let mmatrix = mstream.dict.get(b"Matrix").ok().and_then(read_matrix_obj).unwrap_or(IDENTITY);+                                        let mres = mstream.dict.get(b"Resources").ok()+                                            .and_then(|o| deref(doc, o))+                                            .and_then(|o| o.as_dict().ok())+                                            .cloned();+                                        if let Ok(msub) = Content::decode(&stream_data_with_doc(doc, mstream)) {+                                            let mut mgs = gs.clone();+                                            mgs.ctm = mat_mul(&mmatrix, &gs.ctm);+                                            mgs.soft_mask = None;+                                            mgs.blend_mode = BlendMode::Normal;+                                            mgs.alpha_fill = 1.0;+                                            mgs.alpha_stroke = 1.0;+                                            let mres_ref = mres.as_ref().or(resources);+                                            interpret_content(+                                                doc,+                                                &msub.operations,+                                                mres_ref,+                                                mgs,+                                                prims,+                                                depth + 1,+                                                text_only,+                                            );+                                        }+                                    }+                                    prims.push(Prim::SoftMaskPop);+                                }                             }                         }                     }@@ -917,6 +988,103 @@ pub(crate) fn uncolored_pattern_argb(comps: &[f64]) -> u32 { /// Paint a pattern fill within the region described by `polys` (device space). /// Handles PatternType 2 (shading) and PatternType 1 (tiling), bounded by /// [`MAX_PATTERN_RECURSION`] and a per-pattern tile cap.+/// Build stroke-outline quadrilaterals (device space) for a set of polyline+/// subpaths, offsetting each segment by `hw` (half the device line width) on+/// both sides, plus a small square at every vertex so joints/caps don't leave+/// gaps. Each quad is painted independently so the segments union correctly.+fn stroke_outline_quads(subpaths: &[Vec<(f64, f64)>], hw: f64) -> Vec<Vec<(f64, f64)>> {+    let mut quads: Vec<Vec<(f64, f64)>> = Vec::new();+    for sp in subpaths {+        if sp.len() < 2 { continue; }+        for w in sp.windows(2) {+            let (x0, y0) = w[0];+            let (x1, y1) = w[1];+            let dx = x1 - x0;+            let dy = y1 - y0;+            let len = (dx*dx + dy*dy).sqrt();+            if len < 1e-9 { continue; }+            let nx = -dy / len * hw;+            let ny = dx / len * hw;+            quads.push(vec![+                (x0 + nx, y0 + ny),+                (x1 + nx, y1 + ny),+                (x1 - nx, y1 - ny),+                (x0 - nx, y0 - ny),+            ]);+        }+        for &(x, y) in sp.iter() {+            quads.push(vec![+                (x - hw, y - hw),+                (x + hw, y - hw),+                (x + hw, y + hw),+                (x - hw, y + hw),+            ]);+        }+    }+    quads+}++/// Paint a tiling/shading pattern along a stroked path. The stroke is converted+/// to outline quads (`stroke_outline_quads`); each quad is clipped independently+/// and the pattern rasterized within it, so the painted region is the union of+/// the segments (matching how a real stroke covers the path).+pub(crate) fn paint_pattern_stroke(+    doc: &Document,+    pattern_id: ObjectId,+    subpaths: &[Vec<(f64, f64)>],+    gs: &GraphicsState,+    pattern_base_ctm: &Mat,+    prims: &mut Vec<Prim>,+    depth: u32,+) {+    if depth >= MAX_PATTERN_RECURSION || prims.len() >= MAX_PRIMITIVES {+        return;+    }+    let obj = match doc.get_object(pattern_id) {+        Ok(o) => o,+        Err(_) => return,+    };+    let dict = match obj {+        Object::Dictionary(d) => d,+        Object::Stream(s) => &s.dict,+        _ => return,+    };+    let ptype = dict.get(b"PatternType").ok().and_then(num).unwrap_or(0.0) as i64;+    let matrix = dict.get(b"Matrix").ok().and_then(read_matrix_obj).unwrap_or(IDENTITY);+    let pmat = mat_mul(&matrix, pattern_base_ctm);++    // Half stroke width in device space (CTM average axis scale).+    let ctm = &gs.ctm;+    let sx = (ctm[0]*ctm[0] + ctm[1]*ctm[1]).sqrt();+    let sy = (ctm[2]*ctm[2] + ctm[3]*ctm[3]).sqrt();+    let scale = (sx + sy) / 2.0;+    let hw = ((gs.line_width * scale) / 2.0).max(0.35);++    let quads = stroke_outline_quads(subpaths, hw);+    for quad in &quads {+        if prims.len() >= MAX_PRIMITIVES { break; }+        if quad.len() < 3 || shoelace_area(quad).abs() < 1e-3 { continue; }+        prims.push(Prim::ClipPush {+            even_odd: false,+            pts: quad.iter().map(|&(x, y)| (x as f32, y as f32)).collect(),+            path_ops: None,+        });+        if ptype == 2 {+            if let Some(shobj) = dict.get(b"Shading").ok().and_then(|o| deref(doc, o)) {+                if let Some((ctm, w, h, data)) = rasterize_shading(doc, shobj, &pmat, &HashMap::new(), 256) {+                    if prims.len() < MAX_PRIMITIVES {+                        prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: 1.0 });+                    }+                }+            }+        } else if ptype == 1 {+            let region = std::slice::from_ref(quad);+            paint_tiling_pattern(doc, obj, dict, &pmat, gs.stroke, region, prims, depth);+        }+        prims.push(Prim::ClipPop);+    }+}+ pub(crate) fn paint_pattern_fill(     doc: &Document,     pattern_id: ObjectId,@@ -1077,3 +1245,33 @@ pub(crate) fn read_rect(doc: &Document, obj: &Object) -> Option<[f64; 4]> {     }     Some(out) }++#[cfg(test)]+mod stroke_pattern_tests {+    use super::stroke_outline_quads;++    // A single horizontal segment yields one segment quad plus two vertex+    // squares, all offset by the half width.+    #[test]+    fn horizontal_segment_quad_offsets_by_half_width() {+        let sp = vec![vec![(0.0, 0.0), (10.0, 0.0)]];+        let quads = stroke_outline_quads(&sp, 2.0);+        // 1 segment quad + 2 vertex squares.+        assert_eq!(quads.len(), 3);+        let seg = &quads[0];+        assert_eq!(seg.len(), 4);+        // Normal to a horizontal segment is vertical: y offset = +/-hw.+        assert!(seg.iter().any(|&(_, y)| (y - 2.0).abs() < 1e-9));+        assert!(seg.iter().any(|&(_, y)| (y + 2.0).abs() < 1e-9));+    }++    // Zero-length segments are skipped (no NaN normals), but the vertex square+    // still covers the point.+    #[test]+    fn degenerate_segment_is_skipped() {+        let sp = vec![vec![(5.0, 5.0), (5.0, 5.0)]];+        let quads = stroke_outline_quads(&sp, 1.0);+        // No segment quad, just the two coincident vertex squares.+        assert_eq!(quads.len(), 2);+    }+}
pdf/src/main/rust/src/model.rs
diff --git a/pdf/src/main/rust/src/model.rs b/pdf/src/main/rust/src/model.rsindex f510c69765..2ebdf77324 100644--- a/pdf/src/main/rust/src/model.rs+++ b/pdf/src/main/rust/src/model.rs@@ -16,11 +16,15 @@ pub(crate) enum Prim {         /// PDF text rendering mode (Tr): 0 fill, 1 stroke, 2 fill+stroke, 3         /// invisible, 4-6 = 0-2 plus add-to-clip, 7 clip-only. Serialized in v4.         render_mode: u8,+        /// Blend mode (from the graphics-state `/BM`). Serialized in v5.+        blend: BlendMode,     },     Fill {         argb: u32,         even_odd: bool,         pts: Vec<(f32, f32)>,+        /// Blend mode (from the graphics-state `/BM`). Serialized in v5.+        blend: BlendMode,     },     Stroke {         argb: u32,@@ -32,6 +36,8 @@ pub(crate) enum Prim {         join: u8,         miter: f32,         pts: Vec<(f32, f32)>,+        /// Blend mode (from the graphics-state `/BM`). Serialized in v5.+        blend: BlendMode,     },     /// A raster image placed by mapping the unit square through `ctm` (PDF image     /// space). `format`: 0 = raw RGBA8888 (`w*h*4` bytes), 1 = JPEG bytes.@@ -65,6 +71,14 @@ pub(crate) enum Prim {         blend: BlendMode,     },     GroupPop,+    /// Begin an ExtGState soft-masked region (v5). `mask_type`: 0 = alpha,+    /// 1 = luminosity. Primitives until `SoftMaskContent` are the masked+    /// content; those from `SoftMaskContent` to `SoftMaskPop` are the mask.+    SoftMaskPush { mask_type: u8 },+    /// Marker: switch from masked content to mask drawing (v5).+    SoftMaskContent,+    /// End a soft-masked region; composite the mask onto the content (v5).+    SoftMaskPop, }  /// Path operation for bezier-retentive clip (Phase 5 fidelity).@@ -111,6 +125,9 @@ pub(crate) fn scale_prim_alpha(prim: &mut Prim, alpha_mul: f64) {         Prim::TextClipApply => {},         Prim::GroupPush { alpha: ga, .. } => { let cur = *ga as f64; *ga = (cur * alpha_mul.clamp(0.0,1.0)) as f32; },         Prim::GroupPop => {},+        Prim::SoftMaskPush { .. } => {},+        Prim::SoftMaskContent => {},+        Prim::SoftMaskPop => {},     } } 
pdf/src/main/rust/src/wire.rs
diff --git a/pdf/src/main/rust/src/wire.rs b/pdf/src/main/rust/src/wire.rsindex db827d625e..30a301cf3c 100644--- a/pdf/src/main/rust/src/wire.rs+++ b/pdf/src/main/rust/src/wire.rs@@ -1,7 +1,7 @@ use crate::*;      const WIRE_MAGIC: u32 = 0x50444657; // 'PDFW'-    const WIRE_VERSION: u32 = 4;+    const WIRE_VERSION: u32 = 5;     #[allow(dead_code)]     const WIRE_VERSION_V2: u32 = 2;     const TAG_TEXT: u8 = 1;@@ -13,20 +13,23 @@ use crate::*;     const TAG_GROUP_PUSH: u8 = 7;     const TAG_GROUP_POP: u8 = 8;     const TAG_TEXT_CLIP_APPLY: u8 = 9;+    const TAG_SMASK_PUSH: u8 = 10;+    const TAG_SMASK_CONTENT: u8 = 11;+    const TAG_SMASK_POP: u8 = 12;      const PATHOP_MOVE: u8 = 0;     const PATHOP_LINE: u8 = 1;     const PATHOP_CUBIC: u8 = 2;     const PATHOP_CLOSE: u8 = 3; -    /// Serialize a page into a compact little-endian buffer v4:+    /// Serialize a page into a compact little-endian buffer v5:     ///     /// ```text-    /// header: u32 MAGIC=0x50444657, u32 VERSION=4, f32 pageWidth, f32 pageHeight, u32 primitiveCount+    /// header: u32 MAGIC=0x50444657, u32 VERSION=5, f32 pageWidth, f32 pageHeight, u32 primitiveCount     /// per primitive: u8 tag, then payload-    ///   1 Text:   f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode  (renderMode is v4)-    ///   2 Fill:   u32 argb, u8 evenOdd, u16 nPts, [f32 x, f32 y]...-    ///   3 Stroke: u32 argb, f32 width, u8 nDash, [f32 dash]..., f32 phase, u8 cap, u8 join, f32 miter, u16 nPts, [f32 x, f32 y]...+    ///   1 Text:   f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5)+    ///   2 Fill:   u32 argb, u8 evenOdd, u16 nPts, [f32 x, f32 y]..., 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, f32 y]..., u8 blend (v5)     ///   4 Image:  6×f32 ctm, u32 w, u32 h, u8 format, u32 len, [bytes] (format 0=RGBA8888, 1=JPEG)     ///   5 ClipPush: u8 evenOdd, u16 nPts, [f32 x,y]..., u16 nPathOps, [u8 kind, coords]...  (path-ops section is v4)     ///              path-op kinds: 0 Move(2f32) 1 Line(2f32) 2 Cubic(6f32) 3 Close(0)@@ -34,7 +37,10 @@ use crate::*;     ///   7 GroupPush: u8 isolated, u8 knockout, f32 alpha, u8 blend     ///   8 GroupPop: empty     ///   9 TextClipApply: empty (v4)-    /// v1 legacy (no magic), v2 and v3 remain backward compatible for cached pages.+    ///   10 SoftMaskPush: u8 maskType (0 alpha, 1 luminosity) (v5)+    ///   11 SoftMaskContent: empty (v5)+    ///   12 SoftMaskPop: empty (v5)+    /// v1 legacy (no magic), v2/v3/v4 remain backward compatible for cached pages.     /// ```     pub fn serialize(page: &PageData) -> Vec<u8> {         let mut buf = Vec::new();@@ -45,7 +51,7 @@ use crate::*;         buf.extend_from_slice(&(page.prims.len() as u32).to_le_bytes());         for prim in &page.prims {             match prim {-                Prim::Text { x, y, size, argb, text, stroke_argb, stroke_width, advance: _, render_mode, .. } => {+                Prim::Text { x, y, size, argb, text, stroke_argb, stroke_width, advance: _, render_mode, blend } => {                     buf.push(TAG_TEXT);                     buf.extend_from_slice(&x.to_le_bytes());                     buf.extend_from_slice(&y.to_le_bytes());@@ -65,14 +71,16 @@ use crate::*;                         buf.extend_from_slice(&0f32.to_le_bytes());                     }                     buf.push(*render_mode); // v4+                    buf.push(*blend as u8); // v5                 }-                Prim::Fill { argb, even_odd, pts } => {+                Prim::Fill { argb, even_odd, pts, blend } => {                     buf.push(TAG_FILL);                     buf.extend_from_slice(&argb.to_le_bytes());                     buf.push(if *even_odd { 1 } else { 0 });                     write_points(&mut buf, pts);+                    buf.push(*blend as u8); // v5                 }-                Prim::Stroke { argb, width, dash, dash_phase, cap, join, miter, pts } => {+                Prim::Stroke { argb, width, dash, dash_phase, cap, join, miter, pts, blend } => {                     buf.push(TAG_STROKE);                     buf.extend_from_slice(&argb.to_le_bytes());                     buf.extend_from_slice(&width.to_le_bytes());@@ -86,6 +94,7 @@ use crate::*;                     buf.push(*join);                     buf.extend_from_slice(&miter.to_le_bytes());                     write_points(&mut buf, pts);+                    buf.push(*blend as u8); // v5                 }                 Prim::Image { ctm, w, h, format, data, alpha: _ } => {                     buf.push(TAG_IMAGE);@@ -120,6 +129,16 @@ use crate::*;                 Prim::GroupPop => {                     buf.push(TAG_GROUP_POP);                 }+                Prim::SoftMaskPush { mask_type } => {+                    buf.push(TAG_SMASK_PUSH);+                    buf.push(*mask_type);+                }+                Prim::SoftMaskContent => {+                    buf.push(TAG_SMASK_CONTENT);+                }+                Prim::SoftMaskPop => {+                    buf.push(TAG_SMASK_POP);+                }             }         }         buf@@ -219,11 +238,13 @@ use crate::*;                         stroke_width: Some(0.5),                         advance: 12.0,                         render_mode: 0,+                        blend: BlendMode::Multiply,                     },                     Prim::Fill {                         argb: 0xFFAABBCC,                         even_odd: true,                         pts: vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)],+                        blend: BlendMode::Screen,                     },                     Prim::Stroke {                         argb: 0xFF010203,@@ -234,6 +255,7 @@ use crate::*;                         join: 1,                         miter: 10.0,                         pts: vec![(3.0, 4.0), (5.0, 6.0)],+                        blend: BlendMode::Normal,                     },                     Prim::ClipPush {                         even_odd: false,@@ -246,6 +268,9 @@ use crate::*;                     },                     Prim::ClipPop,                     Prim::TextClipApply,+                    Prim::SoftMaskPush { mask_type: 1 },+                    Prim::SoftMaskContent,+                    Prim::SoftMaskPop,                 ],             };             let buf = serialize(&page);@@ -254,7 +279,7 @@ use crate::*;             assert_eq!(r.u32(), WIRE_VERSION);             assert_eq!(r.f32(), 612.0);             assert_eq!(r.f32(), 792.0);-            assert_eq!(r.u32(), 6);+            assert_eq!(r.u32(), 9);              assert_eq!(r.u8(), TAG_TEXT);             assert_eq!(r.f32(), 10.0);@@ -269,12 +294,14 @@ use crate::*;             assert_eq!(r.u32(), 0xFF445566);             assert!((r.f32() - 0.5).abs() < 1e-6);             assert_eq!(r.u8(), 0); // render_mode (v4)+            assert_eq!(r.u8(), BlendMode::Multiply as u8); // blend (v5)              assert_eq!(r.u8(), TAG_FILL);             assert_eq!(r.u32(), 0xFFAABBCC);             assert_eq!(r.u8(), 1); // even-odd             assert_eq!(r.u16(), 3);             r.pos += 3 * 8;+            assert_eq!(r.u8(), BlendMode::Screen as u8); // blend (v5)              assert_eq!(r.u8(), TAG_STROKE);             assert_eq!(r.u32(), 0xFF010203);@@ -288,6 +315,7 @@ use crate::*;             assert!((r.f32() - 10.0).abs() < 1e-4);             assert_eq!(r.u16(), 2);             r.pos += 2*8;+            assert_eq!(r.u8(), BlendMode::Normal as u8); // blend (v5)              assert_eq!(r.u8(), TAG_CLIP_PUSH);             assert_eq!(r.u8(), 0); // evenOdd false@@ -304,5 +332,9 @@ use crate::*;              assert_eq!(r.u8(), TAG_CLIP_POP);             assert_eq!(r.u8(), TAG_TEXT_CLIP_APPLY);+            assert_eq!(r.u8(), TAG_SMASK_PUSH);+            assert_eq!(r.u8(), 1); // mask_type luminosity+            assert_eq!(r.u8(), TAG_SMASK_CONTENT);+            assert_eq!(r.u8(), TAG_SMASK_POP);         }     }