Modern Apps git

← Modern-Apps.git

pdf: add even more features

Commit
681c5bd16f9282c4ed20c8fb732cebfc48f38621
Author
Vayun Mathur <[email protected]>
When
2026-07-25 04:56 UTC (4 months ago)
Parents
1fd0472

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 df80b8dfee..c3648c6aae 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -1320,31 +1320,25 @@ private fun TextSelectionLayer(page: SafePdfPage, ch: Float, scale: Float) {         for (prim in page.primitives) {             if (prim !is PdfPrimitive.Text || prim.text.isEmpty()) continue             tmpPaint.textSize = prim.size * scale-            // Use actual unicode string measurement for width instead of size*0.5f approximation per plan 19-            // Measure whole run then split proportionally using per-glyph advance if available             val textStr = prim.text+            // Rust emits one glyph per Text prim with `advance` = that glyph's+            // true device-space advance (from /Widths|/W, Tc/Tw/Tz). Use it for+            // both stepping and glyph width; fall back to measured width only for+            // multi-char runs (the font-less fallback path).             val measuredTotal = if (textStr.isNotEmpty()) tmpPaint.measureText(textStr) else prim.size * 0.5f-            // Prefer prim.advance if >0 (from Rust accurate glyph advance via /Widths /W/Tz)-            // prim.advance is per-glyph? In our Rust we emitted per-glyph advance as glyph_device_adv. For multi-char string (ligature) we have per-prim not per-char? We emitted per glyph but text may still be multi-char for ligatures -> we treat advance as total for that prim.-            val totalAdvancePageSpace = prim.advance * textStr.length.coerceAtLeast(1) // Rust advance currently per glyph? For per-glyph emission, each prim has 1 char and advance=size, so multiply by len is ok-            // For text selection, we compute per-glyph width via measured width divided by char count, but also consider Tz (h_scale) already in advance.             val perGlyphMeasured = if (textStr.isNotEmpty()) measuredTotal / textStr.length else prim.size * 0.5f * scale-            // Use max of measured and accurate Rust advance for fidelity             var curPxPage = prim.origin.x-            for ((idx, c) in textStr.withIndex()) {-                // glyph origin+            for (c in textStr) {                 val px = curPxPage-                // width of this glyph-                val cwMeasured = perGlyphMeasured // canvas space already+                val singleGlyph = textStr.length == 1+                val cw = if (singleGlyph) prim.advance * scale else perGlyphMeasured+                val stepPage = if (singleGlyph) prim.advance else perGlyphMeasured / scale                 val left = px * scale-                val right = left + cwMeasured+                val right = left + cw                 val baseline = ch - prim.origin.y * scale                 val top = baseline - prim.size * scale-                // ch as String for ligatures (though per-glyph emission has single char, but preserve ligature handling)                 list.add(Triple(-prim.origin.y, px, SelGlyph(c.toString(), left, top, right, baseline)))-                // Advance via Rust accurate advance (advance is per glyph? For per-glyph emission we have one glyph per prim, so its advance is the glyph's width)-                // For multi-char prim (if we later emit runs), we should split advance evenly-                curPxPage += prim.advance // page space advance+                curPxPage += stepPage             }         }         list.sortWith(compareBy({ it.first }, { it.second }))@@ -1789,7 +1783,7 @@ private fun FormFieldOverlay(                 DisposableEffect(field.id) {                     onDispose {                         if (text != field.value) {-                            scope.launch { document.setTextField(index, field.id, text); onEdited() }+                            scope.launch { document.setChoiceField(index, field.id, text); onEdited() }                         }                     }                 }
pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.ktindex 6499097d1c..f2a61a6d45 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt@@ -161,12 +161,17 @@ object PdfNative {      external fun setCheckbox(handle: Long, widgetId: Long, on: Boolean): Boolean +    external fun setChoiceField(handle: Long, widgetId: Long, value: String): Boolean+     /** Serialize the modified document to PDF bytes, or null on failure. */     external fun saveDocument(handle: Long): ByteArray?      /** Build a signature-ready PDF (placeholder /ByteRange + /Contents) for signing. */     external fun prepareSignature(handle: Long, name: String, contentsBytes: Int): ByteArray? +    /** Detached CMS/PKCS#7 signature (self-signed RSA-2048, SHA-256) over [content]. */+    external fun signCms(content: ByteArray, name: String): ByteArray?+     /** Serialize with streams compressed + unused objects pruned, or null. */     external fun saveCompressed(handle: Long): ByteArray? 
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 9fd10cae40..0ba1533b15 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -168,6 +168,11 @@ class SafePdfDocument private constructor(             PdfNative.setCheckbox(handle, widgetId, on).also { invalidate(index) }         } +    suspend fun setChoiceField(index: Int, widgetId: Long, value: String): Boolean =+        withContext(Dispatchers.IO) {+            PdfNative.setChoiceField(handle, widgetId, value).also { invalidate(index) }+        }+     /** Serialize the (possibly edited) document to PDF bytes. */     suspend fun save(): ByteArray? = withContext(Dispatchers.IO) { PdfNative.saveDocument(handle) } 
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 69472966ff..42f09d9f46 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -51,11 +51,12 @@ object SafePdfParser {     private const val PATHOP_CLOSE = 3      const val WIRE_MAGIC: Int = 0x50444657 // 'PDFW' little-endian as u32-    const val WIRE_VERSION: Int = 6+    const val WIRE_VERSION: Int = 7     private const val WIRE_VERSION_V2 = 2     private const val WIRE_VERSION_V4 = 4     private const val WIRE_VERSION_V5 = 5     private const val WIRE_VERSION_V6 = 6+    private const val WIRE_VERSION_V7 = 7     const val MAX_PRIMITIVES = 50000     const val MAX_ANNOTATIONS = 10000 @@ -95,6 +96,7 @@ object SafePdfParser {         val isV4 = wireVersion >= WIRE_VERSION_V4         val isV5 = wireVersion >= WIRE_VERSION_V5         val isV6 = wireVersion >= WIRE_VERSION_V6+        val isV7 = wireVersion >= WIRE_VERSION_V7         // 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) {@@ -145,9 +147,15 @@ object SafePdfParser {                         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)+                    // v7 carries the true device-space glyph advance; older wires+                    // fall back to the size*0.5*len heuristic.+                    val adv = if (isV7) {+                        if (buf.remaining() < 4) throw IllegalArgumentException("Text v7 advance truncated")+                        buf.float+                    } else {+                        size * 0.5f * txt.length.coerceAtLeast(1)+                    }                     primitives.add(                         PdfPrimitive.Text(                             origin = Offset(x, y),
pdf/src/main/rust/Cargo.lock
diff --git a/pdf/src/main/rust/Cargo.lock b/pdf/src/main/rust/Cargo.lockindex 47d98d8ce6..8b8bacfb79 100644--- a/pdf/src/main/rust/Cargo.lock+++ b/pdf/src/main/rust/Cargo.lock@@ -34,6 +34,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+ [[package]] name = "bitflags" version = "1.3.2"@@ -140,6 +146,27 @@ dependencies = [  "inout", ] +[[package]]+name = "cms"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730"+dependencies = [+ "aes",+ "cbc",+ "cipher",+ "const-oid",+ "der",+ "rsa",+ "sha1",+ "sha2",+ "sha3",+ "signature",+ "spki",+ "x509-cert",+ "zeroize",+]+ [[package]] name = "combine" version = "4.6.7"@@ -150,6 +177,12 @@ dependencies = [  "memchr", ] +[[package]]+name = "const-oid"+version = "0.9.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"+ [[package]] name = "core-foundation-sys" version = "0.8.7"@@ -206,6 +239,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [  "generic-array",+ "rand_core 0.6.4",  "typenum", ] @@ -240,6 +274,30 @@ dependencies = [  "thiserror 2.0.18", ] +[[package]]+name = "der"+version = "0.7.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"+dependencies = [+ "const-oid",+ "der_derive",+ "flagset",+ "pem-rfc7468",+ "zeroize",+]++[[package]]+name = "der_derive"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+ [[package]] name = "deranged" version = "0.5.8"@@ -253,6 +311,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [  "block-buffer",+ "const-oid",  "crypto-common", ] @@ -298,6 +357,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]]+name = "flagset"+version = "0.4.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"+ [[package]] name = "flate2" version = "1.1.9"@@ -342,6 +407,17 @@ dependencies = [  "version_check", ] +[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi",+]+ [[package]] name = "getrandom" version = "0.3.4"@@ -531,12 +607,36 @@ dependencies = [  "wasm-bindgen", ] +[[package]]+name = "keccak"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"+dependencies = [+ "cpufeatures",+]++[[package]]+name = "lazy_static"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"+dependencies = [+ "spin",+]+ [[package]] name = "libc" version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+ [[package]] name = "log" version = "0.4.33"@@ -563,7 +663,7 @@ dependencies = [  "md-5",  "nom",  "nom_locate",- "rand",+ "rand 0.9.4",  "rangemap",  "rayon",  "serde",@@ -620,12 +720,47 @@ dependencies = [  "nom", ] +[[package]]+name = "num-bigint-dig"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7"+dependencies = [+ "lazy_static",+ "libm",+ "num-integer",+ "num-iter",+ "num-traits",+ "rand 0.8.7",+ "smallvec",+ "zeroize",+]+ [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]]+name = "num-integer"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-iter"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"+dependencies = [+ "num-integer",+ "num-traits",+]+ [[package]] name = "num-traits" version = "0.2.19"@@ -633,6 +768,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [  "autocfg",+ "libm", ]  [[package]]@@ -661,6 +797,9 @@ version = "0.1.0" dependencies = [  "aes",  "cbc",+ "cms",+ "const-oid",+ "der",  "fax",  "flate2",  "hayro-jbig2",@@ -669,8 +808,21 @@ dependencies = [  "lopdf",  "md-5",  "openjp2",+ "rand 0.8.7",+ "rsa",  "sha2",+ "spki",  "weezl",+ "x509-cert",+]++[[package]]+name = "pem-rfc7468"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"+dependencies = [+ "base64ct", ]  [[package]]@@ -679,6 +831,27 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]]+name = "pkcs1"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"+dependencies = [+ "der",+ "pkcs8",+ "spki",+]++[[package]]+name = "pkcs8"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"+dependencies = [+ "der",+ "spki",+]+ [[package]] name = "portable-atomic" version = "1.13.1"@@ -733,14 +906,35 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]]+name = "rand"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a"+dependencies = [+ "libc",+ "rand_chacha 0.3.1",+ "rand_core 0.6.4",+]+ [[package]] name = "rand" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" dependencies = [- "rand_chacha",- "rand_core",+ "rand_chacha 0.9.0",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core 0.6.4", ]  [[package]]@@ -750,7 +944,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [  "ppv-lite86",- "rand_core",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom 0.2.17", ]  [[package]]@@ -759,7 +962,7 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" dependencies = [- "getrandom",+ "getrandom 0.3.4", ]  [[package]]@@ -788,6 +991,27 @@ dependencies = [  "crossbeam-utils", ] +[[package]]+name = "rsa"+version = "0.9.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"+dependencies = [+ "const-oid",+ "digest",+ "num-bigint-dig",+ "num-integer",+ "num-traits",+ "pkcs1",+ "pkcs8",+ "rand_core 0.6.4",+ "sha2",+ "signature",+ "spki",+ "subtle",+ "zeroize",+]+ [[package]] name = "rustversion" version = "1.0.23"@@ -833,6 +1057,17 @@ dependencies = [  "syn", ] +[[package]]+name = "sha1"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]+ [[package]] name = "sha2" version = "0.10.9"@@ -844,12 +1079,32 @@ dependencies = [  "digest", ] +[[package]]+name = "sha3"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874"+dependencies = [+ "digest",+ "keccak",+]+ [[package]] name = "shlex" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]]+name = "signature"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"+dependencies = [+ "digest",+ "rand_core 0.6.4",+]+ [[package]] name = "simd-adler32" version = "0.3.9"@@ -868,6 +1123,22 @@ version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +[[package]]+name = "spin"+version = "0.9.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"++[[package]]+name = "spki"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"+dependencies = [+ "base64ct",+ "der",+]+ [[package]] name = "sprintf" version = "0.1.4"@@ -885,6 +1156,12 @@ dependencies = [  "unicode-properties", ] +[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+ [[package]] name = "syn" version = "2.0.118"@@ -981,6 +1258,27 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +[[package]]+name = "tls_codec"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"+dependencies = [+ "tls_codec_derive",+ "zeroize",+]++[[package]]+name = "tls_codec_derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]+ [[package]] name = "typenum" version = "1.20.1"@@ -1030,6 +1328,12 @@ dependencies = [  "winapi-util", ] +[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"+ [[package]] name = "wasip2" version = "1.0.4+wasi-0.2.12"@@ -1239,6 +1543,20 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]]+name = "x509-cert"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"+dependencies = [+ "const-oid",+ "der",+ "sha1",+ "signature",+ "spki",+ "tls_codec",+]+ [[package]] name = "zerocopy" version = "0.8.53"@@ -1258,3 +1576,23 @@ dependencies = [  "quote",  "syn", ]++[[package]]+name = "zeroize"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]
pdf/src/main/rust/Cargo.toml
diff --git a/pdf/src/main/rust/Cargo.toml b/pdf/src/main/rust/Cargo.tomlindex 811b2717b2..767620e77a 100644--- a/pdf/src/main/rust/Cargo.toml+++ b/pdf/src/main/rust/Cargo.toml@@ -22,7 +22,16 @@ openjp2 = "0.6" md-5 = "0.10" aes = "0.8" cbc = { version = "0.1", features = ["alloc"] }-sha2 = "0.10"+sha2 = { version = "0.10", features = ["oid"] }++# Detached CMS/PKCS#7 signing (replaces Bouncy Castle on the Kotlin side).+rsa = { version = "0.9", features = ["sha2"] }+rand = "0.8"+x509-cert = { version = "0.2", features = ["builder"] }+cms = { version = "0.2", features = ["builder"] }+der = { version = "0.7", features = ["alloc", "oid"] }+spki = "0.7"+const-oid = { version = "0.9", features = ["db"] }  [profile.release] opt-level = 3
pdf/src/main/rust/README.md
diff --git a/pdf/src/main/rust/README.md b/pdf/src/main/rust/README.mdindex 5439194a0d..4c0bad4fae 100644--- a/pdf/src/main/rust/README.md+++ b/pdf/src/main/rust/README.md@@ -23,7 +23,7 @@ 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`, **Type 1 `/FontFile`** clear-text+  encoding recovery: TrueType `cmap` (formats 0/4/6/10/12/13), **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   glyph advance from `/Widths`/`/W`/`/DW` + `Tc`/`Tw`/`Th`.@@ -38,15 +38,23 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   function type, all N inputs), plus Lab, CalRGB/CalGray, ICCBased (alternate),   and Indexed. **Raster image samples** are converted through the same   colorspace machinery (with LUTs for single-component and indexed images), so-  Separation/DeviceN/Lab/ICC images are colored correctly.+  Separation/DeviceN/Lab/ICC images are colored correctly. Image transparency+  covers `/SMask` (soft mask, with `/Matte` un-premultiplication), explicit+  stencil `/Mask` images, and color-key masking compared against pre-conversion+  samples (correct for CMYK/DeviceN, not just RGB). CMYK/YCCK JPEGs (including+  Adobe APP14 inverted CMYK) are decoded in Rust; JPX honors its enumerated+  color space (gray/RGB/YCC/CMYK + alpha). - **Shadings** (`images.rs` + `shading.rs`): Type 1 (function-based), Type 2   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. Radial (Type 3) shadings solve the true+  actual boundary Bézier curves — Type 7 uses the full bicubic tensor surface+  from its 4 interior control points. 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`.+  arbitrary `BitsPerCoordinate/Component/Flag`. Axial/radial/function shadings+  are rasterized at a resolution derived from their device footprint (sharp when+  zoomed) and, when they lack a `/BBox`, cover the current clip extent. - **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@@ -55,9 +63,10 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   **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-  longer fall through to reinterpreting encoded bytes as raw samples.+  now with PNG (Predictor 10–15) **and TIFF (Predictor 2, all of 1/2/4/8/16-bit)**+  support; CCITT G3 (1-D) / G4 (2-D); JBIG2 and DCT/JPX passthrough. Decode+  failures for JPX/CCITT/DCT no longer fall through to reinterpreting encoded+  bytes as raw samples. - **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.@@ -73,11 +82,17 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   (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+  `gs` apply to all subsequent drawing while active — fills, strokes, text,+  images, shadings, and Form XObjects — not only forms. Rust brackets each+  masked draw with SoftMaskPush/Content/Pop, rendering the `/G` group at the CTM+  in effect when the mask was set; a `/BC` backdrop (luminosity masks) is painted+  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.+  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. - **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@@ -87,7 +102,13 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   exact. - **Annotations / forms**: `subtype_code` covers the full ISO 32000 annotation   subtype set; text-field appearance regeneration honors `/Q` alignment,-  multiline wrapping and comb (`/MaxLen`) fields, alongside checkboxes.+  multiline wrapping and comb (`/MaxLen`) fields, alongside checkboxes,+  **radio-button groups** (setting one clears its siblings and updates the parent+  `/V`) and **Choice fields** (records `/V` + the matched `/Opt` index in `/I`+  with a regenerated appearance). Annotations that ship without an `/AP` stream+  get a **synthesized appearance** for the common types — Square, Circle, Line,+  Ink, Highlight, Underline and StrikeOut (via `/QuadPoints`, `/C`, `/IC`,+  `/BS`).  ## Genuinely unsupported (documented, not silently skipped) @@ -98,10 +119,35 @@ UTF-8 text, so Kotlin never touches the raw PDF bytes.   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).+- **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.  ## Prerequisites (local + CI) 
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 9dd5b0838c..81b9318244 100644--- a/pdf/src/main/rust/src/annotations.rs+++ b/pdf/src/main/rust/src/annotations.rs@@ -67,10 +67,14 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:     };      // Resolve the normal appearance: /AP /N is either a stream or a subdictionary-    // of appearance states selected by /AS.+    // of appearance states selected by /AS. When absent, synthesize a basic+    // appearance for common markup/shape annotation types.     let ap = match dict.get(b"AP").ok().and_then(|o| deref(doc, o)) {         Some(Object::Dictionary(d)) => d,-        _ => return,+        _ => {+            synthesize_annotation_appearance(doc, dict, rect, base, prims);+            return;+        }     };     let normal = match ap.get(b"N").ok().and_then(|o| deref(doc, o)) {         Some(Object::Stream(s)) => s,@@ -127,6 +131,148 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:     } } +/// 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()?;+    let c: Vec<f64> = arr.iter().filter_map(num).collect();+    match c.len() {+        1 => Some(gray_to_argb(c[0])),+        3 => Some(rgb_to_argb(c[0], c[1], c[2])),+        4 => Some(cmyk_to_argb(c[0], c[1], c[2], c[3])),+        _ => None,+    }+}++/// Border width from `/BS /W` (preferred) or the legacy `/Border` array [_,_,W].+fn annot_border_width(doc: &Document, dict: &lopdf::Dictionary) -> f64 {+    if let Some(w) = dict.get(b"BS").ok().and_then(|o| deref(doc, o))+        .and_then(|o| o.as_dict().ok())+        .and_then(|bs| bs.get(b"W").ok()).and_then(num) {+        return w;+    }+    if let Some(Object::Array(b)) = dict.get(b"Border").ok().and_then(|o| deref(doc, o)) {+        if let Some(w) = b.get(2).and_then(num) { return w; }+    }+    1.0+}++/// 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.+pub(crate) fn synthesize_annotation_appearance(+    doc: &Document,+    dict: &lopdf::Dictionary,+    rect: [f64; 4],+    base: &Mat,+    prims: &mut Vec<Prim>,+) {+    let subtype = match dict.get(b"Subtype").ok().and_then(|o| o.as_name().ok()) {+        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 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).+    let scale = ((base[0]*base[0]+base[1]*base[1]).sqrt() + (base[2]*base[2]+base[3]*base[3]).sqrt()) / 2.0;++    let mut gs = GraphicsState::default();+    gs.ctm = *base;+    gs.line_width = bw.max(0.5);+    gs.alpha_fill = ca;+    gs.alpha_stroke = ca;++    // QuadPoints (text markup): 8 numbers per quad.+    let quads: Vec<[(f64,f64);4]> = dict.get(b"QuadPoints").ok()+        .and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok())+        .map(|a| {+            let v: Vec<f64> = a.iter().filter_map(num).collect();+            v.chunks_exact(8).map(|q| [(q[0],q[1]),(q[2],q[3]),(q[4],q[5]),(q[6],q[7])]).collect()+        }).unwrap_or_default();++    match subtype.as_slice() {+        b"Square" => {+            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"Circle" => {+            // Approximate the inscribed ellipse with a polygon.+            let (cx, cy) = ((rect[0]+rect[2])/2.0, (rect[1]+rect[3])/2.0);+            let (rx, ry) = ((rect[2]-rect[0]).abs()/2.0, (rect[3]-rect[1]).abs()/2.0);+            let poly: Vec<(f64,f64)> = (0..48).map(|i| {+                let t = i as f64 / 48.0 * std::f64::consts::TAU;+                dev(cx + rx*t.cos(), cy + ry*t.sin())+            }).collect();+            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"Line" => {+            if let Some(Object::Array(l)) = dict.get(b"L").ok().and_then(|o| deref(doc, o)) {+                let n: Vec<f64> = l.iter().filter_map(num).collect();+                if n.len() >= 4 {+                    let seg = vec![dev(n[0],n[1]), dev(n[2],n[3])];+                    let mut sgs = gs.clone(); sgs.stroke = stroke.unwrap_or(0xFF00_0000);+                    emit_stroke(prims, std::slice::from_ref(&seg), &sgs);+                }+            }+        }+        b"Ink" => {+            if let Some(Object::Array(paths)) = dict.get(b"InkList").ok().and_then(|o| deref(doc, o)) {+                let mut sgs = gs.clone(); sgs.stroke = stroke.unwrap_or(0xFF00_0000);+                for p in paths {+                    let n: Vec<f64> = p.as_array().map(|a| a.iter().filter_map(num).collect()).unwrap_or_default();+                    let pts: Vec<(f64,f64)> = n.chunks_exact(2).map(|c| dev(c[0], c[1])).collect();+                    if pts.len() >= 2 { emit_stroke(prims, std::slice::from_ref(&pts), &sgs); }+                }+            }+        }+        b"Highlight" => {+            let color = stroke.unwrap_or(0xFFFF_FF00); // default yellow+            for q in &quads {+                let poly: Vec<(f64,f64)> = q.iter().map(|&(x,y)| dev(x,y)).collect();+                // QuadPoint ordering varies; use the convex bbox to be safe.+                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);+            }+        }+        b"Underline" | b"StrikeOut" => {+            let color = stroke.unwrap_or(0xFF00_0000);+            let mut sgs = gs.clone(); sgs.stroke = color;+            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[3].max(bx[1]) };+                let seg = vec![(bx[0], y), (bx[2], y)];+                emit_stroke(prims, std::slice::from_ref(&seg), &sgs);+            }+        }+        _ => {}+    }+}++/// Device-space bounding box [x0,y0,x1,y1] of a polygon.+fn bbox_of(poly: &[(f64,f64)]) -> [f64;4] {+    let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY];+    for &(x,y) in poly {+        b[0]=b[0].min(x); b[1]=b[1].min(y); b[2]=b[2].max(x); b[3]=b[3].max(y);+    }+    b+}+ // --------------------------------------------------------------------------- // Editing: annotations, form filling, and save (lopdf write-back) // ---------------------------------------------------------------------------
pdf/src/main/rust/src/color.rs
diff --git a/pdf/src/main/rust/src/color.rs b/pdf/src/main/rust/src/color.rsindex eb71f6c569..1d8c1dfdc0 100644--- a/pdf/src/main/rust/src/color.rs+++ b/pdf/src/main/rust/src/color.rs@@ -28,8 +28,8 @@ pub(crate) enum CsKind {     Lab { white: [f64;3], range: [[f64;2];2], black: Option<[f64;3]> },     Separation { name: Vec<u8>, alt: Box<CsKind>, tint_fn: Option<PdfFunction> },     DeviceN { names: Vec<Vec<u8>>, alt: Box<CsKind>, tint_fn: Option<PdfFunction> },-    Pattern,-    Indexed { base: Box<CsKind>, lookup: Vec<u8>, base_ncomp: u8 },+    Pattern { base: Option<Box<CsKind>> },+    Indexed { base: Box<CsKind>, lookup: Vec<u8>, base_ncomp: u8, hival: u16 },     ICCBased { n: u8, alt: Option<Box<CsKind>> },     CalRGB { white: [f64;3], gamma: [f64;3], matrix: [[f64;3];3] },     CalGray { white: [f64;3], gamma: f64, black: Option<[f64;3]> },@@ -104,7 +104,7 @@ pub(crate) fn parse_cs_kind(doc: &Document, cs_obj: Option<&Object>, cs_resource             b"DeviceRGB" | b"RGB" => Some(CsKind::DeviceRGB),             b"DeviceCMYK" | b"CMYK" => Some(CsKind::DeviceCMYK),             b"DeviceGray" | b"Gray" | b"G" => Some(CsKind::DeviceGray),-            b"Pattern" => Some(CsKind::Pattern),+            b"Pattern" => Some(CsKind::Pattern { base: None }),             _ => None,         }     }@@ -135,7 +135,7 @@ pub(crate) fn parse_named_cs(             b"DeviceRGB" | b"RGB" => return Some(CsKind::DeviceRGB),             b"DeviceCMYK" | b"CMYK" => return Some(CsKind::DeviceCMYK),             b"DeviceGray" | b"Gray" | b"G" => return Some(CsKind::DeviceGray),-            b"Pattern" => return Some(CsKind::Pattern),+            b"Pattern" => return Some(CsKind::Pattern { base: None }),             _ => {}         }         if let Some(res) = resources {@@ -158,7 +158,10 @@ pub(crate) fn parse_cs_array(doc: &Document, arr: &[Object], cs_resources: &Hash         b"DeviceRGB" | b"RGB" => Some(CsKind::DeviceRGB),         b"DeviceCMYK" | b"CMYK" => Some(CsKind::DeviceCMYK),         b"DeviceGray" | b"G" | b"Gray" => Some(CsKind::DeviceGray),-        b"Pattern" => Some(CsKind::Pattern),+        b"Pattern" => Some(CsKind::Pattern {+            // [ /Pattern baseColorSpace ] for uncolored (PaintType 2) patterns.+            base: arr.get(1).and_then(|o| parse_cs_kind(doc, Some(o), cs_resources)).map(Box::new),+        }),         b"CalRGB" => {             // [ /CalRGB dict ]             let dict = arr.get(1).and_then(|o| deref(doc, o)).and_then(|o| o.as_dict().ok());@@ -209,12 +212,14 @@ pub(crate) fn parse_cs_array(doc: &Document, arr: &[Object], cs_resources: &Hash             // [ /Indexed base hival lookup ]             let base = arr.get(1).and_then(|o| parse_cs_kind(doc, Some(o), cs_resources)).unwrap_or(CsKind::DeviceRGB);             let base_n = cs_kind_ncomp(&base);+            let hival = arr.get(2).and_then(|o| deref(doc, o)).as_ref().and_then(|o| o.as_i64().ok())+                .unwrap_or(255).clamp(0, 65535) as u16;             let lookup = match arr.get(3).and_then(|o| deref(doc, o)) {                 Some(Object::String(s,_)) => s.clone(),                 Some(Object::Stream(s)) => { s.decompressed_content().unwrap_or_else(|_| s.content.clone()) },                 _ => Vec::new(),             };-            Some(CsKind::Indexed { base: Box::new(base), lookup, base_ncomp: base_n })+            Some(CsKind::Indexed { base: Box::new(base), lookup, base_ncomp: base_n, hival })         }         b"Separation" => {             // [ /Separation name alt tintTransform ]@@ -245,7 +250,7 @@ pub(crate) fn cs_kind_ncomp(kind: &CsKind) -> u8 {         CsKind::Indexed { base_ncomp, .. } => *base_ncomp,         CsKind::Separation { .. } => 1,         CsKind::DeviceN { names, .. } => names.len() as u8,-        CsKind::Pattern => 0,+        CsKind::Pattern { .. } => 0,     } } @@ -395,8 +400,8 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re                 _ => None,             }         }-        CsKind::Indexed { base, lookup, base_ncomp } => {-            let idx = (comps.get(0).copied().unwrap_or(0.0) as usize).clamp(0, 255);+        CsKind::Indexed { base, lookup, base_ncomp, hival } => {+            let idx = (comps.get(0).copied().unwrap_or(0.0) as usize).clamp(0, *hival as usize);             let off = idx * *base_ncomp as usize;             if off + *base_ncomp as usize <= lookup.len() {                 let slice = &lookup[off..off+*base_ncomp as usize];@@ -423,10 +428,13 @@ pub(crate) fn eval_cs_to_rgb(doc: &Document, kind: &CsKind, comps: &[f64], cs_re                 let alt_comps = tf.eval(comps);                 eval_cs_to_rgb(doc, alt, &alt_comps, cs_resources)             } else {-                Some(gray_to_argb(1.0 - comps.get(0).copied().unwrap_or(0.0)))+                // No tint transform: treat each colorant as an independent subtractive+                // ink so all components contribute (0 tint = white, full tint = darker).+                let light: f64 = comps.iter().map(|c| 1.0 - c.clamp(0.0, 1.0)).product();+                Some(gray_to_argb(light))             }         }-        CsKind::Pattern => {+        CsKind::Pattern { .. } => {             // Pattern color handling: SCN may include base color, we already evaluated base if comps present             // For pattern-only, we have no color - return None to keep current             None@@ -614,4 +622,56 @@ mod tests {         let argb = eval_cs_to_rgb(&doc, &kind, &[1.0, 0.0, 0.0], &empty).unwrap();         assert_eq!(argb & 0x00FF_FFFF, 0x00FF_0000, "direct-array ICCBased red must stay red");     }++    // Indexed index must clamp to hival, not a hard-coded 255. With hival=1 an+    // out-of-range index (5) should clamp to entry 1, not read past the table.+    #[test]+    fn indexed_clamps_to_hival() {+        let doc = Document::with_version("1.7");+        // Two-entry palette over DeviceRGB: [black, white].+        let cs = CsKind::Indexed {+            base: Box::new(CsKind::DeviceRGB),+            lookup: vec![0, 0, 0, 255, 255, 255],+            base_ncomp: 3,+            hival: 1,+        };+        let res = HashMap::new();+        let over = eval_cs_to_rgb(&doc, &cs, &[5.0], &res).unwrap();+        assert_eq!(over & 0x00FF_FFFF, 0x00FF_FFFF, "index 5 clamps to hival=1 (white)");+    }++    // DeviceN without a tint transform must consider all components, not just the+    // first: two fully-inked colorants should be darker than one.+    #[test]+    fn devicen_without_tint_uses_all_components() {+        let doc = Document::with_version("1.7");+        let cs = CsKind::DeviceN {+            names: vec![b"A".to_vec(), b"B".to_vec()],+            alt: Box::new(CsKind::DeviceGray),+            tint_fn: None,+        };+        let res = HashMap::new();+        let one = eval_cs_to_rgb(&doc, &cs, &[0.5, 0.0], &res).unwrap() & 0xFF;+        let both = eval_cs_to_rgb(&doc, &cs, &[0.5, 0.5], &res).unwrap() & 0xFF;+        assert!(both < one, "two inks ({both}) must be darker than one ({one})");+    }++    // An uncolored Pattern colorspace [/Pattern base] must record its base space+    // so SCN operands resolve in it rather than by arity guessing.+    #[test]+    fn pattern_records_base_colorspace() {+        let doc = Document::with_version("1.7");+        let arr = vec![+            Object::Name(b"Pattern".to_vec()),+            Object::Name(b"DeviceCMYK".to_vec()),+        ];+        let empty = HashMap::new();+        let kind = parse_cs_array(&doc, &arr, &empty).expect("pattern cs");+        match kind {+            CsKind::Pattern { base: Some(b) } => {+                assert!(matches!(*b, CsKind::DeviceCMYK), "base must be DeviceCMYK");+            }+            _ => panic!("expected Pattern with base colorspace"),+        }+    } }
pdf/src/main/rust/src/decrypt.rs
diff --git a/pdf/src/main/rust/src/decrypt.rs b/pdf/src/main/rust/src/decrypt.rsindex 639a1a7a35..1f387ee5bd 100644--- a/pdf/src/main/rust/src/decrypt.rs+++ b/pdf/src/main/rust/src/decrypt.rs@@ -178,15 +178,21 @@ pub(crate) enum EncryptAlgo {     Aes256, } -/// A small md5-based pseudo-random byte source seeded from `seed` plus wall-clock-/// entropy. Adequate for generating salts/IVs in this offline viewer.+/// Cryptographically-secure random bytes for salts/IVs, sourced from the OS+/// CSPRNG. Falls back to md5-based mixing (seed + wall clock) only if the OS+/// RNG is unavailable, preserving the no-panic invariant. fn rand_bytes(n: usize, seed: &[u8]) -> Vec<u8> {+    use rand::RngCore;+    let mut out = vec![0u8; n];+    if rand::rngs::OsRng.try_fill_bytes(&mut out).is_ok() {+        return out;+    }     use md5::{Digest, Md5};     let t = std::time::SystemTime::now()         .duration_since(std::time::UNIX_EPOCH)         .map(|d| d.as_nanos())         .unwrap_or(0);-    let mut out = Vec::with_capacity(n);+    out.clear();     let mut ctr: u64 = 0;     while out.len() < n {         let mut m = Md5::new();
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 8ac261bd01..55959b4179 100644--- a/pdf/src/main/rust/src/draw.rs+++ b/pdf/src/main/rust/src/draw.rs@@ -42,6 +42,14 @@ pub(crate) fn emit_stroke(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], g     };     let dash_phase = (gs.dash_phase * scale) as f32;     let argb = apply_alpha_to_argb(gs.stroke, gs.alpha_stroke);+    // Overprint (stroking) is approximated as Multiply on an RGB compositor:+    // white/zero-ink channels leave the backdrop unchanged, matching overprint's+    // intent for the common case. Only applied when no explicit blend is set.+    let blend = if gs.overprint_stroke && gs.blend_mode == BlendMode::Normal {+        BlendMode::Multiply+    } else {+        gs.blend_mode+    };     for sp in subpaths {         if sp.len() >= 2 {             prims.push(Prim::Stroke {@@ -53,7 +61,7 @@ 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,+                blend,             });         }     }@@ -95,6 +103,9 @@ pub(crate) fn show_string(     let th = gs.h_scale;     let trm = mat_mul(text_matrix, &gs.ctm);     let y_scale = (trm[2] * trm[2] + trm[3] * trm[3]).sqrt();+    // Device-space horizontal scale, used to convert glyph advances (user space)+    // into the device advance carried on the wire for text selection/search.+    let x_scale = (trm[0] * trm[0] + trm[1] * trm[1]).sqrt();     let size = (tfs * y_scale) as f32;     // Modes 3 (invisible) and 7 (clip only) advance the pen but paint nothing.     let drawable = gs.render_mode != 3 && gs.render_mode != 7;@@ -159,7 +170,7 @@ pub(crate) fn show_string(                 let rm = gs.render_mode as u8;                 let base_adv = fi.width(code) * tfs;                 let _ = base_adv;-                let glyph_device_adv = glyph_advance_user as f32;+                let glyph_device_adv = (glyph_advance_user * x_scale) as f32;                 if prims.len() < MAX_PRIMITIVES {                     if has_fill {                         prims.push(Prim::Text {
pdf/src/main/rust/src/filters.rs
diff --git a/pdf/src/main/rust/src/filters.rs b/pdf/src/main/rust/src/filters.rsindex 4436c7b749..8c5ad927f4 100644--- a/pdf/src/main/rust/src/filters.rs+++ b/pdf/src/main/rust/src/filters.rs@@ -248,6 +248,10 @@ pub fn parse_ccitt_params(doc: &Document, dict_opt: Option<&Dictionary>) -> Ccit }  pub fn decode_ccitt(data: &[u8], w: u32, h: u32, params: &CcittParams) -> Option<Vec<u8>> {+    // NOTE: `/EncodedByteAlign` and mixed 1-D/2-D G3 (K>0) are not honored — the+    // `fax` crate decodes pure G3 (1-D) / G4 (2-D) from a continuous bitstream+    // and exposes no per-row byte-alignment or K>0 mode switching hook. Pure+    // G3/G4 (the common cases) decode correctly. See README limitations.     let columns = if params.columns>0 { params.columns } else { w };     let rows = if params.rows>0 { params.rows } else { h };     let rows_us = rows as usize;@@ -393,24 +397,68 @@ fn apply_predictor(data: Vec<u8>, parms: Option<&Dictionary>, doc: &Document) ->     } } -/// TIFF Predictor 2: horizontal differencing. Only the common 8-bit case is-/// reversed exactly; other bit depths are returned unchanged.+/// TIFF Predictor 2: horizontal differencing. Reverses the left-difference for+/// 1/2/4/8/16-bit samples. Rows are byte-aligned; sub-byte samples are packed+/// big-endian within each byte and 16-bit samples are big-endian. fn apply_tiff_predictor2(mut data: Vec<u8>, cols: usize, colors: usize, bpc: usize) -> Vec<u8> {-    if bpc != 8 || cols == 0 || colors == 0 {+    if cols == 0 || colors == 0 {         return data;     }-    let row_bytes = cols * colors;+    let samples_per_row = cols * colors;+    let row_bits = samples_per_row * bpc;+    let row_bytes = (row_bits + 7) / 8;     if row_bytes == 0 {         return data;     }     let rows = data.len() / row_bytes;-    for r in 0..rows {-        let base = r * row_bytes;-        for i in colors..row_bytes {-            let prev = data[base + i - colors];-            let cur = data[base + i];-            data[base + i] = cur.wrapping_add(prev);+    match bpc {+        8 => {+            for r in 0..rows {+                let base = r * row_bytes;+                for i in colors..samples_per_row {+                    let prev = data[base + i - colors];+                    data[base + i] = data[base + i].wrapping_add(prev);+                }+            }         }+        16 => {+            for r in 0..rows {+                let base = r * row_bytes;+                for i in colors..samples_per_row {+                    let p = base + (i - colors) * 2;+                    let c = base + i * 2;+                    let prev = ((data[p] as u16) << 8) | data[p + 1] as u16;+                    let cur = ((data[c] as u16) << 8) | data[c + 1] as u16;+                    let val = cur.wrapping_add(prev);+                    data[c] = (val >> 8) as u8;+                    data[c + 1] = (val & 0xFF) as u8;+                }+            }+        }+        1 | 2 | 4 => {+            let mask = ((1u32 << bpc) - 1) as u16;+            for r in 0..rows {+                let base = r * row_bytes;+                // Unpack samples (MSB-first) for this row.+                let mut samples = vec![0u16; samples_per_row];+                for (s, slot) in samples.iter_mut().enumerate() {+                    let bit = s * bpc;+                    let byte = base + bit / 8;+                    let shift = 8 - bpc - (bit % 8);+                    *slot = ((data[byte] as u16) >> shift) & mask;+                }+                for i in colors..samples_per_row {+                    samples[i] = samples[i].wrapping_add(samples[i - colors]) & mask;+                }+                for (s, val) in samples.iter().enumerate() {+                    let bit = s * bpc;+                    let byte = base + bit / 8;+                    let shift = 8 - bpc - (bit % 8);+                    data[byte] = (data[byte] & !((mask as u8) << shift)) | ((*val as u8) << shift);+                }+            }+        }+        _ => {}     }     data }@@ -450,4 +498,26 @@ mod tests {         let out = apply_tiff_predictor2(encoded, 3, 1, 8);         assert_eq!(out, vec![10, 20, 30, 5, 5, 5]);     }+    #[test] fn tiff_predictor2_16bit() {+        // One row, 2 columns, 1 color, 16bpc big-endian.+        // Original samples [0x0102, 0x0305] -> diffs [0x0102, 0x0203].+        let encoded = vec![0x01, 0x02, 0x02, 0x03];+        let out = apply_tiff_predictor2(encoded, 2, 1, 16);+        assert_eq!(out, vec![0x01, 0x02, 0x03, 0x05]);+    }+    #[test] fn tiff_predictor2_4bit() {+        // One row, 4 columns, 1 color, 4bpc. Original nibbles [1,3,6,7].+        // Diffs [1,2,3,1] -> packed 0x12, 0x31.+        let encoded = vec![0x12, 0x31];+        let out = apply_tiff_predictor2(encoded, 4, 1, 4);+        assert_eq!(out, vec![0x13, 0x67]);+    }+    #[test] fn tiff_predictor2_1bit() {+        // One row, 8 columns, 1 color, 1bpc. Original bits 1 0 1 1 0 0 1 0.+        // Left diffs (xor-like add mod 2): b[0]=1; b[i]=orig[i]-orig[i-1] mod2+        // orig=10110010 -> diffs: 1, 1, 1, 0, 1, 0, 1, 1 = 0b11101011 = 0xEB.+        let encoded = vec![0xEBu8];+        let out = apply_tiff_predictor2(encoded, 8, 1, 1);+        assert_eq!(out, vec![0b10110010]);+    } }
pdf/src/main/rust/src/fonts.rs
diff --git a/pdf/src/main/rust/src/fonts.rs b/pdf/src/main/rust/src/fonts.rsindex 359cd0ecf2..0bb32aee68 100644--- a/pdf/src/main/rust/src/fonts.rs+++ b/pdf/src/main/rust/src/fonts.rs@@ -453,6 +453,17 @@ use std::io::Cursor;                     }                 }             }+            10 => {+                // Trimmed array (like format 6 but 32-bit code space).+                let first = u32b(b, off + 12);+                let count = u32b(b, off + 16) as usize;+                for i in 0..count.min(0x20000) {+                    let g = u16b(b, off + 20 + i * 2);+                    if g != 0 {+                        out.push((first + i as u32, g));+                    }+                }+            }             12 => {                 let ngroups = u32b(b, off + 12) as usize;                 for i in 0..ngroups {@@ -468,6 +479,23 @@ use std::io::Cursor;                     }                 }             }+            13 => {+                // Many-to-one range mappings: every code in a group maps to the+                // same glyph (used for e.g. "last resort" fonts).+                let ngroups = u32b(b, off + 12) as usize;+                for i in 0..ngroups {+                    let g = off + 16 + i * 12;+                    let sc = u32b(b, g);+                    let ec = u32b(b, g + 4);+                    let gid = u32b(b, g + 8) as u16;+                    if sc > ec || ec - sc > 65535 || gid == 0 {+                        continue;+                    }+                    for c in sc..=ec {+                        out.push((c, gid));+                    }+                }+            }             _ => {}         }         out@@ -525,6 +553,47 @@ use std::io::Cursor;         }         result     }++    #[cfg(test)]+    mod tests {+        use super::parse_subtable;++        fn be16(v: u16) -> [u8; 2] { v.to_be_bytes() }+        fn be32(v: u32) -> [u8; 4] { v.to_be_bytes() }++        #[test]+        fn format13_maps_range_to_single_glyph() {+            let mut b = Vec::new();+            b.extend_from_slice(&be16(13));      // format+            b.extend_from_slice(&be16(0));       // reserved+            b.extend_from_slice(&be32(0));       // length+            b.extend_from_slice(&be32(0));       // language+            b.extend_from_slice(&be32(1));       // nGroups+            b.extend_from_slice(&be32(0x41));    // startChar+            b.extend_from_slice(&be32(0x43));    // endChar+            b.extend_from_slice(&be32(5));       // glyphID+            let pairs = parse_subtable(&b, 0);+            assert!(pairs.contains(&(0x41, 5)));+            assert!(pairs.contains(&(0x42, 5)));+            assert!(pairs.contains(&(0x43, 5)));+        }++        #[test]+        fn format10_trimmed_array() {+            let mut b = Vec::new();+            b.extend_from_slice(&be16(10));      // format+            b.extend_from_slice(&be16(0));       // reserved+            b.extend_from_slice(&be32(0));       // length+            b.extend_from_slice(&be32(0));       // language+            b.extend_from_slice(&be32(0x41));    // startCharCode+            b.extend_from_slice(&be32(2));       // numChars+            b.extend_from_slice(&be16(7));       // glyph for 0x41+            b.extend_from_slice(&be16(8));       // glyph for 0x42+            let pairs = parse_subtable(&b, 0);+            assert!(pairs.contains(&(0x41, 7)));+            assert!(pairs.contains(&(0x42, 8)));+        }+    } }  // ---------------------------------------------------------------------------
pdf/src/main/rust/src/forms.rs
diff --git a/pdf/src/main/rust/src/forms.rs b/pdf/src/main/rust/src/forms.rsindex 1b9f03a081..06ce0fa502 100644--- a/pdf/src/main/rust/src/forms.rs+++ b/pdf/src/main/rust/src/forms.rs@@ -365,6 +365,37 @@ pub(crate) fn set_checkbox(handle: i64, widget_id: i64, on: bool) -> bool {         })         .unwrap_or_else(|| b"Yes".to_vec()); +    // Radio buttons: the widget belongs to a parent field with several kid+    // widgets that must be mutually exclusive. Setting one on clears the others+    // and records the chosen export value on the parent /V.+    let parent = doc.get_dictionary(id).ok()+        .and_then(|d| d.get(b"Parent").ok())+        .and_then(|o| o.as_reference().ok());+    let sibling_ids: Vec<ObjectId> = parent+        .and_then(|pid| doc.get_dictionary(pid).ok())+        .and_then(|pd| pd.get(b"Kids").ok())+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_array().ok())+        .map(|kids| kids.iter().filter_map(|k| k.as_reference().ok()).collect())+        .unwrap_or_default();++    if let Some(pid) = parent {+        if sibling_ids.len() > 1 {+            // Radio group: set each kid's /AS, and the parent /V.+            for kid in &sibling_ids {+                let state = if *kid == id && on { on_state.clone() } else { b"Off".to_vec() };+                if let Ok(kd) = doc.get_dictionary_mut(*kid) {+                    kd.set("AS", Object::Name(state));+                }+            }+            if let Ok(pd) = doc.get_dictionary_mut(pid) {+                if on { pd.set("V", Object::Name(on_state.clone())); }+                else { pd.set("V", Object::Name(b"Off".to_vec())); }+            }+            return true;+        }+    }+     let state = if on { on_state } else { b"Off".to_vec() };     if let Ok(dict) = doc.get_dictionary_mut(id) {         dict.set("AS", Object::Name(state.clone()));@@ -375,6 +406,64 @@ pub(crate) fn set_checkbox(handle: i64, widget_id: i64, on: bool) -> bool {     } } +/// Set a Choice (`/Ch`) field's value: records `/V`, the matching `/Opt` index+/// in `/I`, and builds a single-line text appearance showing the selection.+pub(crate) fn set_choice_field(handle: i64, widget_id: i64, value: &str) -> bool {+    let mut reg = registry().lock().unwrap();+    let doc = match reg.get_mut(&handle) {+        Some(d) => d,+        None => return false,+    };+    let id = decode_id(widget_id);+    let rect = doc+        .get_dictionary(id)+        .ok()+        .and_then(|d| d.get(b"Rect").ok())+        .and_then(|o| read_rect(doc, o))+        .map(normalize_rect);+    // Find the option index whose export/display value matches `value`.+    let opt_index = field_attr(doc, id, b"Opt")+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_array().ok())+        .and_then(|opts| {+            opts.iter().position(|o| {+                let disp = match deref(doc, o).unwrap_or(o) {+                    Object::String(s, _) => String::from_utf8_lossy(s).into_owned(),+                    Object::Array(pair) => pair.last()+                        .and_then(|d| d.as_str().ok())+                        .map(|s| String::from_utf8_lossy(s).into_owned())+                        .unwrap_or_default(),+                    _ => String::new(),+                };+                disp == value+            })+        });++    let ap_id = rect.map(|r| {+        let (w, h) = (r[2] - r[0], r[3] - r[1]);+        let size = (h - 4.0).clamp(6.0, 14.0);+        let content = build_text_appearance(value, w, h, size, 0, false, false, 0);+        make_appearance(doc, w, h, content, helvetica_resources())+    });++    if let Ok(dict) = doc.get_dictionary_mut(id) {+        dict.set("V", Object::string_literal(value));+        match opt_index {+            Some(i) => { dict.set("I", Object::Array(vec![Object::Integer(i as i64)])); }+            None => { dict.remove(b"I"); }+        }+        if let Some(ap_id) = ap_id {+            let mut ap = Dictionary::new();+            ap.set("N", Object::Reference(ap_id));+            dict.set("AP", Object::Dictionary(ap));+        }+    } else {+        return false;+    }+    set_need_appearances(doc);+    true+}+ /// Extract the document's visible text (from rendered text primitives), one /// blank line between pages. pub(crate) fn document_text(handle: i64) -> Option<String> {
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 180c9d350d..9af696883d 100644--- a/pdf/src/main/rust/src/graphics_state.rs+++ b/pdf/src/main/rust/src/graphics_state.rs@@ -49,6 +49,19 @@ impl BlendMode {     } } +/// Active ExtGState soft mask. The mask group is rendered at the CTM in effect+/// when the mask was set (per ISO 32000 11.6.5.2), optionally over a `/BC`+/// backdrop color. `/TR` transfer functions are not applied (documented).+#[derive(Clone)]+pub(crate) struct SoftMask {+    pub(crate) group_id: ObjectId,+    /// 0 = alpha, 1 = luminosity.+    pub(crate) mask_type: u8,+    pub(crate) ctm: Mat,+    /// `/BC` backdrop color components (in the group's colorspace), if given.+    pub(crate) backdrop: Option<Vec<f64>>,+}+ #[derive(Clone)] pub(crate) struct GraphicsState {     pub(crate) ctm: Mat,@@ -82,9 +95,12 @@ 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)>,+    /// Active ExtGState soft mask, or `None` when `/SMask` is `/None`.+    pub(crate) soft_mask: Option<SoftMask>,+    /// Overprint state: `/OP` (stroking), `/op` (nonstroking), `/OPM` (mode).+    pub(crate) overprint_stroke: bool,+    pub(crate) overprint_fill: bool,+    pub(crate) overprint_mode: u8, }  impl Default for GraphicsState {@@ -115,6 +131,9 @@ impl Default for GraphicsState {             fill_pattern: None,             stroke_pattern: None,             soft_mask: None,+            overprint_stroke: false,+            overprint_fill: false,+            overprint_mode: 0,         }     } }
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 feac9552da..5547e1133c 100644--- a/pdf/src/main/rust/src/images.rs+++ b/pdf/src/main/rust/src/images.rs@@ -133,24 +133,76 @@ pub(crate) mod jp2 {             v.clamp(0, 255) as u8         }; +        // Decide how to interpret components. Prefer the JP2 enumerated color+        // space; fall back to component count when unspecified/unknown.+        #[derive(PartialEq)]+        enum Interp { Gray, Rgb, Ycc, Cmyk }+        let interp = match img.color_space {+            OPJ_CLRSPC_GRAY => Interp::Gray,+            OPJ_CLRSPC_CMYK => Interp::Cmyk,+            OPJ_CLRSPC_SYCC | OPJ_CLRSPC_EYCC => Interp::Ycc,+            OPJ_CLRSPC_SRGB => Interp::Rgb,+            // Unknown/unspecified: infer from channel count.+            _ => match n {+                1 => Interp::Gray,+                4 => Interp::Cmyk,+                _ => Interp::Rgb,+            },+        };+        // Alpha comes from a trailing extra channel for gray/rgb layouts.+        let has_alpha = matches!(interp, Interp::Gray if n >= 2)+            || matches!(interp, Interp::Rgb | Interp::Ycc if n >= 4);+         let mut rgba = vec![0u8; w * h * 4];         for y in 0..h {             for x in 0..w {                 let idx = (y * w + x) * 4;-                let (r, g, b) = if n >= 3 {-                    (+                let (r, g, b) = match interp {+                    Interp::Gray => {+                        let v = sample(&comps[0], x, y);+                        (v, v, v)+                    }+                    Interp::Rgb => (                         sample(&comps[0], x, y),-                        sample(&comps[1], x, y),-                        sample(&comps[2], x, y),-                    )-                } else {-                    let v = sample(&comps[0], x, y);-                    (v, v, v)+                        sample(comps.get(1).unwrap_or(&comps[0]), x, y),+                        sample(comps.get(2).unwrap_or(&comps[0]), x, y),+                    ),+                    Interp::Ycc if n >= 3 => {+                        let yy = sample(&comps[0], x, y) as f32;+                        let cb = sample(&comps[1], x, y) as f32 - 128.0;+                        let cr = sample(&comps[2], x, y) as f32 - 128.0;+                        let r = (yy + 1.402 * cr).round().clamp(0.0, 255.0) as u8;+                        let g = (yy - 0.344136 * cb - 0.714136 * cr).round().clamp(0.0, 255.0) as u8;+                        let b = (yy + 1.772 * cb).round().clamp(0.0, 255.0) as u8;+                        (r, g, b)+                    }+                    Interp::Ycc => {+                        let v = sample(&comps[0], x, y);+                        (v, v, v)+                    }+                    Interp::Cmyk if n >= 4 => {+                        let c = sample(&comps[0], x, y) as f32 / 255.0;+                        let m = sample(&comps[1], x, y) as f32 / 255.0;+                        let ye = sample(&comps[2], x, y) as f32 / 255.0;+                        let k = sample(&comps[3], x, y) as f32 / 255.0;+                        let r = ((1.0 - c) * (1.0 - k) * 255.0).round() as u8;+                        let g = ((1.0 - m) * (1.0 - k) * 255.0).round() as u8;+                        let b = ((1.0 - ye) * (1.0 - k) * 255.0).round() as u8;+                        (r, g, b)+                    }+                    Interp::Cmyk => {+                        let v = sample(&comps[0], x, y);+                        (v, v, v)+                    }                 };                 rgba[idx] = r;                 rgba[idx + 1] = g;                 rgba[idx + 2] = b;-                rgba[idx + 3] = 255;+                rgba[idx + 3] = if has_alpha {+                    sample(&comps[n - 1], x, y)+                } else {+                    255+                };             }         }         Some((w as u32, h as u32, rgba))@@ -251,7 +303,7 @@ pub(crate) fn ocg_is_visible_alias(doc: &Document, id: ObjectId) -> Option<bool> /// `comps_to_rgb` device path which is equivalent for plain RGB/Gray/CMYK). fn cs_needs_eval(k: &CsKind) -> bool {     match k {-        CsKind::DeviceGray | CsKind::DeviceRGB | CsKind::DeviceCMYK | CsKind::Pattern => false,+        CsKind::DeviceGray | CsKind::DeviceRGB | CsKind::DeviceCMYK | CsKind::Pattern { .. } => false,         CsKind::ICCBased { alt, .. } => alt.as_ref().map(|a| cs_needs_eval(a)).unwrap_or(false),         CsKind::Lab { .. }         | CsKind::Separation { .. }@@ -336,7 +388,7 @@ fn image_samples_to_rgba(     };      // Indexed: build a palette LUT over the base colorspace.-    if let CsKind::Indexed { base, lookup, base_ncomp } = &kind {+    if let CsKind::Indexed { base, lookup, base_ncomp, .. } = &kind {         let bn = *base_ncomp as usize;         let maxidx = if bpc >= 8 { 255usize } else { (1usize << bpc) - 1 };         let hival = if bn > 0 { (lookup.len() / bn).saturating_sub(1) } else { 0 };@@ -606,6 +658,13 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u             if let Some((jw,jh,mut rgba)) = decode_jpeg_rgba(&jpeg_bytes) {                 let smask = read_smask(doc, dict, jw, jh);                 apply_smask(&mut rgba, &smask);+                if smask.is_some() { if let Some(matte) = read_matte(doc, dict) { apply_matte(&mut rgba, matte); } }+                if let Some(mask_alpha) = read_explicit_mask(doc, dict, jw, jh) {+                    for (i, px) in rgba.chunks_exact_mut(4).enumerate() {+                        let mv = mask_alpha.get(i).copied().unwrap_or(255) as u16;+                        px[3] = ((px[3] as u16 * mv) / 255) as u8;+                    }+                }                 if let Some(ck) = read_color_key_mask(doc, dict) { apply_color_key_mask(&mut rgba, &Some(ck)); }                 return Some(ImageData { w: jw, h: jh, format: 0, data: rgba });             }@@ -618,11 +677,26 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u                 }                 let smask = read_smask(doc, dict, jw, jh);                 apply_smask(&mut rgba, &smask);+                if let Some(mask_alpha) = read_explicit_mask(doc, dict, jw, jh) {+                    for (i, px) in rgba.chunks_exact_mut(4).enumerate() {+                        let mv = mask_alpha.get(i).copied().unwrap_or(255) as u16;+                        px[3] = ((px[3] as u16 * mv) / 255) as u8;+                    }+                }                 if let Some(ck) = read_color_key_mask(doc, dict) { apply_color_key_mask(&mut rgba, &Some(ck)); }                 return Some(ImageData{ w: jw, h: jh, format: 0, data: rgba });             }         }         if !smask_present && !mask_present {+            // Android's bitmap decoder cannot handle CMYK/YCCK JPEGs, so decode+            // those (and any Adobe-marked JPEG) in Rust; RGB/gray pass through.+            let cmyk = jpeg_num_components(&jpeg_bytes) == Some(4)+                || jpeg_adobe_transform(&jpeg_bytes).is_some();+            if cmyk {+                if let Some((jw, jh, rgba)) = decode_jpeg_rgba(&jpeg_bytes) {+                    return Some(ImageData { w: jw, h: jh, format: 0, data: rgba });+                }+            }             // efficient passthrough             return Some(ImageData { w, h, format: 1, data: jpeg_bytes });         }@@ -636,7 +710,6 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u     let samples = stream_data(stream);     let mut rgba = vec![0u8; (w * h * 4) as usize];     let smask = read_smask(doc, dict, w, h);-    let colorkey = read_color_key_mask(doc, dict);      if image_mask {         let invert = matches!(@@ -682,7 +755,26 @@ pub(crate) fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u     let mut rgba = image_samples_to_rgba(doc, dict, cs_resources, &decoded_comps, w_us, h_us, ncomp as usize, bpc);      apply_smask(&mut rgba, &smask);-    apply_color_key_mask(&mut rgba, &colorkey);+    // /Matte: base colors are premultiplied against a matte background; undo it+    // using the SMask alpha we just applied.+    if smask.is_some() {+        if let Some(matte) = read_matte(doc, dict) {+            apply_matte(&mut rgba, matte);+        }+    }+    // Explicit stencil /Mask image (mutually exclusive with color-key /Mask).+    if let Some(mask_alpha) = read_explicit_mask(doc, dict, w, h) {+        for (i, px) in rgba.chunks_exact_mut(4).enumerate() {+            let mv = mask_alpha.get(i).copied().unwrap_or(255) as u16;+            px[3] = ((px[3] as u16 * mv) / 255) as u8;+        }+    }+    // Color-key masking is compared against the pre-conversion samples so it is+    // correct for CMYK/DeviceN (not just DeviceRGB/Gray). Indexed images key on+    // the index value, which `decoded_comps` already holds (ncomp==1).+    if let Some(ranges_raw) = read_color_key_ranges_raw(doc, dict) {+        apply_color_key_mask_samples(&mut rgba, &decoded_comps, ncomp as usize, &ranges_raw, bpc);+    }     Some(ImageData { w, h, format: 0, data: rgba }) } @@ -730,7 +822,9 @@ pub(crate) fn extract_inline_image(doc: &Document, stream: &lopdf::Stream, _fill     let mut rgba = image_samples_to_rgba(doc, dict, cs_resources, &unpacked, w as usize, h as usize, ncomp as usize, bpc);     let smask = read_smask(doc, dict, w, h);     apply_smask(&mut rgba, &smask);-    if let Some(ck) = read_color_key_mask(doc, dict) { apply_color_key_mask(&mut rgba, &Some(ck)); }+    if let Some(ranges_raw) = read_color_key_ranges_raw(doc, dict) {+        apply_color_key_mask_samples(&mut rgba, &unpacked, ncomp as usize, &ranges_raw, bpc);+    }     Some(ImageData { w, h, format: 0, data: rgba }) } @@ -779,7 +873,15 @@ pub(crate) fn radial_shading_param(coords: &[f64], e0: bool, e1: bool, fx: f64,     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>)> {+/// Compute an effective raster resolution from a unit-square→device matrix so+/// gradients stay sharp when the page is zoomed. Clamped to a sane range.+pub(crate) fn shading_device_size(unit_to_device: &Mat) -> u32 {+    let dev_w = (unit_to_device[0].powi(2) + unit_to_device[1].powi(2)).sqrt();+    let dev_h = (unit_to_device[2].powi(2) + unit_to_device[3].powi(2)).sqrt();+    (dev_w.max(dev_h).ceil() as u32).clamp(64, 1024)+}++pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm: &Mat, cs_resources: &HashMap<Vec<u8>, ObjectId>, size: u32, clip_bbox_device: Option<[f64;4]>) -> 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).     let (dict, mesh_bytes): (&lopdf::Dictionary, Option<Vec<u8>>) = match shading_obj {@@ -788,6 +890,15 @@ pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm:         _ => return None,     };     let shading_type = dict.get(b"ShadingType").ok().and_then(num).unwrap_or(0.0) as i64;+    // When the caller passes size==0, derive an effective resolution from the+    // device footprint of the clip region (falls back to 256 if unknown).+    let auto_size = || -> u32 {+        match clip_bbox_device {+            Some(b) => (((b[2]-b[0]).abs()).max((b[3]-b[1]).abs()).ceil() as u32).clamp(64, 1024),+            None => 256,+        }+    };+    let size = if size == 0 { auto_size() } else { size };     if shading_type==4 || shading_type==5 || shading_type==6 || shading_type==7 {         // Mesh shadings: pass the decoded stream body so real vertices/patches         // can be parsed (falls back to /DataSource when the dict provides one).@@ -804,7 +915,27 @@ pub(crate) fn rasterize_shading(doc: &Document, shading_obj: &Object, base_ctm:     let bg = dict.get(b"Background").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_array().ok())         .map(|a| a.iter().filter_map(|o| deref(doc, o).and_then(num)).collect::<Vec<f64>>()); -    let bbox = dict.get(b"BBox").ok().and_then(|o| read_rect(doc, o)).unwrap_or([0.0,0.0,100.0,100.0]);+    // /BBox bounds the shading in shading space. When absent, cover the current+    // clip region instead of an arbitrary 100×100 box: map the device clip bbox+    // back into shading space via the inverse CTM.+    let bbox = dict.get(b"BBox").ok().and_then(|o| read_rect(doc, o)).unwrap_or_else(|| {+        if let Some(cb) = clip_bbox_device {+            let inv = mat_inverse(base_ctm);+            let corners = [+                transform(&inv, cb[0], cb[1]), transform(&inv, cb[2], cb[1]),+                transform(&inv, cb[2], cb[3]), transform(&inv, cb[0], cb[3]),+            ];+            let xs = corners.iter().map(|p| p.0);+            let ys = corners.iter().map(|p| p.1);+            let x0 = xs.clone().fold(f64::INFINITY, f64::min);+            let x1 = xs.fold(f64::NEG_INFINITY, f64::max);+            let y0 = ys.clone().fold(f64::INFINITY, f64::min);+            let y1 = ys.fold(f64::NEG_INFINITY, f64::max);+            if x1 > x0 && y1 > y0 { [x0, y0, x1, y1] } else { [0.0,0.0,100.0,100.0] }+        } else {+            [0.0,0.0,100.0,100.0]+        }+    });      let color_space_obj = dict.get(b"ColorSpace").ok().and_then(|o| parse_cs_kind(doc, Some(o), cs_resources));     // If CS not present, try to infer from Function or Background etc.@@ -1065,6 +1196,55 @@ pub(crate) fn read_color_key_mask(doc: &Document, dict: &lopdf::Dictionary) -> O     Some(out) } +/// Read a color-key `/Mask` array as raw per-component sample-value ranges+/// (i.e. in the image's 0..2^bpc-1 units, one `(min,max)` per component). This+/// is the form needed to mask against pre-conversion samples for CMYK/DeviceN.+pub(crate) fn read_color_key_ranges_raw(doc: &Document, dict: &lopdf::Dictionary) -> Option<Vec<(u32,u32)>> {+    let mask_obj = dict.get(b"Mask").ok().and_then(|o| deref(doc, o))?;+    let arr = match mask_obj {+        Object::Array(a) => a,+        _ => return None,+    };+    if arr.is_empty() || arr.len()%2!=0 || arr.len()>20 { return None; }+    let mut out = Vec::with_capacity(arr.len()/2);+    for i in 0..arr.len()/2 {+        let mn = num(&arr[i*2]).unwrap_or(0.0).max(0.0);+        let mx = num(&arr[i*2+1]).unwrap_or(0.0).max(0.0);+        out.push((mn.min(mx) as u32, mn.max(mx) as u32));+    }+    Some(out)+}++/// Apply color-key masking against pre-conversion samples. `comps` is+/// `w*h*ncomp` bytes already scaled to 0..255 by [`unpack_samples_to_bytes`];+/// `ranges_raw` holds one `(min,max)` per component in 0..2^bpc-1 units. A pixel+/// whose every component falls inside its range becomes fully transparent. This+/// masks correctly for CMYK/DeviceN, unlike the RGB-only post-conversion path.+pub(crate) fn apply_color_key_mask_samples(+    rgba: &mut [u8],+    comps: &[u8],+    ncomp: usize,+    ranges_raw: &[(u32,u32)],+    bpc: u32,+) {+    if ncomp == 0 || ranges_raw.len() != ncomp { return; }+    let maxval = ((1u64 << bpc.clamp(1, 16)) - 1).max(1);+    // Scale each raw range into the 0..255 sample domain, matching the unpacker.+    let scaled: Vec<(u8,u8)> = ranges_raw.iter().map(|&(mn,mx)| {+        let s = |v: u32| ((v as u64).min(maxval) * 255 / maxval) as u8;+        (s(mn), s(mx))+    }).collect();+    let px = rgba.len() / 4;+    for i in 0..px {+        let mut inside = true;+        for (c, &(mn, mx)) in scaled.iter().enumerate() {+            let v = comps.get(i*ncomp + c).copied().unwrap_or(0);+            if v < mn || v > mx { inside = false; break; }+        }+        if inside { rgba[i*4+3] = 0; }+    }+}+ pub(crate) fn decode_jpeg_rgba(data: &[u8]) -> Option<(u32,u32,Vec<u8>)> {     let mut decoder = jpeg_decoder::Decoder::new(Cursor::new(data));     let pixels = decoder.decode().ok()?;@@ -1094,17 +1274,24 @@ pub(crate) fn decode_jpeg_rgba(data: &[u8]) -> Option<(u32,u32,Vec<u8>)> {             out         }         jpeg_decoder::PixelFormat::CMYK32 => {-            // CMYK -> RGB+            // CMYK -> RGB. Adobe (APP14) CMYK JPEGs store inverted samples, so+            // when the Adobe marker is present the channels must be inverted+            // before conversion or colors come out negated.             if pixels.len() < (w*h*4) as usize { return None; }+            let invert = jpeg_adobe_transform(data).is_some();             let mut out = vec![0u8; (w*h*4) as usize];             for i in 0..(w*h) as usize {-                let c = pixels[i*4] as f64 /255.0;-                let m = pixels[i*4+1] as f64 /255.0;-                let y = pixels[i*4+2] as f64 /255.0;-                let k = pixels[i*4+3] as f64 /255.0;-                let r = ((1.0 - c)*(1.0 - k)*255.0) as u8;-                let g = ((1.0 - m)*(1.0 - k)*255.0) as u8;-                let b = ((1.0 - y)*(1.0 - k)*255.0) as u8;+                let (mut c, mut m, mut y, mut k) = (+                    pixels[i*4], pixels[i*4+1], pixels[i*4+2], pixels[i*4+3],+                );+                if invert { c = 255 - c; m = 255 - m; y = 255 - y; k = 255 - k; }+                let cf = c as f64 /255.0;+                let mf = m as f64 /255.0;+                let yf = y as f64 /255.0;+                let kf = k as f64 /255.0;+                let r = ((1.0 - cf)*(1.0 - kf)*255.0) as u8;+                let g = ((1.0 - mf)*(1.0 - kf)*255.0) as u8;+                let b = ((1.0 - yf)*(1.0 - kf)*255.0) as u8;                 out[i*4]=r; out[i*4+1]=g; out[i*4+2]=b; out[i*4+3]=255;             }             out@@ -1114,6 +1301,66 @@ pub(crate) fn decode_jpeg_rgba(data: &[u8]) -> Option<(u32,u32,Vec<u8>)> {     Some((w,h,rgba)) } +/// Read the component count from a JPEG's SOF marker (1 = gray, 3 = YCbCr/RGB,+/// 4 = CMYK/YCCK). Returns `None` if no SOF is found.+pub(crate) fn jpeg_num_components(data: &[u8]) -> Option<u8> {+    if data.len() < 2 || data[0] != 0xFF || data[1] != 0xD8 { return None; }+    let mut i = 2;+    while i + 1 < data.len() {+        if data[i] != 0xFF { i += 1; continue; }+        let marker = data[i + 1];+        if marker == 0xFF { i += 1; continue; }+        if marker == 0x01 || (0xD0..=0xD9).contains(&marker) { i += 2; continue; }+        if marker == 0xDA { break; }+        if i + 4 > data.len() { break; }+        let len = ((data[i + 2] as usize) << 8) | data[i + 3] as usize;+        if len < 2 { break; }+        let seg_end = i + 2 + len;+        if seg_end > data.len() { break; }+        // SOF0..SOF15, excluding DHT(C4), JPG(C8), DAC(CC).+        let is_sof = (0xC0..=0xCF).contains(&marker)+            && marker != 0xC4 && marker != 0xC8 && marker != 0xCC;+        if is_sof {+            // payload: precision(1) height(2) width(2) ncomp(1)+            return data.get(i + 4 + 5).copied();+        }+        i = seg_end;+    }+    None+}++/// Scan JPEG markers for an APP14 "Adobe" segment, returning its transform flag+/// (0 = unknown/CMYK, 1 = YCbCr, 2 = YCCK) if present. Its mere presence signals+/// the Adobe inverted-CMYK convention. Returns `None` for non-Adobe JPEGs.+pub(crate) fn jpeg_adobe_transform(data: &[u8]) -> Option<u8> {+    if data.len() < 2 || data[0] != 0xFF || data[1] != 0xD8 { return None; }+    let mut i = 2;+    while i + 1 < data.len() {+        if data[i] != 0xFF { i += 1; continue; }+        let marker = data[i + 1];+        // Padding fill bytes.+        if marker == 0xFF { i += 1; continue; }+        // Standalone markers (no length): TEM, RSTn, SOI, EOI.+        if marker == 0x01 || (0xD0..=0xD9).contains(&marker) { i += 2; continue; }+        // Start of scan: entropy-coded data follows; stop looking.+        if marker == 0xDA { break; }+        if i + 4 > data.len() { break; }+        let len = ((data[i + 2] as usize) << 8) | data[i + 3] as usize;+        if len < 2 { break; }+        let seg_start = i + 4;+        let seg_end = i + 2 + len;+        if seg_end > data.len() { break; }+        if marker == 0xEE {+            let seg = &data[seg_start..seg_end];+            if seg.len() >= 12 && &seg[0..5] == b"Adobe" {+                return Some(seg[11]);+            }+        }+        i = seg_end;+    }+    None+}+ pub(crate) fn decode_jpeg_gray(data: &[u8]) -> Option<(u32,u32,Vec<u8>)> {     let mut decoder = jpeg_decoder::Decoder::new(Cursor::new(data));     let pixels = decoder.decode().ok()?;@@ -1232,6 +1479,86 @@ pub(crate) fn unpack_samples_to_bytes(samples: &[u8], w: usize, h: usize, ncomp:     None } +/// Decode an explicit stencil `/Mask` image (an `ImageMask` XObject) into a+/// `w*h` 8-bit alpha buffer for the base image: mask sample 1 => masked+/// (alpha 0), 0 => painted (alpha 255), honoring the mask's `/Decode`. Scaled to+/// the base image's dimensions. Returns `None` for a color-key array `/Mask` or+/// for masks using image codecs this path doesn't decode (CCITT/JBIG2/DCT/JPX).+pub(crate) fn read_explicit_mask(doc: &Document, dict: &lopdf::Dictionary, w: u32, h: u32) -> Option<Vec<u8>> {+    let m = dict.get(b"Mask").ok().and_then(|o| deref(doc, o))?;+    let s = match m { Object::Stream(s) => s, _ => return None };+    if !matches!(s.dict.get(b"ImageMask").ok(), Some(Object::Boolean(true))) {+        return None;+    }+    let sw = s.dict.get(b"Width").ok().and_then(num)? as usize;+    let sh = s.dict.get(b"Height").ok().and_then(num)? as usize;+    if sw == 0 || sh == 0 || sw > 20000 || sh > 20000 { return None; }+    let filters = filter_names(doc, &s.dict);+    if filters.iter().any(|f| {+        f.eq_ignore_ascii_case("CCITTFaxDecode") || f.eq_ignore_ascii_case("CCF")+            || f.eq_ignore_ascii_case("JBIG2Decode") || f.eq_ignore_ascii_case("DCTDecode")+            || f.eq_ignore_ascii_case("JPXDecode")+    }) {+        return None;+    }+    // Default Decode is [0 1]; [1 0] inverts the stencil sense.+    let invert = matches!(+        s.dict.get(b"Decode").ok().and_then(|o| deref(doc, o)),+        Some(Object::Array(a)) if a.first().and_then(num) == Some(1.0)+    );+    let data = stream_data(s);+    let row_bytes = (sw + 7) / 8;+    let (w_us, h_us) = (w as usize, h as usize);+    let mut alpha = vec![255u8; w_us * h_us];+    for y in 0..h_us {+        for x in 0..w_us {+            let sx = x * sw / w_us;+            let sy = y * sh / h_us;+            let byte = data.get(sy * row_bytes + sx / 8).copied().unwrap_or(0);+            let mut bit = (byte >> (7 - (sx % 8))) & 1;+            if invert { bit ^= 1; }+            alpha[y * w_us + x] = if bit == 1 { 0 } else { 255 };+        }+    }+    Some(alpha)+}++/// Read an SMask `/Matte` color as an RGB triple (0..1), if present. The matte+/// is given in the base image's colorspace; components are interpreted by arity+/// (gray/RGB/CMYK), which is sufficient for un-premultiplication.+pub(crate) fn read_matte(doc: &Document, dict: &lopdf::Dictionary) -> Option<[f64; 3]> {+    let sm = dict.get(b"SMask").ok().and_then(|o| deref(doc, o))?;+    let smd = sm.as_dict().ok()?;+    let arr = smd.get(b"Matte").ok().and_then(|o| deref(doc, o))?;+    let comps: Vec<f64> = arr.as_array().ok()?.iter().filter_map(num).collect();+    let rgb = match comps.len() {+        1 => [comps[0], comps[0], comps[0]],+        3 => [comps[0], comps[1], comps[2]],+        4 => {+            let (c, m, y, k) = (comps[0], comps[1], comps[2], comps[3]);+            [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]+        }+        _ => return None,+    };+    Some(rgb)+}++/// Un-premultiply an RGBA buffer whose colors were premultiplied against a+/// `/Matte` background, using the already-applied SMask alpha in `rgba`.+/// `c = matte + (c' - matte) / alpha`.+pub(crate) fn apply_matte(rgba: &mut [u8], matte: [f64; 3]) {+    let m = [matte[0] * 255.0, matte[1] * 255.0, matte[2] * 255.0];+    for px in rgba.chunks_exact_mut(4) {+        let a = px[3] as f64 / 255.0;+        if a <= 0.0 { continue; }+        for ch in 0..3 {+            let cp = px[ch] as f64;+            let un = m[ch] + (cp - m[ch]) / a;+            px[ch] = un.round().clamp(0.0, 255.0) as u8;+        }+    }+}+ /// Decode an image's `/SMask` (soft mask) into a `w*h` 8-bit alpha buffer, /// now supporting DCT (JPEG) and JPX and low BPC. pub(crate) fn read_smask(doc: &Document, dict: &lopdf::Dictionary, w: u32, h: u32) -> Option<Vec<u8>> {@@ -1293,6 +1620,71 @@ pub(crate) fn read_smask(doc: &Document, dict: &lopdf::Dictionary, w: u32, h: u3     Some(alpha) } +#[cfg(test)]+mod mask_tests {+    use super::*;++    #[test]+    fn adobe_app14_transform_detected() {+        // SOI + APP14 "Adobe" (transform=2) + SOS.+        let data = vec![+            0xFF, 0xD8,+            0xFF, 0xEE, 0x00, 0x0E, // APP14, len=14+            b'A', b'd', b'o', b'b', b'e', 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x02,+            0xFF, 0xDA,+        ];+        assert_eq!(jpeg_adobe_transform(&data), Some(2));+        // A plain JPEG without the Adobe marker returns None.+        let plain = vec![0xFF, 0xD8, 0xFF, 0xDA];+        assert_eq!(jpeg_adobe_transform(&plain), None);+    }++    #[test]+    fn sof_component_count_read() {+        // SOI + SOF0 declaring 3 components, padded to the segment length.+        let mut data = vec![+            0xFF, 0xD8,+            0xFF, 0xC0, 0x00, 0x11, // SOF0, len=17+            0x08, 0x00, 0x01, 0x00, 0x01, 0x03, // prec, h, w, ncomp=3+        ];+        data.extend(std::iter::repeat(0u8).take(9)); // 3 component specs+        assert_eq!(jpeg_num_components(&data), Some(3));+    }++    #[test]+    fn color_key_masks_cmyk_in_range() {+        // Two CMYK pixels: first inside the key range, second outside.+        let mut rgba = vec![10u8, 20, 30, 255,  40, 50, 60, 255];+        let comps = vec![5u8, 5, 5, 5,  200, 200, 200, 200];+        let ranges = [(0u32, 10), (0, 10), (0, 10), (0, 10)];+        apply_color_key_mask_samples(&mut rgba, &comps, 4, &ranges, 8);+        assert_eq!(rgba[3], 0, "in-range CMYK pixel becomes transparent");+        assert_eq!(rgba[7], 255, "out-of-range pixel stays opaque");+    }++    #[test]+    fn matte_un_premultiplies() {+        // Black matte: c = c' / alpha. c'=100, alpha=128/255 -> ~199.+        let mut rgba = vec![100u8, 100, 100, 128];+        apply_matte(&mut rgba, [0.0, 0.0, 0.0]);+        assert!((198..=201).contains(&rgba[0]), "un-premult ~199, got {}", rgba[0]);+        assert_eq!(rgba[3], 128, "alpha is preserved");+    }++    #[test]+    fn device_size_scales_with_ctm() {+        // Unit square scaled to 500 device px -> ~500 raster, clamped to [64,1024].+        let big = super::shading_device_size(&[500.0, 0.0, 0.0, 400.0, 0.0, 0.0]);+        assert_eq!(big, 500);+        // A tiny footprint clamps up to the 64 minimum.+        let small = super::shading_device_size(&[10.0, 0.0, 0.0, 10.0, 0.0, 0.0]);+        assert_eq!(small, 64);+        // A huge footprint clamps to the 1024 maximum.+        let huge = super::shading_device_size(&[5000.0, 0.0, 0.0, 5000.0, 0.0, 0.0]);+        assert_eq!(huge, 1024);+    }+}+ #[cfg(test)] mod radial_tests {     use super::radial_shading_param;
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 ea206fa33c..f4c1c6c32b 100644--- a/pdf/src/main/rust/src/interpret.rs+++ b/pdf/src/main/rust/src/interpret.rs@@ -249,11 +249,12 @@ pub(crate) fn interpret_content(                     });                     // Helper to apply a dict to gs                     let apply_dict = |dict: &lopdf::Dictionary, gs: &mut GraphicsState, doc: &Document| {+                        // ISO 32000: /CA is the stroking alpha, /ca is the nonstroking (fill) alpha.                         if let Some(v) = dict.get(b"CA").ok().and_then(num) {-                            gs.alpha_fill = v.clamp(0.0,1.0);+                            gs.alpha_stroke = v.clamp(0.0,1.0);                         }                         if let Some(v) = dict.get(b"ca").ok().and_then(num) {-                            gs.alpha_stroke = v.clamp(0.0,1.0);+                            gs.alpha_fill = v.clamp(0.0,1.0);                         }                         if let Some(v) = dict.get(b"LW").ok().and_then(num) {                             gs.line_width = v;@@ -290,6 +291,18 @@ pub(crate) fn interpret_content(                                 }                             }                         }+                        // Overprint: /OP (stroking), /op (nonstroking; defaults+                        // to /OP when absent), /OPM (overprint mode 0|1).+                        if let Some(b) = dict.get(b"OP").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(|o| match o { Object::Boolean(v) => Some(*v), _ => None }) {+                            gs.overprint_stroke = b;+                            gs.overprint_fill = b; // op defaults to OP unless overridden below+                        }+                        if let Some(b) = dict.get(b"op").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(|o| match o { Object::Boolean(v) => Some(*v), _ => None }) {+                            gs.overprint_fill = b;+                        }+                        if let Some(v) = dict.get(b"OPM").ok().and_then(num) {+                            gs.overprint_mode = (v as i64).clamp(0, 1) as u8;+                        }                         // 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() {@@ -301,9 +314,20 @@ pub(crate) fn interpret_content(                                         Some(b"Luminosity") => 1u8,                                         _ => 0u8, // Alpha (default)                                     };+                                    // /BC backdrop color (components in the group's colorspace).+                                    let backdrop = smdict.get(b"BC").ok()+                                        .and_then(|o| deref(doc, o))+                                        .and_then(|o| o.as_array().ok())+                                        .map(|a| a.iter().filter_map(num).collect::<Vec<f64>>())+                                        .filter(|v| !v.is_empty());                                     // /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));+                                        gs.soft_mask = Some(SoftMask {+                                            group_id: *gid,+                                            mask_type,+                                            ctm: gs.ctm,+                                            backdrop,+                                        });                                     }                                 }                             }@@ -431,11 +455,15 @@ pub(crate) fn interpret_content(                     }                 }                 if !text_only && !oc_stack.last().copied().unwrap_or(false) {+                    let sm_start = prims.len();                     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 let Some(m) = gs.soft_mask.clone() {+                        wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth);+                    }                 }                 subpaths.clear(); clip_path_ops.clear();             }@@ -453,10 +481,15 @@ pub(crate) fn interpret_content(                     }                 }                 if !text_only && !oc_stack.last().copied().unwrap_or(false) {+                    let sm_start = prims.len();                     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, gs.blend_mode);+                        let fb = if gs.overprint_fill && gs.blend_mode == BlendMode::Normal { BlendMode::Multiply } else { gs.blend_mode };+                        emit_fill(prims, &subpaths, gs.fill, op.operator == "f*", gs.alpha_fill, fb);+                    }+                    if let Some(m) = gs.soft_mask.clone() {+                        wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth);                     }                 }                 subpaths.clear(); clip_path_ops.clear();@@ -480,16 +513,21 @@ pub(crate) fn interpret_content(                     }                 }                 if !text_only && !oc_stack.last().copied().unwrap_or(false) {+                    let sm_start = prims.len();                     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, gs.blend_mode);+                        let fb = if gs.overprint_fill && gs.blend_mode == BlendMode::Normal { BlendMode::Multiply } else { gs.blend_mode };+                        emit_fill(prims, &subpaths, gs.fill, op.operator.ends_with('*'), gs.alpha_fill, fb);                     }                     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 let Some(m) = gs.soft_mask.clone() {+                        wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth);+                    }                 }                 subpaths.clear(); clip_path_ops.clear();             }@@ -520,7 +558,9 @@ pub(crate) fn interpret_content(                 if !text_only && !oc_stack.last().copied().unwrap_or(false) {                     if let Some(Object::Stream(stream)) = o.first() {                         if let Some(img) = extract_inline_image(doc, stream, gs.fill, &colorspaces) {+                            let sm_start = prims.len();                             if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: 1.0 }); }+                            if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); }                         }                     }                 }@@ -545,7 +585,9 @@ pub(crate) fn interpret_content(                             if subtype == Some(b"Image") {                                 if !text_only && !oc_stack.last().copied().unwrap_or(false) {                                     if let Some(img) = extract_image(doc, stream, gs.fill, &colorspaces) {+                                        let sm_start = prims.len();                                         if prims.len() < MAX_PRIMITIVES { prims.push(Prim::Image { ctm: gs.ctm, w: img.w, h: img.h, format: img.format, data: img.data, alpha: 1.0 }); }+                                        if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); }                                     }                                 }                             } else if subtype == Some(b"Form") && depth < 10 {@@ -579,27 +621,38 @@ pub(crate) fn interpret_content(                                 // 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 active_smask = gs.soft_mask.clone();                                 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 sm_start = prims.len();                                 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 });+                                        // The nonstroking constant alpha (ca) applies to the+                                        // group as a whole when it is painted; NOT ca*CA.+                                        prims.push(Prim::GroupPush { isolated, knockout, alpha: gs.alpha_fill as f32, blend: gs.blend_mode });                                         group_depth+=1;                                     }                                 }                                 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.+                                        // A soft mask does not re-apply to nested Do's inside the+                                        // (masked) form content.                                         sub_gs.soft_mask = None;+                                        // Per PDF 11.6.6: on entering a transparency group the+                                        // alpha constants reset to 1.0 and blend to Normal — they+                                        // are applied when the group's result is composited (via+                                        // GroupPush), not again to each element inside. Without+                                        // this, ca is double-applied and low-alpha groups vanish.+                                        if should_emit_group {+                                            sub_gs.alpha_fill = 1.0;+                                            sub_gs.alpha_stroke = 1.0;+                                            sub_gs.blend_mode = BlendMode::Normal;+                                        }                                         let res_ref = form_res.as_ref().or(resources);                                         interpret_content(                                             doc,@@ -611,35 +664,12 @@ 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,-                                            );-                                        }+                                // Bracket the whole form as the masked content, then+                                // append the mask group (rendered at the mask's set-time CTM).+                                if use_smask {+                                    if let Some(mask) = active_smask {+                                        wrap_with_soft_mask(prims, sm_start, doc, resources, &mask, depth);                                     }-                                    prims.push(Prim::SoftMaskPop);                                 }                             }                         }@@ -722,10 +752,10 @@ pub(crate) fn interpret_content(             }             "SCN" => {                 let comps: Vec<f64> = o.iter().filter_map(num).collect();-                if matches!(gs.stroke_cs, CsKind::Pattern) {+                if matches!(gs.stroke_cs, CsKind::Pattern { .. }) {                     gs.stroke_pattern = o.last().and_then(|obj| obj.as_name().ok()).and_then(|pn| patterns.get(pn).copied());                     if !comps.is_empty() {-                        gs.stroke = uncolored_pattern_argb(&comps);+                        gs.stroke = uncolored_pattern_argb(doc, &gs.stroke_cs, &comps, &colorspaces);                     }                 } else if !comps.is_empty() {                     if let Some(rgb) = eval_cs_to_rgb(doc, &gs.stroke_cs, &comps, &colorspaces) {@@ -735,10 +765,10 @@ pub(crate) fn interpret_content(             }             "scn" => {                 let comps: Vec<f64> = o.iter().filter_map(num).collect();-                if matches!(gs.non_stroke_cs, CsKind::Pattern) {+                if matches!(gs.non_stroke_cs, CsKind::Pattern { .. }) {                     gs.fill_pattern = o.last().and_then(|obj| obj.as_name().ok()).and_then(|pn| patterns.get(pn).copied());                     if !comps.is_empty() {-                        gs.fill = uncolored_pattern_argb(&comps);+                        gs.fill = uncolored_pattern_argb(doc, &gs.non_stroke_cs, &comps, &colorspaces);                     }                 } else if !comps.is_empty() {                     if let Some(rgb) = eval_cs_to_rgb(doc, &gs.non_stroke_cs, &comps, &colorspaces) {@@ -747,6 +777,19 @@ pub(crate) fn interpret_content(                 }             }             "sh" => {+                // Capture the clip extent (device space) that bounds this shading+                // so it can be rasterized at device resolution and, when the+                // shading has no /BBox, cover the whole clip.+                let clip_bbox_device: Option<[f64;4]> = pending_clip.as_ref().map(|pc| {+                    let mut x0 = f64::INFINITY; let mut y0 = f64::INFINITY;+                    let mut x1 = f64::NEG_INFINITY; let mut y1 = f64::NEG_INFINITY;+                    for poly in pc.polys.iter() {+                        for &(x,y) in poly.iter() {+                            x0 = x0.min(x); y0 = y0.min(y); x1 = x1.max(x); y1 = y1.max(y);+                        }+                    }+                    [x0, y0, x1, y1]+                }).filter(|b| b[2] > b[0] && b[3] > b[1]);                 if let Some(to_emit) = pending_clip.take() {                     for poly in to_emit.polys.iter() {                         if poly.len()>=3 && !text_only && !oc_stack.last().copied().unwrap_or(false) && clip_depth < MAX_CLIP_DEPTH && shoelace_area(poly).abs() >= 1e-3 {@@ -759,9 +802,11 @@ pub(crate) fn interpret_content(                     if let Some(Object::Name(name)) = o.first() {                         if let Some(&id) = shadings.get(name) {                             if let Ok(obj) = doc.get_object(id) {-                                if let Some((ctm,w,h,data)) = rasterize_shading(doc, obj, &gs.ctm, &colorspaces, 256) {+                                if let Some((ctm,w,h,data)) = rasterize_shading(doc, obj, &gs.ctm, &colorspaces, 0, clip_bbox_device) {                                     if prims.len() < MAX_PRIMITIVES && !oc_stack.last().copied().unwrap_or(false) {+                                        let sm_start = prims.len();                                         prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: 1.0 });+                                        if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); }                                     }                                 }                             }@@ -905,8 +950,10 @@ pub(crate) fn interpret_content(             }             "Tj" => {                 if let Some(Object::String(bytes, _)) = o.first() {+                    let sm_start = prims.len();                     let adv = show_string(doc, prims, &gs, &fonts, &text_matrix, bytes, depth);                     text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+                    if gs.render_mode <= 2 { if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); } }                 }             }             "'" => {@@ -932,6 +979,7 @@ pub(crate) fn interpret_content(                 }             }             "TJ" => {+                let sm_start = prims.len();                 if let Some(Object::Array(arr)) = o.first() {                     for el in arr {                         match el {@@ -949,6 +997,7 @@ pub(crate) fn interpret_content(                         }                     }                 }+                if gs.render_mode <= 2 { if let Some(m) = gs.soft_mask.clone() { wrap_with_soft_mask(prims, sm_start, doc, resources, &m, depth); } }             }             // Explicit no-ops (documented): rendering intent, and compatibility             // sections have no effect on our flat-primitive output.@@ -974,9 +1023,21 @@ pub(crate) fn read_matrix(operands: &[Object]) -> Option<Mat> {     } } -/// Approximate an RGB color for an uncolored (`/PaintType 2`) pattern's base-/// color operands, by treating them as Gray/RGB/CMYK by arity.-pub(crate) fn uncolored_pattern_argb(comps: &[f64]) -> u32 {+/// Resolve the ARGB base color for an uncolored (`/PaintType 2`) pattern's+/// operands. When the Pattern colorspace declares an underlying base space+/// (`[/Pattern base]`), the operands are interpreted in that space; otherwise+/// they are approximated as Gray/RGB/CMYK by arity.+pub(crate) fn uncolored_pattern_argb(+    doc: &Document,+    cs: &CsKind,+    comps: &[f64],+    cs_resources: &HashMap<Vec<u8>, ObjectId>,+) -> u32 {+    if let CsKind::Pattern { base: Some(base) } = cs {+        if let Some(rgb) = eval_cs_to_rgb(doc, base, comps, cs_resources) {+            return rgb;+        }+    }     match comps.len() {         1 => gray_to_argb(comps[0]),         3 => rgb_to_argb(comps[0], comps[1], comps[2]),@@ -1027,6 +1088,101 @@ fn stroke_outline_quads(subpaths: &[Vec<(f64, f64)>], hw: f64) -> Vec<Vec<(f64, /// 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+/// Render an ExtGState soft-mask group into `prims` as the mask content of a+/// SoftMaskPush/Content/Pop bracket. The group is placed at the CTM captured+/// when the mask was set. For a luminosity mask with a `/BC` backdrop, a+/// backdrop-colored rectangle is painted first so uncovered areas take the+/// backdrop luminance (default black otherwise).+pub(crate) fn render_soft_mask_group(+    doc: &Document,+    resources: Option<&lopdf::Dictionary>,+    mask: &SoftMask,+    prims: &mut Vec<Prim>,+    depth: u32,+) {+    if depth >= MAX_PATTERN_RECURSION as u32 || prims.len() >= MAX_PRIMITIVES {+        return;+    }+    let mstream = match doc.get_object(mask.group_id) {+        Ok(Object::Stream(s)) => s.clone(),+        _ => return,+    };+    let mmatrix = mstream.dict.get(b"Matrix").ok().and_then(read_matrix_obj).unwrap_or(IDENTITY);+    let group_ctm = mat_mul(&mmatrix, &mask.ctm);+    let mres = mstream.dict.get(b"Resources").ok()+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_dict().ok())+        .cloned();+    // /BC backdrop rectangle for luminosity masks.+    if mask.mask_type == 1 {+        if let Some(bc) = &mask.backdrop {+            if let Some(rect) = mstream.dict.get(b"BBox").ok().and_then(|o| read_rect(doc, o)) {+                let cs = mstream.dict.get(b"Group").ok().and_then(|o| deref(doc, o))+                    .and_then(|o| o.as_dict().ok())+                    .and_then(|gd| gd.get(b"CS").ok().and_then(|o| parse_cs_kind(doc, Some(o), &HashMap::new())));+                let argb = cs.as_ref()+                    .and_then(|k| eval_cs_to_rgb(doc, k, bc, &HashMap::new()))+                    .unwrap_or_else(|| match bc.len() {+                        1 => gray_to_argb(bc[0]),+                        3 => rgb_to_argb(bc[0], bc[1], bc[2]),+                        4 => cmyk_to_argb(bc[0], bc[1], bc[2], bc[3]),+                        _ => 0xFF00_0000,+                    });+                let corners = [+                    transform(&group_ctm, rect[0], rect[1]),+                    transform(&group_ctm, rect[2], rect[1]),+                    transform(&group_ctm, rect[2], rect[3]),+                    transform(&group_ctm, rect[0], rect[3]),+                ];+                let poly: Vec<(f64, f64)> = corners.to_vec();+                emit_fill(prims, std::slice::from_ref(&poly), argb, false, 1.0, BlendMode::Normal);+            }+        }+    }+    if let Ok(msub) = Content::decode(&stream_data_with_doc(doc, &mstream)) {+        let mut mgs = GraphicsState::default();+        mgs.ctm = group_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, false);+    }+}++/// Bracket the primitives appended since `start` with the given soft mask so+/// they are drawn only where the mask is opaque/luminous. No-op if nothing was+/// emitted. Reuses the SoftMaskPush/Content/Pop wire prims.+pub(crate) fn wrap_with_soft_mask(+    prims: &mut Vec<Prim>,+    start: usize,+    doc: &Document,+    resources: Option<&lopdf::Dictionary>,+    mask: &SoftMask,+    depth: u32,+) {+    if start >= prims.len() || prims.len() >= MAX_PRIMITIVES {+        return;+    }+    prims.insert(start, Prim::SoftMaskPush { mask_type: mask.mask_type });+    prims.push(Prim::SoftMaskContent);+    render_soft_mask_group(doc, resources, mask, prims, depth);+    prims.push(Prim::SoftMaskPop);+}++/// Bounding box (device space) of a set of polygons, or `None` if empty.+fn polys_device_bbox(polys: &[Vec<(f64, f64)>]) -> Option<[f64;4]> {+    let mut x0 = f64::INFINITY; let mut y0 = f64::INFINITY;+    let mut x1 = f64::NEG_INFINITY; let mut y1 = f64::NEG_INFINITY;+    for poly in polys {+        for &(x,y) in poly.iter() {+            x0 = x0.min(x); y0 = y0.min(y); x1 = x1.max(x); y1 = y1.max(y);+        }+    }+    if x1 > x0 && y1 > y0 { Some([x0, y0, x1, y1]) } else { None }+}+ /// the segments (matching how a real stroke covers the path). pub(crate) fn paint_pattern_stroke(     doc: &Document,@@ -1061,6 +1217,7 @@ pub(crate) fn paint_pattern_stroke(     let hw = ((gs.line_width * scale) / 2.0).max(0.35);      let quads = stroke_outline_quads(subpaths, hw);+    let stroke_bbox = polys_device_bbox(subpaths);     for quad in &quads {         if prims.len() >= MAX_PRIMITIVES { break; }         if quad.len() < 3 || shoelace_area(quad).abs() < 1e-3 { continue; }@@ -1071,7 +1228,7 @@ pub(crate) fn paint_pattern_stroke(         });         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 let Some((ctm, w, h, data)) = rasterize_shading(doc, shobj, &pmat, &HashMap::new(), 0, stroke_bbox) {                     if prims.len() < MAX_PRIMITIVES {                         prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: 1.0 });                     }@@ -1129,7 +1286,8 @@ pub(crate) fn paint_pattern_fill(      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) {+            let fill_bbox = polys_device_bbox(polys);+            if let Some((ctm, w, h, data)) = rasterize_shading(doc, shobj, &pmat, &HashMap::new(), 0, fill_bbox) {                 if prims.len() < MAX_PRIMITIVES {                     prims.push(Prim::Image { ctm, w, h, format: 0, data, alpha: 1.0 });                 }
pdf/src/main/rust/src/jni_bindings.rs
diff --git a/pdf/src/main/rust/src/jni_bindings.rs b/pdf/src/main/rust/src/jni_bindings.rsindex a53cd62e69..f24248e31e 100644--- a/pdf/src/main/rust/src/jni_bindings.rs+++ b/pdf/src/main/rust/src/jni_bindings.rs@@ -62,6 +62,24 @@ use crate::*;         bytes_or_null(&env, save_encrypted(handle as i64, u.as_bytes(), o.as_bytes()))     } +    /// `PdfNative.signCms(byte[], String) -> byte[]`. Detached CMS/PKCS#7+    /// signature (fresh self-signed RSA-2048, SHA-256 with RSA) over `content`,+    /// or null on failure. Replaces the Bouncy Castle path on the Kotlin side.+    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_signCms<'local>(+        mut env: JNIEnv<'local>,+        _class: JClass<'local>,+        content: JByteArray<'local>,+        name: JString<'local>,+    ) -> jbyteArray {+        let data = match env.convert_byte_array(&content) {+            Ok(b) => b,+            Err(_) => return std::ptr::null_mut(),+        };+        let nm = jstr(&mut env, &name);+        bytes_or_null(&env, crate::signing::sign_cms(&data, &nm))+    }+     /// `PdfNative.getPageCount(long) -> int`.     #[no_mangle]     pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_getPageCount<'local>(@@ -590,6 +608,18 @@ use crate::*;         set_checkbox(handle as i64, widget_id, on != 0) as jboolean     } +    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_setChoiceField<'local>(+        mut env: JNIEnv<'local>,+        _class: JClass<'local>,+        handle: jlong,+        widget_id: jlong,+        value: JString<'local>,+    ) -> jboolean {+        let v = jstr(&mut env, &value);+        set_choice_field(handle as i64, widget_id, &v) as jboolean+    }+     /// `PdfNative.saveDocument(long) -> byte[]`. Serialized modified PDF.     #[no_mangle]     pub extern "system" fn Java_com_vayunmathur_pdf_util_PdfNative_saveDocument<'local>(
pdf/src/main/rust/src/lib.rs
diff --git a/pdf/src/main/rust/src/lib.rs b/pdf/src/main/rust/src/lib.rsindex b042c931f9..c20efc6911 100644--- a/pdf/src/main/rust/src/lib.rs+++ b/pdf/src/main/rust/src/lib.rs@@ -30,6 +30,7 @@ pub(crate) use lopdf::content::Content; pub(crate) use lopdf::{dictionary, Dictionary, Document, Object, ObjectId, Stream};  mod crypto;+mod signing; mod filters; mod functions; pub(crate) use functions::*;
pdf/src/main/rust/src/shading.rs
diff --git a/pdf/src/main/rust/src/shading.rs b/pdf/src/main/rust/src/shading.rsindex 0377d72aa3..f7bb495a61 100644--- a/pdf/src/main/rust/src/shading.rs+++ b/pdf/src/main/rust/src/shading.rs@@ -394,7 +394,9 @@ fn parse_type6_7(         };          // 12 boundary control points (p1..p12) and 4 corner colors for this patch.+        // Type 7 additionally has 4 interior control points (p13..p16).         let mut pts: Vec<(f64, f64)> = Vec::with_capacity(12);+        let mut interior: Vec<(f64, f64)> = Vec::with_capacity(4);         let mut cols: Vec<Vec<f64>> = Vec::with_capacity(4);          if flag == 0 || prev_pts.len() < 12 || prev_cols.len() < 4 {@@ -410,7 +412,10 @@ fn parse_type6_7(             if !ok || all.len() < 12 {                 break;             }-            pts = all[0..12].to_vec(); // boundary points (tensor interior ignored)+            pts = all[0..12].to_vec(); // p1..p12 boundary points+            if shading_type == 7 && all.len() >= 16 {+                interior = all[12..16].to_vec(); // p13..p16 tensor interior+            }             let mut cok = true;             for _ in 0..4 {                 match read_color(&mut br) {@@ -438,7 +443,11 @@ fn parse_type6_7(             if !ok {                 break;             }-            // Boundary = shared edge (4) + next 8 new boundary points.+            // Boundary = shared edge (4) + next 8 new boundary points; for tensor+            // the final 4 new points are the interior control points.+            if shading_type == 7 && new_pts.len() >= 12 {+                interior = new_pts[8..12].to_vec();+            }             pts.extend_from_slice(&shared_pts);             pts.extend(new_pts.into_iter().take(8));             if pts.len() < 12 {@@ -464,9 +473,40 @@ fn parse_type6_7(         let c11 = cols.get(2).cloned().unwrap_or_default();         let c10 = cols.get(3).cloned().unwrap_or_default(); -        // Subdivide the Coons surface on an N×N grid.+        // Subdivide the patch surface on an N×N grid. Coons (Type 6) uses the+        // bilinearly-blended boundary surface; tensor (Type 7) uses the full+        // bicubic Bézier defined by the 12 boundary + 4 interior control points.         const N: usize = 8;+        // Build the 4×4 tensor control grid P[i][j] from the PDF point ordering.+        let tensor_grid: Option<[[(f64, f64); 4]; 4]> = if shading_type == 7 && interior.len() == 4 {+            let mut p = [[(0.0, 0.0); 4]; 4];+            p[0][0] = pts[0];  p[0][1] = pts[1];  p[0][2] = pts[2];  p[0][3] = pts[3];+            p[1][3] = pts[4];  p[2][3] = pts[5];  p[3][3] = pts[6];  p[3][2] = pts[7];+            p[3][1] = pts[8];  p[3][0] = pts[9];  p[2][0] = pts[10]; p[1][0] = pts[11];+            p[1][1] = interior[0]; p[1][2] = interior[1]; p[2][2] = interior[2]; p[2][1] = interior[3];+            Some(p)+        } else {+            None+        };+        let bern = |t: f64| -> [f64; 4] {+            let mt = 1.0 - t;+            [mt*mt*mt, 3.0*t*mt*mt, 3.0*t*t*mt, t*t*t]+        };         let surf = |u: f64, v: f64| -> (f64, f64) {+            if let Some(p) = tensor_grid {+                let bu = bern(u);+                let bv = bern(v);+                let mut sx = 0.0;+                let mut sy = 0.0;+                for i in 0..4 {+                    for j in 0..4 {+                        let w = bu[i] * bv[j];+                        sx += w * p[i][j].0;+                        sy += w * p[i][j].1;+                    }+                }+                return (sx, sy);+            }             let left = bezier(e_left, v);             let right = {                 // u=1 edge from C10(v=0) to C11(v=1): reverse e_right (C11->C10)@@ -656,4 +696,40 @@ mod tests {         assert_eq!(br.read(5), Some(0b00000));         assert_eq!(br.read(2), Some(0b11));     }++    // A Type 7 tensor patch whose interior control points are displaced must+    // produce a different surface than the equivalent Type 6 Coons patch (which+    // has no interior points). This guards against silently dropping p13..p16.+    fn tensor_patch_bytes(interior: [(u8, u8); 4]) -> Vec<u8> {+        // 12 boundary points forming a [0,100] square, then 4 interior points.+        let boundary: [(u8, u8); 12] = [+            (0, 0), (0, 33), (0, 66), (0, 100),+            (33, 100), (66, 100), (100, 100),+            (100, 66), (100, 33), (100, 0),+            (66, 0), (33, 0),+        ];+        let mut out = vec![0u8]; // flag = 0 (full patch), 8-bit+        for (x, y) in boundary { out.push(x); out.push(y); }+        for (x, y) in interior { out.push(x); out.push(y); }+        out.extend_from_slice(&[0, 0, 0, 0]); // 4 single-component colors+        out+    }++    #[test]+    fn tensor_interior_changes_surface() {+        // Coord decode maps 0..255 -> 0..255 (identity); one color component.+        let decode = [0.0, 255.0, 0.0, 255.0, 0.0, 1.0];+        // Flat/interpolated interior vs interior pulled hard to the corners.+        let flat = tensor_patch_bytes([(33, 33), (33, 66), (66, 66), (66, 33)]);+        let bulged = tensor_patch_bytes([(0, 0), (0, 100), (100, 100), (100, 0)]);+        let a = parse_type6_7(&flat, 7, 8, 8, 8, 1, &decode);+        let b = parse_type6_7(&bulged, 7, 8, 8, 8, 1, &decode);+        assert!(!a.is_empty() && !b.is_empty(), "both patches should tessellate");+        let verts = |tris: &[(Vertex, Vertex, Vertex)]| -> Vec<(i64, i64)> {+            tris.iter().flat_map(|(p, q, r)| {+                [p, q, r].map(|v| ((v.x * 100.0) as i64, (v.y * 100.0) as i64))+            }).collect()+        };+        assert_ne!(verts(&a), verts(&b), "displaced interior must alter geometry");+    } }
pdf/src/main/rust/src/tests.rs
diff --git a/pdf/src/main/rust/src/tests.rs b/pdf/src/main/rust/src/tests.rsindex d5de7fdff1..8f6020f762 100644--- a/pdf/src/main/rust/src/tests.rs+++ b/pdf/src/main/rust/src/tests.rs@@ -90,6 +90,71 @@ use crate::*;         }     } +    /// A transparency-group form painted under ca=0.05 must composite the group+    /// at alpha 0.05 (not ca*CA = 0.0025), and elements inside the group keep+    /// full alpha — 

Diff truncated.