Modern Apps git

← Modern-Apps.git

pdf: hayro differential tests, fix Type 3, text clip, stroke, DCT (#321)

Commit
51cff9ab6dbc403a74a6f8ed52d5a94b30f5c354
Author
vayun-mathur <[email protected]>
When
2026-08-31 22:42 UTC (3 months ago)
Parents
945da3d

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 76c515a20f..8d38bb2b48 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -114,6 +114,21 @@ dependencies = [  "memchr", ] +[[package]]+name = "alloc-no-stdlib"+version = "2.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"++[[package]]+name = "alloc-stdlib"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"+dependencies = [+ "alloc-no-stdlib",+]+ [[package]] name = "android_system_properties" version = "0.1.5"@@ -342,6 +357,27 @@ dependencies = [  "hybrid-array", ] +[[package]]+name = "brotli"+version = "8.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+ "brotli-decompressor",+]++[[package]]+name = "brotli-decompressor"+version = "5.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+]+ [[package]] name = "bumpalo" version = "3.20.3"@@ -354,12 +390,38 @@ version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" +[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]+ [[package]] name = "byteorder" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"+ [[package]] name = "bytes" version = "1.12.1"@@ -564,6 +626,15 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]]+name = "color"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf"+dependencies = [+ "bytemuck",+]+ [[package]] name = "colorchoice" version = "1.0.5"@@ -1032,6 +1103,15 @@ dependencies = [  "windows-sys 0.61.2", ] +[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]+ [[package]] name = "euicc" version = "0.1.0"@@ -1064,6 +1144,21 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70ed8646f3993cad0585c6669ffba6f7e5440a0bfb0a1f16600cae33ce7cf307" +[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "fearless_simd"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"+ [[package]] name = "ff" version = "0.13.1"@@ -1130,6 +1225,21 @@ dependencies = [  "miniz_oxide", ] +[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "font-types"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"+dependencies = [+ "bytemuck",+]+ [[package]] name = "form_urlencoded" version = "1.2.2"@@ -1220,6 +1330,23 @@ dependencies = [  "polyval", ] +[[package]]+name = "glifo"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e"+dependencies = [+ "bytemuck",+ "foldhash",+ "hashbrown",+ "log",+ "peniko",+ "png",+ "skrifa",+ "smallvec",+ "vello_common 0.0.9",+]+ [[package]] name = "group" version = "0.13.0"@@ -1231,6 +1358,15 @@ dependencies = [  "subtle", ] +[[package]]+name = "guillotiere"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab"+dependencies = [+ "euclid",+]+ [[package]] name = "half" version = "2.7.1"@@ -1247,6 +1383,23 @@ name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+dependencies = [+ "foldhash",+]++[[package]]+name = "hayro"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4caa128ab87fd48ffb7490617cf93f77f606820dffbc9fd9ef6ab0ed077f56d"+dependencies = [+ "bytemuck",+ "hayro-interpret",+ "image",+ "kurbo",+ "pic-scale",+ "vello_cpu",+]  [[package]] name = "hayro-ccitt"@@ -1254,13 +1407,74 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" +[[package]]+name = "hayro-cmap"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d285dc30731c8485de5fa732fbdf2b3affdf01e4da7c2135022ca6fa664bf6"+dependencies = [+ "brotli",+ "hayro-postscript",+]++[[package]]+name = "hayro-interpret"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2613d0406898995042d0794c4245b2f2fba1246490c8ac593769bba6551129d"+dependencies = [+ "bitflags 2.13.1",+ "hayro-cmap",+ "hayro-syntax",+ "kurbo",+ "moxcms",+ "phf",+ "rustc-hash",+ "siphasher",+ "skrifa",+ "smallvec",+ "yoke",+]+ [[package]] name = "hayro-jbig2" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69374b3668dd45aeb3d3145cda68f2c7b4f223aaa2511e67d076f1c7d741388d" dependencies = [+ "fearless_simd",+ "hayro-ccitt",+]++[[package]]+name = "hayro-jpeg2000"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1"+dependencies = [+ "fearless_simd",+]++[[package]]+name = "hayro-postscript"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "885c5ef0654933139a9b9546fc2c69e18d37f38aa2520f079092b1be18f1fcaa"++[[package]]+name = "hayro-syntax"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0edeafd70aa2db743de8ede8637d07ec87db05efe69cde371d03f1b185fcef27"+dependencies = [+ "flate2",  "hayro-ccitt",+ "hayro-jbig2",+ "hayro-jpeg2000",+ "memchr",+ "rustc-hash",+ "smallvec",+ "zune-jpeg", ]  [[package]]@@ -1479,6 +1693,19 @@ dependencies = [  "icu_properties", ] +[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "moxcms",+ "num-traits",+ "png",+]+ [[package]] name = "indenter" version = "0.3.4"@@ -1684,6 +1911,18 @@ dependencies = [  "zeroize", ] +[[package]]+name = "kurbo"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"+dependencies = [+ "arrayvec",+ "euclid",+ "polycool",+ "smallvec",+]+ [[package]] name = "lazy_static" version = "1.5.0"@@ -1767,6 +2006,12 @@ dependencies = [  "windows-link", ] +[[package]]+name = "linebender_resource_handle"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"+ [[package]] name = "linux-raw-sys" version = "0.4.15"@@ -1887,6 +2132,16 @@ dependencies = [  "jni", ] +[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]+ [[package]] name = "network_location_position_estimation_rust" version = "0.1.0"@@ -2124,6 +2379,7 @@ dependencies = [  "fax",  "flate2",  "getrandom 0.2.17",+ "hayro",  "hayro-jbig2",  "indexmap",  "jni",@@ -2145,12 +2401,67 @@ dependencies = [  "base64ct", ] +[[package]]+name = "peniko"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6"+dependencies = [+ "bytemuck",+ "color",+ "kurbo",+ "linebender_resource_handle",+ "smallvec",+]+ [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]]+name = "phf"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+dependencies = [+ "phf_macros",+ "phf_shared",+]++[[package]]+name = "phf_generator"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"+dependencies = [+ "fastrand",+ "phf_shared",+]++[[package]]+name = "phf_macros"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"+dependencies = [+ "phf_generator",+ "phf_shared",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "phf_shared"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+dependencies = [+ "siphasher",+]+ [[package]] name = "photos_fx" version = "0.1.0"@@ -2158,6 +2469,16 @@ dependencies = [  "jni", ] +[[package]]+name = "pic-scale"+version = "0.7.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4c80d88d5c31215ceec2862abb2504860c715b8e2545a5ab15b62a3d097f30d"+dependencies = [+ "num-traits",+ "pxfm",+]+ [[package]] name = "pin-project-lite" version = "0.2.17"@@ -2202,6 +2523,19 @@ dependencies = [  "plotters-backend", ] +[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.1",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide",+]+ [[package]] name = "poly1305" version = "0.8.0"@@ -2213,6 +2547,15 @@ dependencies = [  "universal-hash", ] +[[package]]+name = "polycool"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"+dependencies = [+ "arrayvec",+]+ [[package]] name = "polyval" version = "0.6.2"@@ -2368,6 +2711,12 @@ version = "2.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" +[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"+ [[package]] name = "quick-xml" version = "0.37.5"@@ -2512,6 +2861,16 @@ dependencies = [  "crossbeam-utils", ] +[[package]]+name = "read-fonts"+version = "0.39.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"+dependencies = [+ "bytemuck",+ "font-types",+]+ [[package]] name = "redox_syscall" version = "0.5.18"@@ -2813,6 +3172,22 @@ dependencies = [  "tinyvec", ] +[[package]]+name = "siphasher"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"++[[package]]+name = "skrifa"+version = "0.42.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"+dependencies = [+ "bytemuck",+ "read-fonts",+]+ [[package]] name = "slab" version = "0.4.12"@@ -3226,6 +3601,53 @@ dependencies = [  "wasm-bindgen", ] +[[package]]+name = "vello_common"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee"+dependencies = [+ "bytemuck",+ "fearless_simd",+ "guillotiere",+ "hashbrown",+ "log",+ "peniko",+ "png",+ "smallvec",+ "thiserror 2.0.19",+]++[[package]]+name = "vello_common"+version = "0.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750"+dependencies = [+ "bytemuck",+ "fearless_simd",+ "guillotiere",+ "hashbrown",+ "log",+ "peniko",+ "png",+ "smallvec",+ "thiserror 2.0.19",+]++[[package]]+name = "vello_cpu"+version = "0.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0"+dependencies = [+ "bytemuck",+ "glifo",+ "hashbrown",+ "png",+ "vello_common 0.0.8",+]+ [[package]] name = "version_check" version = "0.9.5"@@ -3798,3 +4220,18 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]
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 34246e2a5a..6d265f0a5e 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -116,6 +116,7 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.TextFieldValue+import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import kotlinx.coroutines.flow.collectLatest import androidx.compose.ui.unit.sp@@ -1282,12 +1283,17 @@ fun PdfOutlineDrawer(  * Takes a decoded [SafePdfPage] rather than a document handle, so a `@Preview` can render a  * hand-built page (the primitives are plain data; only producing them needs the native  * renderer).+ *+ * A null [page] with a non-null [failureReason] is a page that will never arrive, and shows a+ * placeholder instead of a spinner. Without that distinction a decode failure, a caught native+ * panic and "still loading" all present as the same indefinite spinner.  */ @Composable fun SafePdfPageCanvas(     page: SafePdfPage?,     modifier: Modifier = Modifier,     placeholderRatio: Float? = null,+    failureReason: String? = null,     overlays: @Composable BoxWithConstraintsScope.(cw: Float, ch: Float, scale: Float) -> Unit = { _, _, _ -> }, ) {     // A wrong placeholder ratio makes the item change height the moment the page decodes,@@ -1308,7 +1314,20 @@ fun SafePdfPageCanvas(             .clipToBounds()     ) {         if (page == null || page.width <= 0f) {-            CircularProgressIndicator(Modifier.align(Alignment.Center))+            if (failureReason != null) {+                // A page that will never arrive. A spinner here is a lie that never resolves,+                // and is why this whole class of failure went unreported: the reason is logged+                // for the bug report, the user just needs to know this page is not coming.+                Text(+                    text = stringResource(R.string.pdf_page_failed),+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.align(Alignment.Center).padding(16.dp),+                )+            } else {+                CircularProgressIndicator(Modifier.align(Alignment.Center))+            }             return@BoxWithConstraints         }         val decoded = page@@ -1368,8 +1387,8 @@ private fun SafePdfPageItem(     onAddPolyPoint: (Offset) -> Unit,     onLinkPage: (Int) -> Unit, ) {-    val page by produceState<SafePdfPage?>(null, document, index, version) {-        value = document.renderPage(index)+    val pageLoad by produceState<SafePdfDocument.PageLoad?>(null, document, index, version) {+        value = document.renderPageResult(index)     }     val annotations by produceState(emptyList<SafeAnnotation>(), document, index, version) {         value = if (editMode) document.annotations(index) else emptyList()@@ -1381,14 +1400,19 @@ private fun SafePdfPageItem(         value = if (!editMode) document.links(index) else emptyList()     } -    val current = page+    val current = (pageLoad as? SafePdfDocument.PageLoad.Decoded)?.page+    val failureReason = (pageLoad as? SafePdfDocument.PageLoad.Failed)?.reason      // Report this page's width so the viewer can raise the zoom cap for large pages.     LaunchedEffect(current?.width) {         current?.width?.let { if (it > 0f) onPageWidth(it) }     } -    SafePdfPageCanvas(current, placeholderRatio = document.knownAspectRatio(index)) { cw, ch, scale ->+    SafePdfPageCanvas(+        current,+        placeholderRatio = document.knownAspectRatio(index),+        failureReason = failureReason,+    ) { cw, ch, scale ->         // Non-null inside the overlay slot: SafePdfPageCanvas only invokes it once the page         // has been decoded.         val decoded = current!!@@ -2869,7 +2893,6 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {         return p     }     val textClipPath = android.graphics.Path()-    var hasTextClip = false     val glyphPathPaint = android.graphics.Paint().apply { isAntiAlias = true }     val tmpGlyphPath = android.graphics.Path() @@ -2950,8 +2973,14 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {             }              is PdfPrimitive.Text -> {-                // Embedded-font glyphs are painted via their real outline as Fill-                // prims; this Text is kept only for selection/search — never painted.+                // `outline` means "skip this record entirely" — no paint AND no clip+                // contribution — not merely "already painted". Modes 0-2 set it because+                // Rust already inked the glyph as Fill/Stroke prims from its real contours+                // and there is no clip to build, so only the selection/search payload is+                // left. Modes 4-6 now paint from those same real contours (draw.rs) but+                // deliberately send `outline = false`, because this check sits ABOVE the+                // clip accumulator below and would take the aperture with it; they are made+                // non-painting by `argb = 0` instead. Do not widen this to the clip modes.                 if (prim.outline) continue                 if (prim.text.isBlank()) continue                 val origin = map(prim.origin)@@ -3038,11 +3067,33 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {                 // Accumulate glyph outlines for text-clip render modes (Tr 4-7),                 // applied at the following TextClipApply marker. Use styled glyphPathPaint                 // so clip matches bold/italic visual.+                //+                // KNOWN LIMITATION: the aperture is derived from the SUBSTITUTE face via+                // getTextPath, never from the document's embedded outline — Rust sends a+                // string here, not contours. Modes 4-6 now take their INK from the real+                // embedded contours (draw.rs), so ink and aperture come from different+                // sources and disagree by up to about a third of their union. That is the+                // ceiling, not the typical case: pdfTypeface() matches the generic family+                // and the bold/italic style the wire carries, so the mismatch is a weight+                // or metric difference within the right family, and a correctly matched+                // weight lands below it. A wholly wrong family would be worse but needs+                // Rust's family detection to be wrong, which is a separate defect.+                // Both shapes were substitute-derived before C4, so they were wrong+                // together and this was invisible; it is newly VISIBLE, not newly wrong.+                // Fixing it means carrying the real contours across the wire — see the+                // carrier constraint on ClipPush above.+                //+                // CONTRACT: every Text at rm 4..7 MUST be followed by a TextClipApply.+                // `textClipPath` is reset ONLY in that arm, so a record that never gets a+                // marker leaves its outlines pending and folds them into the NEXT text+                // object's clip. Rust guarantees this by latching on the same condition it+                // emits the record under; a latch predicate that misses an emit path+                // (e.g. the whole-run no-font-metrics record, which bypasses for_each_code)+                // breaks it.                 if (rm in 4..7) {                     tmpGlyphPath.reset()                     glyphPathPaint.getTextPath(prim.text, 0, prim.text.length, origin.x, origin.y, tmpGlyphPath)                     textClipPath.addPath(tmpGlyphPath)-                    hasTextClip = true                 }             } @@ -3155,6 +3206,14 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {             is PdfPrimitive.ClipPush -> {                 // Save and apply clip; prefer the bezier-retentive path (v4) for                 // accurate curved clips, falling back to the flattened polyline.+                //+                // An empty path here means DO NOT NARROW — the opposite of TextClipApply+                // below, which narrows to nothing. Deliberate: Rust drops an empty ClipPush+                // entirely (interpret.rs), so one arriving here is a degenerate `W n` whose+                // ClipPop would otherwise release an enclosing clip early, whereas an empty+                // text clip is a real §9.4.3 intersection against no outlines. Both contracts+                // are pinned by tests. Do not "harmonize" them, and do not route glyph+                // outlines through ClipPush — it would silently invert the text-clip case.                 nativeCanvas.save()                 saveCount++                 val ops = prim.pathOps@@ -3184,15 +3243,16 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) {             }              is PdfPrimitive.TextClipApply -> {-                // Intersect the accumulated glyph outlines into the clip. Paired-                // with a later ClipPop (Rust incremented the clip depth).+                // §9.4.3: at ET the accumulated glyph outlines are combined with the current+                // clip BY INTERSECTION. An empty accumulation intersects to EMPTY, not to+                // absent, so clip unconditionally — a Path with no contours has an empty+                // region and yields exactly that. Skipping the clip instead would let the+                // content that should show only inside the letterforms paint over the whole+                // page. Paired with a later ClipPop (Rust incremented the clip depth).                 nativeCanvas.save()                 saveCount++-                if (hasTextClip) {-                    nativeCanvas.clipPath(textClipPath)-                }+                nativeCanvas.clipPath(textClipPath)                 textClipPath.reset()-                hasTextClip = false             }              is PdfPrimitive.GroupPush -> {
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 92f7f9090e..6a73d717c0 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -64,26 +64,47 @@ class SafePdfDocument private constructor(         return bytes     } +    /**+     * Outcome of decoding one page. The viewer needs to tell "not decoded yet" apart from+     * "decode failed permanently": both used to surface as a null page, so a caught Rust panic,+     * a null JNI return and a wire parse failure all rendered as the same indefinite spinner and+     * the whole class of missing-content bugs was invisible in the field.+     */+    sealed interface PageLoad {+        data class Decoded(val page: SafePdfPage) : PageLoad+        /** [reason] is a log/diagnostic string, not user-facing copy. */+        data class Failed(val reason: String) : PageLoad+    }+     /** Decode page [index] (0-based), or `null` if the native render fails. */-    suspend fun renderPage(index: Int): SafePdfPage? = withContext(Dispatchers.IO) {-        synchronized(cache) { cache[index] }?.let { return@withContext it }+    suspend fun renderPage(index: Int): SafePdfPage? =+        (renderPageResult(index) as? PageLoad.Decoded)?.page++    /** As [renderPage], but reports WHY a page is absent so the UI can say so. */+    suspend fun renderPageResult(index: Int): PageLoad = withContext(Dispatchers.IO) {+        synchronized(cache) { cache[index] }?.let { return@withContext PageLoad.Decoded(it) }         // A single unrenderable page must not take down the viewer: the native         // side throws a RuntimeException on an uncaught panic (see the         // catch_unwind boundary in jni_bindings.rs), and a corrupt wire buffer-        // could throw during parse. Degrade either to a skipped (null) page.-        val bytes = runCatching { PdfNative.renderPage(handle, index) }+        // could throw during parse. Degrade either to a failed page.+        val rendered = runCatching { PdfNative.renderPage(handle, index) }             .onFailure { android.util.Log.w(TAG, "native renderPage threw for page $index", it) }-            .getOrNull()+        rendered.exceptionOrNull()?.let {+            return@withContext PageLoad.Failed("native renderer failed: ${it.javaClass.simpleName}")+        }+        val bytes = rendered.getOrNull()         if (bytes == null) {             android.util.Log.w(TAG, "native renderPage returned no data for page $index")-            return@withContext null+            return@withContext PageLoad.Failed("native renderer returned no data")         }-        val page = runCatching { SafePdfParser.parse(bytes) }+        val parsed = runCatching { SafePdfParser.parse(bytes) }             .onFailure {                 android.util.Log.w(TAG, "wire parse failed for page $index (${bytes.size} bytes)", it)             }-            .getOrNull()-            ?: return@withContext null+        val page = parsed.getOrNull()+            ?: return@withContext PageLoad.Failed(+                "wire parse failed: ${parsed.exceptionOrNull()?.javaClass?.simpleName}"+            )         pageSizes[index] = floatArrayOf(page.width, page.height)         synchronized(cache) {             cachedBytes += pageWeightBytes(page)@@ -102,7 +123,7 @@ class SafePdfDocument private constructor(                 cachedBytes = (cachedBytes - pageWeightBytes(displaced)).coerceAtLeast(0L)             }         }-        page+        PageLoad.Decoded(page)     }      /**
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 48c69b83dd..98c75e6d97 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -145,6 +145,37 @@ object SafePdfParser {      * which is why exceeding it skips the one primitive instead of ending the page.      */     private const val MAX_IMAGE_DATA_BYTES = 16 * 1024 * 1024++    /**+     * Decoded-pixel budget, deliberately a SEPARATE constant from [MAX_IMAGE_DATA_BYTES] even+     * though the two currently hold the same literal: one counts compressed bytes on the wire,+     * the other counts pixels after decode (16 Mi pixels is 64 MB of ARGB_8888). The same+     * conflation exists on the Rust side as `MAX_IMAGE_BYTES` / `MAX_IMAGE_PIXELS`; sharing one+     * literal between the two is how a change to either silently moves the other.+     *+     * Enforced per FORMAT, not globally — see `decodeBitmap`.+     *+     * TWIN of `graphics_state.rs:286`, and the invariant is ONE-DIRECTIONAL:+     * this value must be >= Rust's, never <.+     *+     * `images.rs:848` decimates until `out_w * out_h <= MAX_IMAGE_PIXELS` (Rust's), then the+     * `format == 0` branch of `decodeBitmap` drops anything above this one. If this were+     * LOWERED below Rust's, Rust would emit rasters in the gap believing it had decimated them+     * to fit, and they would vanish here — the large-CCITT bug (F13) silently returning, with+     * both sides individually "correct" and no diagnostic on either. Raising it is safe.+     *+     * Same shape as `wire.rs`'s `WIRE_VERSION <= kotlin_version` check: the consumer may run+     * ahead of the producer, never behind. Written as a bare literal with an explicit type so+     * that check's file-reading approach can be pointed at this line too.+     */+    private const val MAX_IMAGE_PIXELS: Long = 16777216 // 16 * 1024 * 1024++    /**+     * TWIN of `graphics_state.rs:284` (used at `images.rs:1078`), with the same+     * consumer->=producer invariant as [MAX_IMAGE_PIXELS]: Rust refuses an image past its+     * value, so a SMALLER value here drops images Rust considered valid.+     */+    private const val MAX_IMAGE_DIM: Int = 20000     /**      * Cap on a tiling pattern's lattice extent per axis. The extent only decides how large a      * region the REPEAT shader is asked to cover, so a big count is not itself expensive, but@@ -223,37 +254,43 @@ object SafePdfParser {          val firstInt = buf.int         val wireVersion: Int-        val width: Float-        val height: Float-        val countRaw: Int+        val rawWidth: Float+        val rawHeight: Float+        val rawCount: Int          if (firstInt == WIRE_MAGIC) {             if (buf.remaining() < 16) throw IllegalArgumentException("v2/v3 header truncated")             wireVersion = buf.int-            width = buf.float-            height = buf.float-            countRaw = buf.int+            rawWidth = buf.float+            rawHeight = buf.float+            rawCount = buf.int         } else {             // v1 legacy: firstInt was actually width bits, reinterpret             wireVersion = 1-            width = java.lang.Float.intBitsToFloat(firstInt)-            height = buf.float-            countRaw = buf.int+            rawWidth = java.lang.Float.intBitsToFloat(firstInt)+            rawHeight = buf.float+            rawCount = buf.int         }          // Safety guards: count caps, version enforcement, dimension sanity.-        // NaN is checked explicitly: every comparison against it is false, so a NaN width-        // passes `<= 0f` and `> 20000f` alike and reaches SafePdfPageCanvas, whose+        //+        // CLAMP, DO NOT THROW. A throw here happens before the per-primitive guard below, so+        // renderPage turns the whole page into null and the UI shows an indefinite spinner —+        // and the Rust producer carries no matching 20000pt bound, so it can legitimately emit+        // a page this side used to reject. Large-format CAD and poster PDFs land here and every+        // real viewer renders them. An over-large page drawn at a clamped size beats a page that+        // never appears.+        //+        // NaN is handled by the same expression: every comparison against it is false, so it+        // takes the fallback rather than reaching SafePdfPageCanvas, whose         // `Modifier.aspectRatio(width / height)` requires a ratio > 0 and throws on NaN —         // taking down the composition rather than the one page.-        if (!width.isFinite() || !height.isFinite() ||-            width <= 0f || height <= 0f || width > 20000f || height > 20000f-        ) {-            throw IllegalArgumentException("Invalid page dimensions $width x $height")-        }-        if (countRaw < 0) {-            throw IllegalArgumentException("Negative primitive count: $countRaw")+        val width = if (rawWidth.isFinite() && rawWidth > 0f) rawWidth.coerceAtMost(20000f) else 612f+        val height = if (rawHeight.isFinite() && rawHeight > 0f) rawHeight.coerceAtMost(20000f) else 792f+        if (width != rawWidth || height != rawHeight) {+            android.util.Log.w(TAG, "page dimensions $rawWidth x $rawHeight out of range, clamped to $width x $height")         }+        val countRaw = rawCount.coerceAtLeast(0)         val count = countRaw.coerceAtMost(MAX_PRIMITIVES)         if (count < countRaw) {             android.util.Log.w(TAG, "primitive count $countRaw exceeds $MAX_PRIMITIVES, rendering the first $count")@@ -271,11 +308,13 @@ object SafePdfParser {         // 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) {-            if (wireVersion > WIRE_VERSION) {-                android.util.Log.w("SafePdfParser", "Wire version $wireVersion > $WIRE_VERSION, attempting forward compat parse")-            } else {-                throw IllegalArgumentException("Unsupported wire version: $wireVersion")-            }+            // Neither direction throws: a throw here becomes a null page and an indefinite+            // spinner. An older-than-known version degrades the same way a newer one does —+            // parse what the tags allow and drop what they do not.+            android.util.Log.w(+                "SafePdfParser",+                "Wire version $wireVersion outside 1..$WIRE_VERSION, attempting best-effort parse",+            )         }          val primitives = ArrayList<PdfPrimitive>(count.coerceAtMost(4096))@@ -464,13 +503,20 @@ object SafePdfParser {                     val ctm = FloatArray(6) { buf.float }                     val w = buf.int                     val h = buf.int-                    if (w <= 0 || h <= 0 || w > 20000 || h > 20000 ||-                        w.toLong() * h.toLong() > 16 * 1024 * 1024-                    ) {+                    if (w <= 0 || h <= 0 || w > MAX_IMAGE_DIM || h > MAX_IMAGE_DIM) {                         // Unusable dimensions: consume this payload EXACTLY so the stream                         // stays in sync, then drop the primitive. If it cannot be skipped                         // cleanly the buffer is untrustworthy, so stop rather than decode                         // garbage from a desynced offset.+                        //+                        // The PIXEL budget is deliberately NOT tested here. `format` is not+                        // read until below, so a test here can only reject every format+                        // alike — and Rust drops its own pixel guard for the JPEG+                        // passthrough precisely because the platform decoder subsamples it+                        // (images.rs:1082-1087). Rejecting here deleted every JPEG over+                        // 16 Mpx, which is an ordinary phone photo, with no bitmap, no log+                        // and nothing in logcat. The budget now applies per format in+                        // `decodeBitmap`, where the memory is actually committed.                         val fixed = 1 + (if (isV9) 4 else 0) + (if (isV10) 1 else 0) +                             (if (isV11) 1 else 0) + 4                         if (buf.remaining() < fixed) break@@ -831,9 +877,26 @@ object SafePdfParser {         return ops     } +    /**+     * Smallest power-of-two subsample bringing `w*h` within [MAX_IMAGE_PIXELS].+     * `BitmapFactory` rounds `inSampleSize` DOWN to a power of two, so compute one directly+     * rather than hand it a ratio it would round the wrong way (a rounded-down sample size+     * decodes LARGER than asked, which is the direction that OOMs).+     */+    internal fun sampleSizeFor(w: Int, h: Int): Int {+        var s = 1+        while ((w.toLong() / s) * (h.toLong() / s) > MAX_IMAGE_PIXELS) s = s shl 1+        return s+    }+     /** Decode an image payload: format 1 = JPEG bytes, 0 = raw RGBA8888. */     private fun decodeBitmap(w: Int, h: Int, format: Int, data: ByteArray): android.graphics.Bitmap? {-        if (w <= 0 || h <= 0 || w > 20000 || h > 20000 || w.toLong()*h.toLong() > 16*1024*1024) return null+        if (w <= 0 || h <= 0 || w > MAX_IMAGE_DIM || h > MAX_IMAGE_DIM) return null+        // The pixel budget is per format. The raw branch below allocates `w*h` ints before it+        // can do anything, so it must be refused outright — and Rust decimates that path, so+        // an oversized raw image is a contract violation rather than ordinary input. A JPEG+        // commits nothing until the decoder runs and is scaled down there instead.+        if (format != 1 && w.toLong() * h.toLong() > MAX_IMAGE_PIXELS) return null         return try {             when (format) {                 1 -> {@@ -841,7 +904,13 @@ object SafePdfParser {                         android.util.Log.w("SafePdfParser", "JPEG too large ${data.size}")                         null                     } else {-                        android.graphics.BitmapFactory.decodeByteArray(data, 0, data.size)+                        // Subsample instead of dropping. Rust hands the JPEG over at full+                        // dimensions deliberately (images.rs:1082-1087) because this decoder+                        // is what is supposed to scale it; without inSampleSize it decodes at+                        // full size, so a 20 MP photo would commit ~80 MB of ARGB_8888.+                        val opts = android.graphics.BitmapFactory.Options()+                        opts.inSampleSize = sampleSizeFor(w, h)+                        android.graphics.BitmapFactory.decodeByteArray(data, 0, data.size, opts)                     }                 }                 0 -> {
pdf/src/main/res/values/strings.xml
diff --git a/pdf/src/main/res/values/strings.xml b/pdf/src/main/res/values/strings.xmlindex f1909751b2..942fe7ce10 100644--- a/pdf/src/main/res/values/strings.xml+++ b/pdf/src/main/res/values/strings.xml@@ -90,4 +90,6 @@     <string name="outline">Outline</string>     <!-- Button: add signature annotation -->     <string name="sign">Sign</string>+    <!-- PDF viewer, shown in place of a page that could not be decoded -->+    <string name="pdf_page_failed">This page could not be displayed</string> </resources>
pdf/src/main/rust/Cargo.toml
diff --git a/pdf/src/main/rust/Cargo.toml b/pdf/src/main/rust/Cargo.tomlindex d0e273fb6a..8d64f7d232 100644--- a/pdf/src/main/rust/Cargo.toml+++ b/pdf/src/main/rust/Cargo.toml@@ -37,6 +37,25 @@ getrandom.workspace = true rand.workspace = true der.workspace = true +[dev-dependencies]+# Independent reference renderer for `reference_diff_tests.rs`. TEST-ONLY.+#+# Every other test in this crate is self-referential: it asserts the renderer+# does what this team decided it should do, so a clause misread the same way by+# the implementer and by the reviewers passes every test. `hayro` is a second,+# unrelated implementation of the same spec (pure Rust, CPU-only via vello_cpu,+# `#![forbid(unsafe_code)]`, Apache-2.0 OR MIT — the MIT arm is compatible with+# this crate's GPL-2.0-only, and a dev-dependency is not distributed anyway).+#+# It CANNOT reach the shipped cdylib: cargo only builds dev-dependencies for+# test/bench/example targets, never for `--lib`. Verified with+#   cargo tree -p pdf_render --edges normal --target aarch64-linux-android+# which does not mention hayro. See the module header of+# `src/reference_diff_tests.rs` for the full argument and the caveat that+# `hayro-jbig2` is a SHARED component (also a normal dependency above), so JBIG2+# is deliberately outside the differential corpus.+hayro = "0.7.1"+ [profile.release] opt-level = 3 lto = true
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 bc4eb94a60..259428696d 100644--- a/pdf/src/main/rust/src/annotations.rs+++ b/pdf/src/main/rust/src/annotations.rs@@ -131,6 +131,20 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:         None => return,     }; +    // §12.7.2 Table 218: when the AcroForm sets /NeedAppearances the consumer+    // SHALL construct field appearances from /V and /DA, so the flag wins over a+    // /AP that is present but stale. Without the flag a real /AP wins, and a+    // Widget reaches the same synthesis only through+    // `synthesize_annotation_appearance` below — i.e. when there is no usable+    // /AP at all.+    if dict.get(b"Subtype").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(|o| o.as_name().ok())+        == Some(b"Widget".as_ref())+        && crate::forms::need_appearances(doc)+        && render_widget_value(doc, dict, rect, base, prims)+    {+        return;+    }+     // Resolve the normal appearance: /AP /N is either a stream or a subdictionary     // of appearance states selected by /AS. When absent, synthesize a basic     // appearance for common markup/shape annotation types.@@ -145,13 +159,45 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:     let normal = match ap.get(b"N").ok().and_then(|o| deref(doc, o)) {         Some(Object::Stream(s)) => s,         Some(Object::Dictionary(states)) => {-            let as_name = dict.get(b"AS").ok().and_then(|o| o.as_name().ok());+            // §7.3.10 lets any object be indirect. An indirect /AS read as a+            // plain name yields None, which falls into the no-/AS branch below+            // and renders a checkbox whose state was set indirectly as unchecked+            // — or draws nothing at all. /F, /Subtype, /C and /CA are all+            // dereferenced in this file; /AS was the outlier.+            let as_name = dict+                .get(b"AS")+                .ok()+                .and_then(|o| deref(doc, o).or(Some(o)))+                .and_then(|o| o.as_name().ok());             let picked = match as_name {-                // /AS present: it selects the state. If it names a state that is-                // absent, fall back to "Off" (a button's default) and otherwise-                // draw nothing — NOT an arbitrary entry, which is-                // nondeterministic and would render an unchecked box as checked.-                Some(n) => states.get(n).ok().or_else(|| states.get(b"Off").ok()),+                // §12.5.5 defines no fallback for an /AS that names a state the+                // /N dictionary does not hold, so this is a judgement about+                // malformed input. The name itself decides the direction:+                //+                //   /AS = /Off, absent — blank IS the off appearance, and+                //   omitting the /Off entry is a normal way to encode it. Draw+                //   nothing, which the synthesis fallback below does.+                //+                //   /AS = anything else, absent — the file is asserting this+                //   widget is ON. Falling back to /Off then renders a checked+                //   box as unchecked, and if /Off is absent too it renders+                //   NOTHING at all. When exactly one non-Off state exists it is+                //   unambiguously the on-art under a different export name+                //   (/Yes vs /On vs /1), so use it. That is not the+                //   "nondeterministic arbitrary entry" this used to warn about:+                //   it is taken only when /AS has explicitly said not-Off, so it+                //   cannot turn an unchecked box into a checked one.+                Some(n) => states.get(n).ok().or_else(|| {+                    if n == b"Off" {+                        return None;+                    }+                    let mut on: Vec<&Object> =+                        states.iter().filter(|(k, _)| k.as_slice() != b"Off").map(|(_, v)| v).collect();+                    match on.len() {+                        1 => Some(on.remove(0)),+                        _ => states.get(b"Off").ok(),+                    }+                }),                 // /AS absent is malformed (§12.5.5, Table 168 requires it when /N                 // is a subdictionary). Prefer "Off"; failing that, a single entry                 // is unambiguous, so use the real appearance rather than@@ -200,6 +246,12 @@ pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base:      let ops = crate::content::stream_operations(doc, normal);     if ops.is_empty() {+        // `objects.rs` returns an empty operation list for a stream it could not+        // decode at all (unknown filter, /Crypt, broken filter chain), which is+        // indistinguishable here from a genuinely empty appearance. Every other+        // unusable-/AP branch above falls back to the synthesized shape; this one+        // returned, so the annotation vanished outright.+        synthesize_annotation_appearance(doc, dict, rect, base, prims);         return;     } @@ -391,14 +443,100 @@ fn finite_coords(doc: &Document, obj: &Object) -> Option<Vec<f64>> { /// Only shapes the file actually specifies are drawn: Square/Circle from `/Rect`, /// Line from `/L` (with `/LE` endings), Ink from `/InkList`, Polygon/PolyLine /// from `/Vertices`, the text markup types from `/QuadPoints`, Caret as an-/// insertion wedge and Stamp as its `/Name` wording in a box.+/// insertion wedge, Stamp as its `/Name` wording in a box, and a Widget's field+/// value from `/V` and `/DA` (§12.7.2 Table 218). ///-/// Everything else — Widget, Link, FileAttachment, Sound, Movie, Screen, and any+/// Everything else — Link, FileAttachment, Sound, Movie, Screen, and any /// of the above missing its defining geometry — draws NOTHING. A crude wrong /// shape is worse than an absent one: a bare `/Rect` outline is /// indistinguishable from a Square annotation and asserts a geometry the file /// never gave. In particular Link must never draw chrome of its own (§12.5.6.5 /// leaves the border to `/Border`, honoured only inside a real `/AP`).+/// `/Rect` inset by HALF the border width, so a stroke laid on the result stays+/// inside the annotation: §8.4.3.2 centres a pen on its path, and a ring laid on+/// `/Rect` itself puts `bw/2` of the border outside. Collapses to the plain rect+/// when the inset would invert it.+fn border_inset_rect(rect: [f64; 4], bw: f64) -> [f64; 4] {+    let r = normalize_rect(rect);+    let i = bw / 2.0;+    let inset = [r[0] + i, r[1] + i, r[2] - i, r[3] - i];+    if inset[2] > inset[0] && inset[3] > inset[1] {+        inset+    } else {+        r+    }+}++/// The rectangle a FreeText annotation's text is laid out in: §12.5.6.6 Table+/// 174's `/RD`, "the numerical differences between ... the Rect entry of the+/// annotation and a rectangle contained within that rectangle. The inner+/// rectangle is where the annotation's text should be displayed."+///+/// Distinct from Table 177's `/RD` in [`shape_rect`], which bounds the SHAPE.+/// Applied to the already border-inset box, since the text sits inside the+/// border. A malformed value is ignored, as for the shape form.+fn free_text_rect(doc: &Document, dict: &lopdf::Dictionary, boxed: [f64; 4]) -> [f64; 4] {+    let rd = match dict+        .get(b"RD")+        .ok()+        .and_then(|o| finite_coords(doc, o))+        .filter(|v| v.len() >= 4 && v.iter().all(|n| *n >= 0.0))+    {+        Some(v) => v,+        None => return boxed,+    };+    let inset = [boxed[0] + rd[0], boxed[1] + rd[3], boxed[2] - rd[2], boxed[3] - rd[1]];+    if inset[2] > inset[0] && inset[3] > inset[1] {+        inset+    } else {+        boxed+    }+}++/// The rectangle a Square/Circle annotation's shape actually occupies.+///+/// §12.5.6.8 Table 177: `/RD` gives "the numerical differences between two+/// rectangles: the `Rect` entry of the annotation and the actual boundaries of+/// the underlying square or circle", as differences in the left, top, right and+/// bottom coordinates. It exists precisely so a shape with a wide border still+/// fits inside `/Rect`, and it was not read anywhere in this crate — so an+/// annotation carrying one was drawn oversized, out to the full `/Rect`.+///+/// Absent `/RD`, the shape is inset by HALF the border width instead: §8.4.3.2+/// centres a stroke on its path, so a path laid on `/Rect` itself puts half the+/// border outside the annotation.+///+/// A malformed `/RD` — negative, non-finite, or wider than the rect — is+/// ignored rather than clamped: it would grow the shape beyond `/Rect` or+/// collapse it, and the plain rect is the better-defined answer.+///+/// This is Table 177's `/RD` and applies ONLY to Square and Circle. §12.5.6.6+/// Table 174 defines a `/RD` for FreeText with different semantics — it insets+/// the TEXT AREA, not the shape boundary — so routing FreeText through here+/// would use a text inset as a border inset.+fn shape_rect(doc: &Document, dict: &lopdf::Dictionary, rect: [f64; 4], bw: f64) -> [f64; 4] {+    let r = normalize_rect(rect);+    let rd = dict+        .get(b"RD")+        .ok()+        .and_then(|o| finite_coords(doc, o))+        .filter(|v| v.len() >= 4 && v.iter().all(|n| *n >= 0.0));+    let [dl, dt, dr, db] = match rd {+        // Table 177 orders the differences left, top, right, bottom. Top is a+        // difference from the TOP edge, so it comes off r[3].+        Some(v) => [v[0], v[1], v[2], v[3]],+        // /RD bounds the shape BORDER AND ALL, so it is never combined with the+        // stroke inset — one or the other.+        None => return border_inset_rect(r, bw),+    };+    let inset = [r[0] + dl, r[1] + db, r[2] - dr, r[3] - dt];+    if inset[2] > inset[0] && inset[3] > inset[1] {+        inset+    } else {+        r+    }+}+ pub(crate) fn synthesize_annotation_appearance(     doc: &Document,     dict: &lopdf::Dictionary,@@ -406,7 +544,11 @@ pub(crate) fn synthesize_annotation_appearance(     base: &Mat,     prims: &mut Vec<Prim>, ) {-    let subtype = match dict.get(b"Subtype").ok().and_then(|o| o.as_name().ok()) {+    // Dereferenced per §7.3.10: an indirect /Subtype read as a plain name gives+    // None and returns here, so the annotation synthesizes NOTHING — the same+    // total loss the arms below exist to prevent. `annot_visible_on_screen_with`+    // already derefs this key.+    let subtype = match dict.get(b"Subtype").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(|o| o.as_name().ok()) {         Some(s) => s.to_vec(),         None => return,     };@@ -426,8 +568,8 @@ pub(crate) fn synthesize_annotation_appearance(     // for — most visibly around a filled Square/Circle, which is exactly how     // this codebase's own `set_shape_border` marks a filled shape.     //-    // Applied only to the two shapes that have a spec-defined interior (/IC), so-    // suppressing the border still leaves the annotation's content. For Line,+    // Applied only to shapes whose content survives losing the border: the+    // Square/Circle interior (/IC) and the FreeText /Contents. For Line,     // PolyLine and Ink the stroke IS the whole annotation, and dropping it on a     // producer that wrote W=0 by accident would erase the annotation outright,     // which is the larger risk of the two.@@ -453,7 +595,10 @@ pub(crate) fn synthesize_annotation_appearance(      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])];+            // §12.5.6.8: the square is /Rect inset by /RD, or by half the border+            // width when /RD is absent — not /Rect itself.+            let sr = shape_rect(doc, dict, rect, bw);+            let poly = vec![dev(sr[0],sr[1]), dev(sr[2],sr[1]), dev(sr[2],sr[3]), dev(sr[0],sr[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.filter(|_| has_border) {                 let mut ring = poly.clone(); ring.push(poly[0]);@@ -464,9 +609,11 @@ pub(crate) fn synthesize_annotation_appearance(             }         }         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);+            // Approximate the inscribed ellipse with a polygon, inscribed in the+            // /RD- or border-inset rect rather than the full /Rect (§12.5.6.8).+            let sr = shape_rect(doc, dict, rect, bw);+            let (cx, cy) = ((sr[0]+sr[2])/2.0, (sr[1]+sr[3])/2.0);+            let (rx, ry) = ((sr[2]-sr[0]).abs()/2.0, (sr[3]-sr[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())@@ -533,6 +680,14 @@ pub(crate) fn synthesize_annotation_appearance(         b"Highlight" => {             let color = stroke.unwrap_or(0xFFFF_FF00); // default yellow             if quads.is_empty() {+                // §12.5.6.10 makes /QuadPoints required, so this is malformed+                // input. The /Rect is still kept as the fallback region, unlike+                // Polygon (which draws nothing without /Vertices) and unlike the+                // sibling markup types below: a fill is well defined for ANY+                // region, and §12.5.2 already makes /Rect the area the annotation+                // occupies, so it claims nothing new. Underline and StrikeOut+                // need a quad to locate a BASELINE, which a /Rect cannot supply+                // at all — hence they draw nothing and this does not.                 let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];                 emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(color, ca), false, 1.0, BlendMode::Multiply);             } else {@@ -668,36 +823,89 @@ pub(crate) fn synthesize_annotation_appearance(         }         b"FreeText" => {             // Border/background box plus the /Contents text (no /AP fallback).-            let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];+            //+            // Normalized up front, and every read below goes through `r`: the+            // box quad survives any corner ordering (inverting only reverses the+            // winding) but the text layout does NOT, and mixing raw and+            // normalized reads in one arm is what hid that. §7.9.5 lets /Rect be+            // given by any two diagonally opposite corners and `read_rect` does+            // not reorder them, so on an inverted rect `rect[3]` is the BOTTOM:+            // the first line started below the box and the `y < rect[1]` guard+            // — comparing against what is actually the TOP — broke the loop+            // immediately, painting the box with none of its text inside.+            let r = border_inset_rect(rect, bw);+            let poly = vec![dev(r[0],r[1]), dev(r[2],r[1]), dev(r[2],r[3]), dev(r[0],r[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 {+            if let Some(s) = stroke.filter(|_| has_border) {                 let mut ring = poly.clone(); ring.push(poly[0]);                 let mut sgs = gs.clone(); sgs.stroke = s;+                let d = annot_border_dash(doc, dict);+                if !d.is_empty() { sgs.dash = d; }                 emit_stroke(prims, std::slice::from_ref(&ring), &sgs);             }             let text = dict.get(b"Contents").ok().and_then(|o| deref(doc, o)).and_then(|o| match o { Object::String(b,_) => Some(decode_pdf_text(b)), _ => None }).unwrap_or_default();             if !text.is_empty() {+                // §12.5.6.6 Table 174 gives FreeText its OWN /RD: the inner+                // rectangle "is where the annotation's text should be+                // displayed". Different meaning from Table 177's shape-bounding+                // /RD, so this must not go through `shape_rect` — but ignoring+                // it entirely runs the text under a thick border, which is the+                // case /RD exists to describe.+                let t = free_text_rect(doc, dict, r);                 let size = 12.0_f64;                 let dsize = (size * scale) as f32;-                let mut y = rect[3] - size; // top-down in page space+                let mut y = t[3] - size; // top-down in page space                 for line in text.split(['\n', '\r']).filter(|l| !l.is_empty()) {-                    if prims.len() >= MAX_PRIMITIVES || y < rect[1] { break; }-                    let (px, py) = dev(rect[0] + 2.0, y);+                    if prims.len() >= MAX_PRIMITIVES || y < t[1] { break; }+                    let (px, py) = dev(t[0] + 2.0, y);                     emit_annot_text(prims, px as f32, py as f32, dsize, 0xFF00_0000, line);                     y -= size * 1.2;                 }             }         }         b"Text" => {-            // Sticky-note icon: a small filled square marker at the annotation rect.-            let x0 = rect[0]; let y1 = rect[3];-            let s = 18.0_f64.min((rect[2]-rect[0]).abs().max(12.0));+            // Sticky-note marker. This is the one place where "draw nothing+            // rather than a crude shape" inverts, so the reasoning is worth+            // recording: the rule exists because a synthesized shape must not+            // assert geometry the file never gave (the /Rect outline that read as+            // a Square) or hide content already on the page (the redaction fill,+            // the translucent wash). A Text annotation is neither. §12.5.6.4+            // makes it an ICON at /Rect that "shall not scale with the page" —+            // position IS its whole geometry and the file always gives it, and a+            // marker asserts only "a comment is here", which is true. Drawing+            // nothing loses that fact entirely, and nothing else in the page view+            // surfaces it.+            //+            // What was wrong was the execution, in two ways, both fixed here:+            //   * `s` came from the rect WIDTH alone, so a wide, short /Rect got+            //     a marker up to 18pt tall over a rect a fraction of that,+            //     spilling onto the text below;+            //   * an unconditional hard-black ring, which is the highest-contrast+            //     mark available and read as an authored black box rather than+            //     viewer chrome.+            // The 12pt floor on each axis stays: §12.5.6.4's icon "shall not+            // scale with the page", and producers do write a zero-size /Rect and+            // rely on the viewer's fixed icon size, so clamping strictly to a+            // degenerate rect would make those notes vanish.+            //+            // Table 172's /Name (Comment, Key, Note, Help, ...) is still ignored,+            // deliberately: we ship none of that artwork, and inventing a+            // distinct crude glyph per name IS the failure mode the rule is+            // about. One neutral marker says only what we actually know.+            // §7.9.5 lets a /Rect be given by any two diagonally opposite+            // corners and `read_rect` does not reorder them, so anchor on the+            // NORMALIZED rect as the Caret and Stamp arms do. Anchoring on the+            // raw one put the marker below an inverted rect's real box, over+            // unrelated page content — the sizing already used `.abs()`, so only+            // the anchor was missing the same treatment.+            let r = normalize_rect(rect);+            let s = 18.0_f64+                .min((r[2] - r[0]).max(12.0))+                .min((r[3] - r[1]).max(12.0));+            let (x0, y1) = (r[0], r[3]);             let poly = vec![dev(x0, y1 - s), dev(x0 + s, y1 - s), dev(x0 + s, y1), dev(x0, y1)];             let col = stroke.or(fill).unwrap_or(0xFFFF_E000); // note yellow             emit_fill(prims, std::slice::from_ref(&poly), apply_alpha_to_argb(col, ca), false, 1.0, BlendMode::Normal);-            let mut ring = poly.clone(); ring.push(poly[0]);-            let mut sgs = gs.clone(); sgs.stroke = 0xFF00_0000;-            emit_stroke(prims, std::slice::from_ref(&ring), &sgs);         }         b"Redact" => {             // §12.5.6.24: a redaction is not applied until apply_redactions runs,@@ -711,7 +919,12 @@ pub(crate) fn synthesize_annotation_appearance(             // content is still there hides the very text the user has to read to             // check the mark, which is the same "wash over the page" failure the             // rest of this function exists to avoid.-            let poly = vec![dev(rect[0],rect[1]), dev(rect[2],rect[1]), dev(rect[2],rect[3]), dev(rect[0],rect[3])];+            // The ring is inset by half the border width for the same §8.4.3.2+            // reason as Square: a path on /Rect leaves half the pen outside the+            // annotation. Table 187 defines no /RD for Redact, so there is no+            // author-supplied inset to honour here.+            let r = border_inset_rect(rect, bw);+            let poly = vec![dev(r[0],r[1]), dev(r[2],r[1]), dev(r[2],r[3]), dev(r[0],r[3])];             let mut ring = poly.clone(); ring.push(poly[0]);             let mut sgs = gs.clone();             sgs.stroke = stroke.unwrap_or(0xFFFF_0000);@@ -719,10 +932,65 @@ pub(crate) fn synthesize_annotation_appearance(             if !d.is_empty() { sgs.dash = d; }             emit_stroke(prims, std::slice::from_ref(&ring), &sgs);         }+        b"Widget" => {+            // A form field with no usable /AP: §12.7.2 Table 218 makes /V and+            // /DA sufficient to rebuild the appearance, and without doing so a+            // form the user filled in — or received filled in — renders+            // completely blank. Unlike the shape types above this asserts no+            // geometry the file did not give: the value is the file's own.+            render_widget_value(doc, dict, rect, base, prims);+        }         _ => {}     } } +/// Paint a Widget's field value, building the appearance from `/V` and `/DA`+/// the way §12.7.2 Table 218 requires of a consumer when `/NeedAppearances` is+/// set or no `/AP` was supplied. Returns whether anything was drawn.+///+/// The geometry deliberately mirrors `forms::set_text_field`: the same content+/// builder, `/BBox` and `/Matrix`, played through `appearance_matrix` exactly as+/// the baked stream would be, so synthesizing at render time and baking at edit+/// time put the value in the same place.+fn render_widget_value(+    doc: &Document,+    dict: &lopdf::Dictionary,+    rect: [f64; 4],+    base: &Mat,+    prims: &mut Vec<Prim>,+) -> bool {+    let (content, res, bbox, apm) = match crate::forms::widget_value_appearance(doc, dict, rect) {+        Some(v) => v,+        None => return false,+    };+    let ops = crate::content::parse_operations_lenient(&content);+    if ops.is_empty() {+        return false;+    }+    let ctm = mat_mul(&appearance_matrix(rect, bbox, apm), base);+    // §8.10.2's /BBox clip, for the same reason a real appearance gets one: a+    // value longer than its field must stop at the field's edge rather than run+    // out across the page.+    let dev: Vec<(f64, f64)> = [+        (bbox[0], bbox[1]),+        (bbox[2], bbox[1]),+        (bbox[2], bbox[3]),+        (bbox[0], bbox[3]),+    ]+    .iter()+    .map(|&(x, y)| transform(&ctm, x, y))+    .collect();+    let pts: Vec<(f32, f32)> = dev.iter().map(|&(x, y)| (x as f32, y as f32)).collect();+    let mut path_ops = vec![PathOp::Move(pts[0].0, pts[0].1)];+    path_ops.extend(pts[1..].iter().map(|&(x, y)| PathOp::Line(x, y)));+    path_ops.push(PathOp::Close);+    prims.push(Prim::ClipPush { even_odd: false, pts, path_ops: Some(path_ops) });+    let gs = GraphicsState { ctm, ..Default::default() };+    interpret_content_seeded(doc, &ops, Some(&res), gs, prims, 1, false, None);+    prims.push(Prim::ClipPop);+    true+}+ /// Emit a single line of substitute-font text at a device-space baseline (used /// for synthesized FreeText appearances). fn emit_annot_text(prims: &mut Vec<Prim>, x: f32, y: f32, size: f32, argb: u32, text: &str) {@@ -1967,6 +2235,14 @@ pub(crate) fn list_annotations(handle: i64, page_index: i32) -> Option<Vec<u8>>         .and_then(|o| deref(doc, o))     {         for a in annots {+            // Direct annotation dictionaries are skipped deliberately: the+            // `encode_id` in the record below is the handle the editor uses to+            // select, move and delete the annotation, and a direct dictionary+            // has no ObjectId to fill it with. Surfacing one under a sentinel id+            // would offer edit affordances that silently do nothing. §12.5.2+            // permits the direct form and `render_annotations` paints it, so+            // such an annotation is visible but not selectable — a known and+            // accepted divergence, not an oversight.             let id = match a.as_reference() {                 Ok(id) => id,                 Err(_) => continue,@@ -1975,7 +2251,7 @@ pub(crate) fn list_annotations(handle: i64, page_index: i32) -> Option<Vec<u8>>                 Ok(d) => d,                 Err(_) => continue,             };-            let subtype = dict.get(b"Subtype").ok().and_then(|o| o.as_name().ok());+            let subtype = dict.get(b"Subtype").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(|o| o.as_name().ok());             let code = subtype.map(subtype_code).unwrap_or(0);             // Report rects in displayed space so the editor's hit-testing and             // selection boxes line up with the (rotation-baked) render.@@ -2643,4 +2919,670 @@ mod synthesis_tests {             }         }     }++    /// Everything a run of `Prim::Text` would paint, concatenated in emission+    /// order: the interpreter emits one prim per glyph, so a value only exists+    /// as the whole run.+    fn painted_text(prims: &[Prim]) -> String {+        prims+            .iter()+            .filter_map(|p| match p {+                Prim::Text { text, .. } => Some(text.as_str()),+                _ => None,+            })+            .collect()+    }++    /// A single-page document whose catalog carries an `/AcroForm`, optionally+    /// with `/NeedAppearances` set.+    fn form_doc(need_appearances: bool) -> Document {+        let mut doc = Document::with_version("1.7");+        let pages_id = doc.new_object_id();+        let page = doc.add_object(dictionary! {+            "Type" => name_obj("Page"),+            "Parent" => Object::Reference(pages_id),+            "MediaBox" => rect_obj([0.0, 0.0, 200.0, 200.0]),+        });+        doc.objects.insert(+            pages_id,+            Object::Dictionary(dictionary! {+                "Type" => name_obj("Pages"),+                "Kids" => Object::Array(vec![Object::Reference(page)]),+                "Count" => 1,+            }),+        );+        let mut acro = dictionary! { "Fields" => Object::Array(vec![]) };+        if need_appearances {+            acro.set("NeedAppearances", Object::Boolean(true));+        }+        let acro_id = doc.add_object(acro);+        let catalog_id = doc.add_object(dictionary! {+            "Type" => name_obj("Catalog"),+            "Pages" => Object::Reference(pages_id),+            "AcroForm" => Object::Reference(acro_id),+        });+        doc.trailer.set("Root", catalog_id);+        doc+    }++    fn text_widget(value: &str) -> Dictionary {+        let mut w = annot("Widget");+        w.set("Rect", rect_obj([10.0, 10.0, 110.0, 30.0]));+        w.set("FT", name_obj("Tx"));+        w.set("T", Object::string_literal("field"));+        w.set("DA", Object::string_literal("/Helv 10 Tf 0 g"));+        w.set("V", Object::string_literal(value));+        w+    }++    /// An `/AP /N` stream painting one unmistakable fill, to tell "the file's+    /// appearance ran" apart from "we synthesized one".+    fn fill_ap(doc: &mut Document) -> Dictionary {+        let ap = doc.add_object(Stream::new(+            dictionary! {+                "Type" => name_obj("XObject"),+                "Subtype" => name_obj("Form"),+                "BBox" => Object::Array(vec![0.into(), 0.into(), 100.into(), 20.into()]),+            },+            b"1 0 0 rg 0 0 100 20 re f".to_vec(),+        ));+        dictionary! { "N" => ap }+    }++    /// §12.7.2 Table 218 makes /V plus /DA enough for a consumer to build the+    /// appearance, and non-Acrobat producers routinely ship a filled-in form with+    /// no /AP on its widgets at all. `/NeedAppearances` was write-only in this+    /// crate and `synthesize_annotation_appearance` had no Widget arm, so such a+    /// form rendered COMPLETELY BLANK — the value was nowhere on the page.+    #[test]+    fn a_widget_with_no_appearance_still_paints_its_value() {+        let doc = form_doc(false);+        let mut prims = Vec::new();+        render_annotation(&doc, &text_widget("Ada Lovelace"), &IDENTITY, &mut prims);+        assert_eq!(painted_text(&prims), "Ada Lovelace", "the field value must be painted");+    }++    /// An empty /V has nothing to draw, and a /Btn's value NAMES an /AP state+    /// rather than supplying text — synthesizing "Off" or "Yes" as a caption+    /// would be inventing content.+    #[test]+    fn only_a_variable_text_field_with_a_value_is_synthesized() {+        let doc = form_doc(false);+        for (ft, v) in [("Tx", ""), ("Btn", "Yes"), ("Sig", "x")] {+            let mut w = text_widget(v);+            w.set("FT", name_obj(ft));+            if v.is_empty() {+                w.remove(b"V");+            }+            let mut prims = Vec::new();+            render_annotation(&doc, &w, &IDENTITY, &mut prims);+            assert!(painted_text(&prims).is_empty(), "/FT {ft} with /V {v:?} must draw no text");+        }+    }++    /// The precedence §12.7.2 Table 218 sets: `/NeedAppearances` means the+    /// appearance in the file is stale and the consumer SHALL rebuild it, so it+    /// overrides a present /AP. Without the flag the file's /AP is authoritative+    /// and must be used as-is.+    #[test]+    fn need_appearances_overrides_a_present_ap_and_nothing_else_does() {+        for need in [false, true] {+            let mut doc = form_doc(need);+            let ap = fill_ap(&mut doc);+            let mut w = text_widget("Ada Lovelace");+            w.set("AP", Object::Dictionary(ap));++            let mut prims = Vec::new();+            render_annotation(&doc, &w, &IDENTITY, &mut prims);+            let fills = prims.iter().filter(|p| matches!(p, Prim::Fill { .. })).count();+            let texts = painted_text(&prims);+            if need {+                assert_eq!(texts, "Ada Lovelace", "the appearance must be regenerated");+                assert_eq!(fills, 0, "the stale /AP must not also be played");+            } else {+                assert_eq!(fills, 1, "the file's own /AP wins when the flag is absent");+                assert!(texts.is_empty(), "nothing may be synthesized over a valid /AP");+            }+        }+    }++    /// §12.7.4.3 Table 226 bit 14: a Password field's value shall not be echoed+    /// visually. Regenerating an appearance for one would put a stored password+    /// on screen — the one case where drawing nothing is required, not merely+    /// preferred.+    #[test]+    fn a_password_field_value_is_never_regenerated_on_screen() {+        let doc = form_doc(true);+        let mut w = text_widget("hunter2");+        w.set("Ff", Object::Integer(1 << 13));+        let mut prims = Vec::new();+        render_annotation(&doc, &w, &IDENTITY, &mut prims);+        assert!(painted_text(&prims).is_empty(), "a password must not be painted");+    }++    /// /V and /DA are field keys (§12.7.3.1), so a widget that is a separate+    /// /Kids entry carries neither: both are inherited through /Parent. Reading+    /// only the widget's own dictionary blanks every multi-widget field.+    #[test]+    fn a_kid_widget_inherits_its_value_from_the_parent_field() {+        let mut doc = form_doc(false);+        let field = doc.add_object(dictionary! {+            "FT" => name_obj("Tx"),+            "T" => Object::string_literal("field"),+            "V" => Object::string_literal("inherited"),+            "DA" => Object::string_literal("/Helv 10 Tf 0 g"),+        });+        let mut w = annot("Widget");+        w.set("Rect", rect_obj([10.0, 10.0, 110.0, 30.0]));+        w.set("Parent", Object::Reference(field));+        let mut prims = Vec::new();+        render_annotation(&doc, &w, &IDENTITY, &mut prims);+        assert_eq!(painted_text(&prims), "inherited");+    }++    /// A value longer than its field must stop at the field's edge: §8.10.2+    /// clips a form XObject to its /BBox, and a regenerated appearance is one+    /// (§12.5.5). Without the clip an over-long value runs out across the page.+    #[test]+    fn a_regenerated_field_appearance_is_clipped_to_its_widget() {+        let doc = form_doc(false);+        let mut prims = Vec::new();+        render_annotation(&doc, &text_widget(&"x".repeat(400)), &IDENTITY, &mut prims);+        let clips: Vec<&Prim> = prims.iter().filter(|p| matches!(p, Prim::ClipPush { .. })).collect();+        assert_eq!(clips.len(), 1, "exactly one /BBox clip");+        let Prim::ClipPush { pts, .. } = clips[0] else { unreachable!() };+        let xs = pts.iter().map(|p| p.0);+        let ys = pts.iter().map(|p| p.1);+        let (x0, x1) = (xs.clone().fold(f32::MAX, f32::min), xs.fold(f32::MIN, f32::max));+        let (y0, y1) = (ys.clone().fold(f32::MAX, f32::min), ys.fold(f32::MIN, f32::max));+        for (got, want) in [(x0, 10.0), (y0, 10.0), (x1, 110.0), (y1, 30.0)] {+            assert!((got - want).abs() < 0.01, "clip must be the /Rect, got [{x0} {y0} {x1} {y1}]");+        }+        assert_eq!(+            prims.iter().filter(|p| matches!(p, Prim::ClipPop)).count(),+            1,+            "the clip must be popped exactly once"+        );+    }++    /// `objects.rs` deliberately yields an empty operation list rather than+    /// still-encoded bytes when every decoder fails, so an /AP /N with a broken+    /// filter chain is indistinguishable here from an empty appearance. Every+    /// other unusable-/AP branch falls back to the synthesized shape; this one+    /// returned early, so the annotation vanished outright.+    #[test]+    fn an_undecodable_appearance_stream_falls_back_to_synthesis() {+        let mut doc = Document::with_version("1.7");+        // Flate is implemented, and these bytes are not valid Flate, so the+        // decoder judges them corrupt and yields nothing.+        let ap = doc.add_object(Stream::new(+            dictionary! {+                "Type" => name_obj("XObject"),+                "Subtype" => name_obj("Form"),+                "BBox" => Object::Array(vec![0.into(), 0.into(), 20.into(), 20.into()]),+                "Filter" => name_obj("FlateDecode"),+            },+            vec![0xFF, 0x00, 0xFF, 0x00, 0xFF],+        ));+        let mut sq = annot("Square");+        sq.set("Rect", rect_obj([0.0, 0.0, 20.0, 20.0]));+        sq.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));+        sq.set("AP", Object::Dictionary(dictionary! { "N" => ap }));++        let mut prims = Vec::new();+        render_annotation(&doc, &sq, &IDENTITY, &mut prims);+        assert!(+            prims.iter().any(|p| matches!(p, Prim::Stroke { .. })),+            "the Square must fall back to its synthesized outline, got {} prims",+            prims.len()+        );+    }++    /// §12.5.4 Table 166: "if this value is 0, no border shall be drawn". The+    /// Square arm honours it; FreeText did not, and `line_width`'s 0.5 floor+    /// turned the declared zero into a hairline the file never asked for. The+    /// /Contents text still has to survive losing the border.+    #[test]+    fn a_freetext_with_a_zero_border_width_draws_no_border() {+        let mut ft = annot("FreeText");+        ft.set("C", Object::Array(vec![0.into(), 0.into(), 1.into()]));+        ft.set("Contents", Object::string_literal("note"));+        ft.set("BS", dictionary! { "W" => 0 });+        let prims = synth(&ft, [0.0, 0.0, 100.0, 40.0]);+        assert!(+            !prims.iter().any(|p| matches!(p, Prim::Stroke { .. })),+            "/BS /W 0 must draw no border"+        );+        assert_eq!(painted_text(&prims), "note", "the text must remain");++        ft.set("BS", dictionary! { "W" => 2 });+        assert!(+            synth(&ft, [0.0, 0.0, 100.0, 40.0]).iter().any(|p| matches!(p, Prim::Stroke { .. })),+            "a declared non-zero width must still draw"+        );+    }++    /// The same §7.9.5 corner-ordering trap as the sticky-note marker, but here+    /// it silently swallowed the annotation's MESSAGE: on an inverted /Rect+    /// `rect[3]` is the bottom, so the first line started below the box and the+    /// `y < rect[1]` guard — against what is really the top — broke the loop on+    /// iteration one. The /IC box still painted, so it read as an empty box+    /// rather than as anything wrong.+    #[test]+    fn freetext_contents_survive_an_inverted_rect() {+        let mut ft = annot("FreeText");+        ft.set("IC", Object::Array(vec![1.into(), 1.into(), 0.into()]));+        ft.set("Contents", Object::string_literal("first\nsecond"));++        let upright = synth(&ft, [0.0, 0.0, 100.0, 40.0]);+        assert_eq!(painted_text(&upright), "firstsecond", "precondition: upright draws both lines");++        // The same box, every other corner ordering.+        for rect in [+            [100.0, 40.0, 0.0, 0.0],+            [0.0, 40.0, 100.0, 0.0],+            [100.0, 0.0, 0.0, 40.0],+        ] {+            let prims = synth(&ft, rect);+            assert_eq!(painted_text(&prims), "firstsecond", "/Rect {rect:?} lost its /Contents");+            let baselines: Vec<(f32, f32)> = prims+                .iter()+                .filter_map(|p| match p {+                    Prim::Text { x, y, .. } => Some((*x, *y)),+                    _ => None,+                })+                .collect();+            for (x, y) in &baselines {+                assert!(+                    *x >= -0.01 && *x <= 100.01 && *y >= -0.01 && *y <= 40.01,+                    "/Rect {rect:?} put a line at ({x}, {y}), outside the box"+                );+            }+        }+    }++    /// The sticky-note marker is kept — losing it loses the only sign in the page+    /// view that a comment exists — but it must not obscure. `s` came from the+    /// rect WIDTH alone, so a wide, short /Rect got a marker up to 18pt tall over+    /// a rect a fraction of that; and the unconditional black ring read as an+    /// authored box rather than viewer chrome. A degenerate /Rect still gets the+    /// nominal marker, since §12.5.6.4's icon does not scale with the page.+    #[test]+    fn the_sticky_note_marker_stays_inside_its_rect_and_draws_no_black_ring() {+        let marker_height = |rect: [f64; 4]| -> f32 {+            let prims = synth(&annot("Text"), rect);+            assert!(+                !prims.iter().any(|p| matches!(p, Prim::Stroke { .. })),+                "no hard-black ring around the marker"+            );+            let fills: Vec<&Prim> = prims.iter().filter(|p| matches!(p, Prim::Fill { .. })).collect();+            assert_eq!(fills.len(), 1, "exactly one marker");+            let Prim::Fill { contours, .. } = fills[0] else { unreachable!() };+            let ys: Vec<f32> = contours.iter().flatten().map(|p| p.1).collect();+            ys.iter().copied().fold(f32::MIN, f32::max) - ys.iter().copied().fold(f32::MAX, f32::min)+        };+        // Wide and short: the marker follows the SHORTER axis, not the width.+        let h = marker_height([0.0, 0.0, 200.0, 14.0]);+        assert!((h - 14.0).abs() < 0.01, "expected a 14pt marker in a 14pt-tall rect, got {h}");+        // Ordinary square note: capped at the 18pt nominal size.+        let h = marker_height([0.0, 0.0, 40.0, 40.0]);+        assert!((h - 18.0).abs() < 0.01, "expected the 18pt nominal marker, got {h}");+        // Zero-size /Rect: still drawn, at the 12pt floor, so the note is visible.+        let h = marker_height([10.0, 10.0, 10.0, 10.0]);+        assert!((h - 12.0).abs() < 0.01, "a degenerate /Rect must still show a marker, got {h}");+    }++    /// §7.3.10 lets ANY object be indirect. `/AS` read as a plain name yields+    /// None for an indirect one, which drops into the no-`/AS` branch — so a+    /// checkbox whose state is set indirectly renders as its `/Off` appearance,+    /// i.e. unchecked. The file already dereferences `/F`, `/Subtype`, `/C` and+    /// `/CA`; `/AS` was the outlier.+    #[test]+    fn an_indirect_appearance_state_selects_the_right_appearance() {+        for indirect in [false, true] {+            let mut doc = Document::with_version("1.7");+            let mk = |doc: &mut Document, colour: &str| {+                doc.add_object(Stream::new(+                    dictionary! {+                        "Type" => name_obj("XObject"),+                        "Subtype" => name_obj("Form"),+                        "BBox" => Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]),+                    },+                    format!("{colour} 0 0 10 10 re f").into_bytes(),+                ))+            };+            let off = mk(&mut doc, "1 0 0 rg");+            let on = mk(&mut doc, "0 1 0 rg");+            let mut w = annot("Widget");+            w.set("Rect", rect_obj([0.0, 0.0, 10.0, 10.0]));+            w.set("AP", dictionary! { "N" => dictionary! { "Off" => off, "On" => on } });+            let as_obj = name_obj("On");+            w.set(+                "AS",+                if indirect { Object::Reference(doc.add_object(as_obj)) } else { as_obj },+            );++            let mut prims = Vec::new();+            render_annotation(&doc, &w, &IDENTITY, &mut prims);+            let fills: Vec<u32> = prims+                .iter()+                .filter_map(|p| match p {+                    Prim::Fill { argb, .. } => Some(*argb),+                    _ => None,+                })+                .collect();+            assert_eq!(fills.len(), 1, "one appearance state must paint");+            assert_eq!(+                fills[0], 0xFF00_FF00,+                "indirect={indirect}: /AS must select the \"On\" state, not fall back to \"Off\""+            );+        }+    }++    /// An indirect `/Subtype` read as a plain name gives None, and+    /// `synthesize_annotation_appearance` returns immediately — so the whole+    /// annotation draws NOTHING, which is the total loss its arms exist to+    /// prevent. `annot_visible_on_screen_with` already dereferenced this key.+    #[test]+    fn an_indirect_subtype_still_selects_a_synthesis_arm() {+        let mut doc = Document::with_version("1.7");+        let subtype = doc.add_object(name_obj("Square"));+        let mut sq = Dictionary::new();+        sq.set("Type", name_obj("Annot"));+        sq.set("Subtype", Object::Reference(subtype));+        sq.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));++        let mut prims = Vec::new();+        synthesize_annotation_appearance(&doc, &sq, [0.0, 0.0, 20.0, 20.0], &IDENTITY, &mut prims);+        assert!(+            prims.iter().any(|p| matches!(p, Prim::Stroke { .. })),+            "an indirect /Subtype must still reach the Square arm"+        );+    }++    /// The `/NeedAppearances` gate reads `/Subtype` too, so an indirect one there+    /// silently skips regeneration and leaves the stale `/AP` — reintroducing the+    /// blank-field symptom for exactly the files that set the flag.+    #[test]+    fn need_appearances_regenerates_even_with_an_indirect_subtype() {+        let mut doc = form_doc(true);+        let subtype = doc.add_object(name_obj("Widget"));+        let ap = fill_ap(&mut doc);+        let mut w = text_widget("Ada Lovelace");+        w.set("Subtype", Object::Reference(subtype));+        w.set("AP", Object::Dictionary(ap));++        let mut prims = Vec::new();+        render_annotation(&doc, &w, &IDENTITY, &mut prims);+        assert_eq!(painted_text(&prims), "Ada Lovelace", "indirect /Subtype must still regenerate");+    }++    /// §12.5.6.8 Table 177: `/RD` is "the numerical differences between ... the+    /// Rect entry of the annotation and the actual boundaries of the underlying+    /// square or circle". It was read nowhere in the crate, so the shape was+    /// drawn out to the full `/Rect`. Absent `/RD` the shape is inset by half the+    /// border width instead, because §8.4.3.2 centres a stroke on its path and a+    /// path laid on `/Rect` puts half the border outside the annotation.+    #[test]+    fn square_and_circle_honour_rd_and_the_border_inset() {+        let bounds = |prims: &[Prim]| -> [f32; 4] {+            let pts: Vec<(f32, f32)> = prims+                .iter()+                .filter_map(|p| match p {+                    Prim::Fill { contours, .. } => Some(contours.iter().flatten().copied()),+                    _ => None,+                })+                .flatten()+                .collect();+            assert!(!pts.is_empty(), "expected a filled shape");+            [+                pts.iter().map(|p| p.0).fold(f32::MAX, f32::min),+                pts.iter().map(|p| p.1).fold(f32::MAX, f32::min),+                pts.iter().map(|p| p.0).fold(f32::MIN, f32::max),+                pts.iter().map(|p| p.1).fold(f32::MIN, f32::max),+            ]+        };+        let rect = [0.0, 0.0, 100.0, 50.0];++        for kind in ["Square", "Circle"] {+            let mut a = annot(kind);+            a.set("IC", Object::Array(vec![0.into(), 0.into(), 1.into()]));+            // /RD [left top right bottom] — top comes off the TOP edge.+            a.set("RD", Object::Array(vec![10.into(), 4.into(), 20.into(), 6.into()]));+            let got = bounds(&synth(&a, rect));+            for (g, want) in got.iter().zip([10.0, 6.0, 80.0, 46.0]) {+                assert!(+                    (g - want).abs() < 0.5,+                    "{kind} with /RD: got {got:?}, expected [10, 6, 80, 46]"+                );+            }++            // No /RD: inset by half the border width.+            a.remove(b"RD");+            a.set("BS", dictionary! { "W" => 8 });+            let got = bounds(&synth(&a, rect));+            for (g, want) in got.iter().zip([4.0, 4.0, 96.0, 46.0]) {+                assert!(+                    (g - want).abs() < 0.5,+                    "{kind} with /BS /W 8: got {got:?}, expected [4, 4, 96, 46]"+                );+            }+        }+    }++    /// A malformed `/RD` must not grow the shape past `/Rect` or collapse it —+    /// the plain rect is the better-defined answer than a clamped guess.+    #[test]+    fn a_malformed_rd_falls_back_to_the_plain_rect() {+        for rd in [+            vec![(-5).into(), 0.into(), 0.into(), 0.into()],   // negative: would grow+            vec![60.into(), 0.into(), 60.into(), 0.into()],    // wider than the rect+            vec![1.into(), 2.into()],                          // too short+        ] {+            let mut a = annot("Square");+            a.set("IC", Object::Array(vec![0.into(), 0.into(), 1.into()]));+            a.set("BS", dictionary! { "W" => 0 });+            a.set("RD", Object::Array(rd.clone()));+            let prims = synth(&a, [0.0, 0.0, 100.0, 50.0]);+            let xs: Vec<f32> = prims+                .iter()+                .filter_map(|p| match p {+                    Prim::Fill { contours, .. } => Some(contours.iter().flatten().map(|q| q.0)),+                    _ => None,+                })+                .flatten()+                .collect();+            let (x0, x1) = (+                xs.iter().copied().fold(f32::MAX, f32::min),+                xs.iter().copied().fold(f32::MIN, f32::max),+            );+            assert!(+                (x0 - 0.0).abs() < 0.01 && (x1 - 100.0).abs() < 0.01,+                "/RD {rd:?} must fall back to the plain /Rect, got [{x0}, {x1}]"+            );+        }+    }++    /// §12.5.5 defines no fallback for an `/AS` naming a state the `/N`+    /// dictionary lacks. `/Off` was used for every such case, so a widget whose+    /// `/AS` says it is ON but whose only state is stored under a different+    /// export name (`/Yes` vs `/On` vs `/1`) rendered unchecked — or, with no+    /// `/Off` entry at all, drew NOTHING. An `/AS` of `/Off` still draws nothing,+    /// because a missing `/Off` entry IS the blank off appearance.+    #[test]+    fn an_as_naming_a_missing_state_resolves_by_whether_it_says_off() {+        let paint = |states: Vec<(&str, &str)>, as_name: &str| -> Vec<u32> {+            let mut doc = Document::with_version("1.7");+            let mut n = Dictionary::new();+            for (name, colour) in states {+                let s = doc.add_object(Stream::new(+                    dictionary! {+                        "Type" => name_obj("XObject"),+                        "Subtype" => name_obj("Form"),+                        "BBox" => Object::Array(vec![0.into(), 0.into(), 10.into(), 10.into()]),+                    },+                    format!("{colour} 0 0 10 10 re f").into_bytes(),+                ));+                n.set(name, Object::Reference(s));+            }+            let mut w = annot("Widget");+            w.set("Rect", rect_obj([0.0, 0.0, 10.0, 10.0]));+            w.set("AP", dictionary! { "N" => n });+            w.set("AS", name_obj(as_name));+            let mut prims = Vec::new();+            render_annotation(&doc, &w, &IDENTITY, &mut prims);+            prims+                .iter()+                .filter_map(|p| match p {+                    Prim::Fill { argb, .. } => Some(*argb),+                    _ => None,+                })+                .collect()+        };+        const RED: u32 = 0xFFFF_0000;+        const GREEN: u32 = 0xFF00_FF00;++        // The on-art under a different export name: use it rather than /Off.+        assert_eq!(paint(vec![("Off", "1 0 0 rg"), ("On", "0 1 0 rg")], "Yes"), vec![GREEN]);+        // No /Off entry at all: previously drew nothing.+        assert_eq!(paint(vec![("On", "0 1 0 rg")], "Yes"), vec![GREEN]);+        // Ambiguous — two non-Off states, so fall back to /Off.+        assert_eq!(+            paint(vec![("Off", "1 0 0 rg"), ("On", "0 1 0 rg"), ("Two", "0 1 0 rg")], "Yes"),+            vec![RED]+        );+        // /AS says Off and /Off is absent: blank IS the off appearance.+        assert!(paint(vec![("On", "0 1 0 rg")], "Off").is_empty());+        // An exact match always wins.+        assert_eq!(paint(vec![("Off", "1 0 0 rg"), ("On", "0 1 0 rg")], "Off"), vec![RED]);+    }++    /// §8.4.3.2 centres a pen on its path, so the C6 stroke inset is not+    /// specific to Square and Circle — FreeText and Redact ring their `/Rect`+    /// too, and left half the border outside the annotation.+    ///+    /// FreeText must NOT reuse `shape_rect`: §12.5.6.6 Table 174 gives it a+    /// `/RD` that insets the TEXT AREA, not the shape, so passing it through the+    /// Table 177 path would apply a text inset as a border inset.+    #[test]+    fn freetext_and_redact_keep_their_border_inside_the_rect() {+        let extent = |prims: &[Prim]| -> [f32; 4] {+            let pts: Vec<(f32, f32)> = prims+                .iter()+                .filter_map(|p| match p {+                    Prim::Stroke { pts, .. } => Some(pts.iter().copied()),+                    _ => None,+                })+                .flatten()+                .collect();+            assert!(!pts.is_empty(), "expected a stroked ring");+            [+                pts.iter().map(|p| p.0).fold(f32::MAX, f32::min),+                pts.iter().map(|p| p.1).fold(f32::MAX, f32::min),+                pts.iter().map(|p| p.0).fold(f32::MIN, f32::max),+                pts.iter().map(|p| p.1).fold(f32::MIN, f32::max),+            ]+        };+        for kind in ["FreeText", "Redact"] {+            let mut a = annot(kind);+            a.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));+            a.set("BS", dictionary! { "W" => 6 });+            let got = extent(&synth(&a, [0.0, 0.0, 100.0, 40.0]));+            for (g, want) in got.iter().zip([3.0, 3.0, 97.0, 37.0]) {+                assert!(+                    (g - want).abs() < 0.01,+                    "{kind}: ring at {got:?}, expected inset by half of /BS /W 6"+                );+            }+        }+    }++    /// §12.5.6.6 Table 174: a FreeText `/RD` says where the TEXT goes, and it+    /// was read nowhere — so an author asking for a wide text inset had the text+    /// run under the border instead. The box itself must NOT move with it, which+    /// is what distinguishes this from Table 177's shape `/RD`.+    #[test]+    fn a_freetext_rd_moves_the_text_but_not_the_box() {+        let mut a = annot("FreeText");+        a.set("C", Object::Array(vec![1.into(), 0.into(), 0.into()]));+        a.set("BS", dictionary! { "W" => 0 });+        a.set("Contents", Object::string_literal("hi"));++        let baseline_of = |prims: &[Prim]| -> (f32, f32) {+            prims+                .iter()+                .find_map(|p| match p {+                    Prim::Text { x, y, .. } => Some((*x, *y)),+                    _ => None,+                })+                .expect("a text line")+        };+        let ring_of = |prims: &[Prim]| -> f32 {+            prims+                .iter()+                .filter_map(|p| match p {+                    Prim::Stroke { pts, .. } => {+                        Some(pts.iter().map(|q| q.0).fold(f32::MAX, f32::min))+                    }+                    _ => None,+                })+                .fold(f32::MAX, f32::min)+        };+        let plain = synth(&a, [0.0, 0.0, 100.0, 40.0]);+        // /RD [left top right bottom]+        a.set("RD", Object::Array(vec![12.into(), 5.into(), 0.into(), 0.into()]));+        let inset = synth(&a, [0.0, 0.0, 100.0, 40.0]);++        let (px, py) = baseline_of(&plain);+        let (ix, iy) = baseline_of(&inset);+        assert!((ix - px - 12.0).abs() < 0.01, "text x must move right by /RD left: {px} -> {ix}");+        assert!((iy - py + 5.0).abs() < 0.01, "text y must drop by /RD top: {py} -> {iy}");+        assert!(+            (ring_of(&plain) - ring_of(&inset)).abs() < 0.01,+            "the box must NOT move — Table 174 /RD insets only the text"+        );+    }++    /// §7.9.5 lets a /Rect be given by ANY two diagonally opposite corners and+    /// `read_rect` does not reorder them. The marker was sized with `.abs()` but+    /// anchored on the raw `rect[3]`, which for an inverted rect is the BOTTOM+    /// edge — so the opaque square landed entirely outside the annotation, over+    /// unrelated page content.+    #[test]+    fn the_sticky_note_marker_anchors_on_a_normalized_rect() {+        let bounds = |rect: [f64; 4]| -> [f32; 4] {+            let prims = synth(&annot("Text"), rect);+            let fills: Vec<&Prim> = prims.iter().filter(|p| matches!(p, Prim::Fill { .. })).collect();+            assert_eq!(fills.len(), 1, "exactly one marker");+            let Prim::Fill { contours, .. } = fills[0] else { unreachable!() };+            let pts: Vec<(f32, f32)> = contours.iter().flatten().copied().collect();+            [+                pts.iter().map(|p| p.0).fold(f32::MAX, f32::min),+                pts.iter().map(|p| p.1).fold(f32::MAX, f32::min),+                pts.iter().map(|p| p.0).fold(f32::MIN, f32::max),+                pts.iter().map(|p| p.1).fold(f32::MIN, f32::max),+            ]+        };+        // The same box described by each of the four corner orderings must place+        // the marker identically, at the box's top-left.+        let want = bounds([10.0, 20.0, 50.0, 60.0]);+        for rect in [+            [50.0, 60.0, 10.0, 20.0], // both axes inverted+            [10.0, 60.0, 50.0, 20.0], // y inverted+            [50.0, 20.0, 10.0, 60.0], // x inverted+        ] {+            let got = bounds(rect);+            for i in 0..4 {+                assert!(+                    (got[i] - want[i]).abs() < 0.01,+                    "/Rect {rect:?} placed the marker at {got:?}, expected {want:?}"+                );+            }+        }+        // And it really is inside the box, not merely consistent.+        assert!(+            want[0] >= 9.99 && want[1] >= 19.99 && want[2] <= 50.01 && want[3] <= 60.01,+            "marker {want:?} escaped the /Rect"+        );+    } }
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 c05745bf08..e6c6ef91f9 100644--- a/pdf/src/main/rust/src/color.rs+++ b/pdf/src/main/rust/src/color.rs@@ -79,6 +79,28 @@ pub(crate) fn patterns_from_resources(doc: &Document, res_dict: &lopdf::Dictiona     out } +/// The `&Object` a resource NAME denotes, whether the entry is an indirect+/// reference or written directly in the resource dictionary.+///+/// §7.3.8.1 requires only STREAMS to be indirect. §8.7.4.2 makes a `/Shading`+/// resource value "a dictionary or a stream", and ShadingTypes 1-3 are+/// dictionaries, so they are legally DIRECT; the same holds for a PatternType 2+/// dictionary (§8.7.3.3 Table 76). [`shadings_from_resources`] and+/// [`patterns_from_resources`] collect only `as_reference()` entries, so a+/// direct one misses the map entirely and `/Sh0 sh` paints nothing at all.+///+/// Mirrors the shape [`parse_named_cs`] already uses for `/ColorSpace`.+pub(crate) fn resolve_named_resource<'a>(+    doc: &'a Document,+    resources: Option<&'a lopdf::Dictionary>,+    key: &[u8],+    name: &[u8],+) -> Option<&'a Object> {+    let sub = resources?.get(key).ok().and_then(|o| deref(doc, o))?;+    let entry = sub.as_dict().ok()?.get(name).ok()?;+    deref(doc, entry)+}+ // Parse a colorspace object (Name or Array) into CsKind, using resources map for named entries /// Depth ceiling for colour-space nesting. §8.6 nests only a handful of levels deep in /// practice (Indexed over ICCBased over an /Alternate, say), so this only ever stops a
pdf/src/main/rust/src/content.rs
diff --git a/pdf/src/main/rust/src/content.rs b/pdf/src/main/rust/src/content.rsindex 9a0f2de394..4da2551143 100644--- a/pdf/src/main/rust/src/content.rs+++ b/pdf/src/main/rust/src/content.rs@@ -177,16 +177,67 @@ fn nesting_is_too_deep(data: &[u8], max: u32) -> bool {  /// Strict parse first, lenient tokenizer only if that fails, yields nothing, or is /// unsafe to attempt at all.-fn strict_operations(bytes: &[u8]) -> Option<Vec<Operation>> {+pub(crate) fn strict_operations(bytes: &[u8]) -> Option<Vec<Operation>> {     if nesting_is_too_deep(bytes, MAX_DEPTH) {         return None;     }     match Content::decode(bytes) {-        Ok(content) if !content.operations.is_empty() => Some(content.operations),+        Ok(content) if !content.operations.is_empty() => Some(repair_d0_d1(content.operations)),         _ => None,     } } +/// Undo lopdf 0.36's mis-tokenisation of `d0`/`d1` (§9.6.5, Table 113).+///+/// lopdf ends an operator token at the first digit, so `700 0 d0` decodes as the+/// DASH operator `d` with operands `[700, 0]` and the orphaned `0` becomes the+/// FIRST OPERAND OF THE NEXT OPERATION. §9.6.5 requires every Type 3 glyph+/// description to begin with `d0` or `d1`, so untreated this corrupts the first+/// painting operator of every conforming Type 3 glyph — `re` arrives with five+/// operands and is dropped, `m` starts the subpath at the wrong point.+///+/// A conforming `d` takes an ARRAY then a number (§8.4.3.6, Table 52), so a `d`+/// whose operands are ALL NUMERIC cannot be a dash and is unambiguously the+/// mangled form: two operands mean `d0` (`wx wy`), six mean `d1`+/// (`wx wy llx lly urx ury`).+///+/// The rename happens only AFTER the leaked digit is confirmed to be sitting+/// there as the next operation's first operand, so a genuinely malformed `d` in+/// a real dash context is left alone. A `d0`/`d1` that is the final operator of+/// a stream — the shape of every blank glyph, `wx 0 d0` and nothing else —+/// leaves no next operation and so no digit to confirm, and is renamed on the+/// strength of the operand signature alone.+///+/// The lenient tokenizer needs no equivalent: its [`OPERATORS`] table lists+/// `d0`/`d1` and matches the whole token.+fn repair_d0_d1(mut ops: Vec<Operation>) -> Vec<Operation> {+    for i in 0..ops.len() {+        let mangled = ops[i].operator == "d"+            && matches!(ops[i].operands.len(), 2 | 6)+            && ops[i]+                .operands+                .iter()+                .all(|o| matches!(o, Object::Integer(_) | Object::Real(_)));+        if !mangled {+            continue;+        }+        let is_d1 = ops[i].operands.len() == 6;+        if let Some(next) = ops.get_mut(i + 1) {+            let leaked = match next.operands.first() {+                Some(Object::Integer(v)) => *v == i64::from(is_d1),+                Some(Object::Real(v)) => *v == f32::from(u8::from(is_d1)),+                _ => false,+            };+            if !leaked {+                continue;+            }+            let _ = next.operands.remove(0);+        }+        ops[i].operator = if is_d1 { "d1" } else { "d0" }.to_string();+    }+    ops+}+ /// Operations for a page's content, preferring lopdf's strict parser and falling /// back to [`parse_operations_lenient`] when it fails or recovers nothing. ///@@ -1038,6 +1089,17 @@ mod tests {         ops.iter().map(|o| o.operator.clone()).collect()     } +    fn num_operands(op: &Operation) -> Vec<f64> {+        op.operands+            .iter()+            .filter_map(|o| match o {+                Object::Integer(i) => Some(*i as f64),+                Object::Real(r) => Some(*r as f64),+                _ => None,+            })+            .collect()+    }+     /// Raw data of every recovered inline image, in order.     fn inline_data(ops: &[Operation]) -> Vec<Vec<u8>> {         ops.iter()@@ -1434,6 +1496,72 @@ mod tests {         assert_eq!(operators(&ops), operators(&strict));     } +    /// §9.6.5: every Type 3 glyph description begins with `d0`/`d1`, and lopdf+    /// 0.36 ends an operator token at the first digit — so without+    /// [`repair_d0_d1`] the glyph's first painting operator is corrupted.+    #[test]+    fn strict_operations_repairs_lopdf_mistokenised_d0_and_d1() {+        // Precondition: lopdf really does mangle these, so this is not a test+        // that would pass anyway.+        let raw = Content::decode(b"700 0 d0\n50 0 600 600 re\nf").expect("decode").operations;+        assert_eq!(raw[0].operator, "d", "precondition: lopdf produces the dash operator");+        assert_eq!(raw[1].operands.len(), 5, "precondition: the digit leaks into `re`");++        let ops = strict_operations(b"700 0 d0\n50 0 600 600 re\nf").expect("strict");+        assert_eq!(operators(&ops), vec!["d0", "re", "f"]);+        assert_eq!(ops[0].operands.len(), 2);+        assert_eq!(ops[1].operands.len(), 4, "`re` must get exactly its four operands");++        let ops = strict_operations(b"0 0 0 0 750 750 d1\n30 0 m\n370 0 l\nh\nf").expect("strict");+        assert_eq!(operators(&ops), vec!["d1", "m", "l", "h", "f"]);+        assert_eq!(ops[0].operands.len(), 6);+        assert_eq!(ops[1].operands.len(), 2, "`m` must start the subpath at (30, 0)");+        assert_eq!(num_operands(&ops[1]), vec![30.0, 0.0]);+    }++    /// The blank-glyph shape — `wx 0 d0` and nothing after it — leaves no next+    /// operation to carry the leaked digit.+    #[test]+    fn strict_operations_repairs_d0_as_the_final_operator() {+        let ops = strict_operations(b"600 0 d0\n").expect("strict");+        assert_eq!(operators(&ops), vec!["d0"]);+        assert_eq!(num_operands(&ops[0]), vec![600.0, 0.0]);+    }++    /// §8.4.3.6 Table 52: a conforming `d` takes an ARRAY then a number, so the+    /// repair must never touch one — including the empty-array "solid" form,+    /// which has the same operand COUNT as a mangled `d0`.+    #[test]+    fn strict_operations_leaves_a_real_dash_operator_alone() {+        for src in [+            &b"[3 3] 0 d\n0 0 m\n"[..],+            &b"[] 0 d\n0 0 m\n"[..],+            &b"[2 2] 0 d\n"[..],+        ] {+            let ops = strict_operations(src).expect("strict");+            assert_eq!(ops[0].operator, "d", "rewrote a conforming dash in {src:?}");+            if let Some(next) = ops.get(1) {+                assert_eq!(next.operands.len(), 2, "ate an operand of the next op in {src:?}");+            }+        }+    }++    /// The precondition that keeps a genuinely malformed `d` intact: the leaked+    /// digit must actually be sitting there as the next operation's first+    /// operand. `3 3 d` is not a legal dash, but nothing follows it that looks+    /// like the split-off `0`, so it stays a `d`.+    #[test]+    fn strict_operations_requires_the_leaked_digit_before_rewriting() {+        let ops = strict_operations(b"3 3 d\n5 7 m\n").expect("strict");+        assert_eq!(ops[0].operator, "d", "rewrote a `d` with no leaked digit after it");+        assert_eq!(num_operands(&ops[1]), vec![5.0, 7.0]);++        // Six numeric operands, but the next op does not begin with `1`.+        let ops = strict_operations(b"0 0 0 0 750 750 d\n5 7 m\n").expect("strict");+        assert_eq!(ops[0].operator, "d");+        assert_eq!(num_operands(&ops[1]), vec![5.0, 7.0]);+    }+     #[test]     fn page_operations_handles_a_page_with_no_contents() {         let mut doc = Document::with_version("1.5");
pdf/src/main/rust/src/docedit.rs
diff --git a/pdf/src/main/rust/src/docedit.rs b/pdf/src/main/rust/src/docedit.rsindex b978de8b67..0be506263f 100644--- a/pdf/src/main/rust/src/docedit.rs+++ b/pdf/src/main/rust/src/docedit.rs@@ -509,19 +509,31 @@ pub(crate) fn flatten_document(handle: i64) -> bool {     let oc = crate::images::OcConfig::from_doc(doc);     for page_id in page_ids {         // Collect (xobject name, appearance id, placement matrix) for each annot.-        let annot_ids: Vec<ObjectId> = match doc+        // The ORIGINAL array is kept, not just the ids: every entry that does not get+        // baked has to be written back below, and a direct-dictionary entry has no id+        // to write back with.+        let annots_arr: Vec<Object> = match doc             .get_dictionary(page_id)             .ok()             .and_then(|d| d.get(b"Annots").ok())             .and_then(|o| deref(doc, o))         {-            Some(Object::Array(a)) => a.iter().filter_map(|o| o.as_reference().ok()).collect(),+            Some(Object::Array(a)) => a.clone(),             _ => continue,         };+        // §12.5.2 does not require an /Annots entry to be indirect, so a direct+        // dictionary is legal here. It cannot be BAKED — the bake path needs an+        // ObjectId to reference the annotation's appearance from the page's+        // /XObject — but the retain below keeps it in /Annots, so it survives the+        // flatten and goes on rendering instead of being erased.+        let annot_ids: Vec<ObjectId> = annots_arr.iter().filter_map(|o| o.as_reference().ok()).collect();         if annot_ids.is_empty() {             continue;         }         let mut placements: Vec<(String, ObjectId, Mat, f64)> = Vec::new();+        // Exactly the annotations whose art reached the content stream. Everything+        // else must stay in /Annots — see the retain at the end of this loop.+        let mut baked_ids: Vec<ObjectId> = Vec::new();         for (i, aid) in annot_ids.iter().enumerate() {             let dict = match doc.get_dictionary(*aid) {                 Ok(d) => d,@@ -552,7 +564,11 @@ pub(crate) fn flatten_document(handle: i64) -> bool {             };             let picked = match deref(doc, ap_n) {                 Some(Object::Dictionary(states)) => {-                    match dict.get(b"AS").ok().and_then(|o| o.as_name().ok()) {+                    // §7.3.10: /AS may be an indirect reference like any other value.+                    // Without the deref it read as None, so a checkbox fell through to+                    // the /Off branch and the UNCHECKED art was baked permanently over a+                    // checked box — a wrong answer written to the file, not a missing one.+                    match dict.get(b"AS").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_name().ok()) {                         Some(a) => states.get(a).ok().or_else(|| states.get(b"Off").ok()),                         None => states.get(b"Off").ok().or_else(|| {                             if states.len() == 1 {@@ -601,6 +617,7 @@ pub(crate) fn flatten_document(handle: i64) -> bool {                 .unwrap_or(1.0)                 .clamp(0.0, 1.0);             placements.push((format!("Fl{}_{}", page_id.0, i), ap_id, m, ca));+            baked_ids.push(*aid);         }         if placements.is_empty() {             continue;@@ -641,8 +658,35 @@ pub(crate) fn flatten_document(handle: i64) -> bool {         for (name, gid) in &gstates {             add_page_resource(doc, page_id, "ExtGState", name, *gid);         }+        // Retain everything that was NOT baked instead of removing /Annots wholesale.+        //+        // Every failure path in the loop above is a `continue`, and this used to be an+        // unconditional `p.remove(b"Annots")`, so "skipped by the bake loop" and "erased+        // from the saved file" were the same outcome. An annotation with no /AP renders+        // through `synthesize_annotation_appearance`, so it is on screen right up until+        // a flatten deletes it — and unlike a dropped image this is written to the+        // user's document and cannot be recovered by reopening it.+        //+        // The comment at the /AP /N lookup above records this mechanism biting once+        // already: a cause was found and fixed while the mechanism was left in place,+        // which is how the remaining ways in went on erasing content. Fixing the+        // mechanism covers all of them, including the deliberate skips — a NoView, /OC+        // -disabled or /Popup annotation must not be baked (it would become permanently+        // visible), and it must not be destroyed either.         if let Ok(p) = doc.get_dictionary_mut(page_id) {-            p.remove(b"Annots");+            let survivors: Vec<Object> = annots_arr+                .into_iter()+                .filter(|o| match o.as_reference() {+                    Ok(id) => !baked_ids.contains(&id),+                    // A direct dictionary was never a bake candidate, so it always survives.+                    Err(_) => true,+                })+                .collect();+            if survivors.is_empty() {+                p.remove(b"Annots");+            } else {+                p.set("Annots", Object::Array(survivors));+            }         }     }     true@@ -1171,6 +1215,215 @@ mod redaction_tests {      /// One-page document carrying a single annotation whose `/AP /N` has the     /// given `/BBox` and `/Matrix`.+    /// Flatten must not DESTROY an annotation it could not bake.+    ///+    /// Every failure path in the bake loop is a `continue`, and `/Annots` used to be+    /// removed unconditionally afterwards, so "we could not bake this" and "this is+    /// erased from the user's saved file" were the same outcome. The severe case is an+    /// annotation with no `/AP`: it renders through `synthesize_annotation_appearance`,+    /// so it is visible on screen right up to the moment a flatten deletes it — and+    /// unlike a dropped image this is written to disk, so reopening cannot recover it.+    ///+    /// Note the precondition, which narrows the blast radius: the page needs at least+    /// one BAKEABLE annotation, because `placements.is_empty()` already skips the page+    /// entirely. So the loss needs a MIXED page — a stamp beside a synthesised square,+    /// which is the ordinary shape.+    #[test]+    fn flatten_keeps_an_annotation_it_could_not_bake() {+        let (dw, dh) = (40.0_f64, 20.0_f64);+        let (handle, page_id) =+            flattenable_doc([10.0, 20.0, 10.0 + dw, 20.0 + dh], [0.0, 0.0, dw, dh], IDENTITY);+        // A second annotation with NO /AP — exactly what the renderer synthesises an+        // appearance for, and exactly what the bake loop skips.+        let no_ap_id = {+            let mut reg = registry().lock().unwrap_or_else(|e| e.into_inner());+            let doc = reg.get_mut(&handle).expect("handle is registered");+            let id = doc.add_object(dictionary! {+                "Type" => name_obj("Annot"),+                "Subtype" => name_obj("Square"),+                "Rect" => rect_obj([100.0, 100.0, 200.0, 150.0]),+            });+            let mut annots = doc+                .get_dictionary(page_id)+                .ok()+                .and_then(|d| d.get(b"Annots").ok())+                .and_then(|o| o.as_array().ok())+                .expect("fixture has /Annots")+                .clone();+            annots.push(Object::Reference(id));+            doc.get_dictionary_mut(page_id).expect("page").set("Annots", Object::Array(annots));+            id+        };++        assert!(flatten_document(handle), "flatten failed");++        let text = String::from_utf8_lossy(&page_bytes(handle, page_id)).into_owned();+        assert!(text.contains("Do"), "the bakeable annotation must still flatten: {text}");++        let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+        let doc = reg.get(&handle).expect("handle is registered");+        let annots: Vec<ObjectId> = doc+            .get_dictionary(page_id)+            .ok()+            .and_then(|d| d.get(b"Annots").ok())+            .and_then(|o| deref(doc, o))+            .and_then(|o| o.as_array().ok())+            .map(|a| a.iter().filter_map(|o| o.as_reference().ok()).collect())+            .unwrap_or_default();+        assert_eq!(+            annots,+            vec![no_ap_id],+            "the un-bakeable annotation must survive in /Annots, and the baked one must not"+        );+        assert!(doc.get_dictionary(no_ap_id).is_ok(), "its object must still be in the document");+        drop(reg);+        close_document(handle);+    }++    /// A direct-dictionary `/Annots` entry is legal — §12.5.2 does not require the+    /// indirection — and cannot be baked, because the bake path needs an ObjectId to+    /// reference the appearance from the page's /XObject. So it must be left alone+    /// rather than erased.+    #[test]+    fn flatten_keeps_a_direct_dictionary_annotation() {+        let (dw, dh) = (40.0_f64, 20.0_f64);+        let (handle, page_id) =+            flattenable_doc([10.0, 20.0, 10.0 + dw, 20.0 + dh], [0.0, 0.0, dw, dh], IDENTITY);+        {+            let mut reg = registry().lock().unwrap_or_else(|e| e.into_inner());+            let doc = reg.get_mut(&handle).expect("handle is registered");+            let mut annots = doc+                .get_dictionary(page_id)+                .ok()+                .and_then(|d| d.get(b"Annots").ok())+                .and_then(|o| o.as_array().ok())+                .expect("fixture has /Annots")+                .clone();+            annots.push(Object::Dictionary(dictionary! {+                "Type" => name_obj("Annot"),+                "Subtype" => name_obj("Square"),+                "Rect" => rect_obj([100.0, 100.0, 200.0, 150.0]),+            }));+            doc.get_dictionary_mut(page_id).expect("page").set("Annots", Object::Array(annots));+        }+        assert!(flatten_document(handle), "flatten failed");++        let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+        let doc = reg.get(&handle).expect("handle is registered");+        let annots = doc+            .get_dictionary(page_id)+            .ok()+            .and_then(|d| d.get(b"Annots").ok())+            .and_then(|o| deref(doc, o))+            .and_then(|o| o.as_array().ok())+            .cloned()+            .unwrap_or_default();+        assert_eq!(annots.len(), 1, "only the direct dictionary should remain: {annots:?}");+        assert!(+            matches!(annots.first(), Some(Object::Dictionary(_))),+            "and it must survive verbatim: {annots:?}"+        );+        drop(reg);+        close_document(handle);+    }++    /// When everything on the page IS baked, `/Annots` still goes away entirely: the+    /// retain must not leave an empty array behind, and flatten must still mean+    /// flattened.+    #[test]+    fn flatten_still_removes_annots_when_everything_baked() {+        let (dw, dh) = (40.0_f64, 20.0_f64);+        let (handle, page_id) =+            flattenable_doc([10.0, 20.0, 10.0 + dw, 20.0 + dh], [0.0, 0.0, dw, dh], IDENTITY);+        assert!(flatten_document(handle));+        let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+        let doc = reg.get(&handle).expect("handle is registered");+        assert!(+            doc.get_dictionary(page_id).ok().and_then(|d| d.get(b"Annots").ok()).is_none(),+            "a fully baked page must have no /Annots at all"+        );+        drop(reg);+        close_document(handle);+    }++    /// §7.3.10: `/AS` may be indirect. Without a deref it read as absent, the /Off+    /// branch was taken, and the UNCHECKED art was baked permanently over a checked+    /// box — a wrong answer written into the file rather than a missing one.+    #[test]+    fn flatten_follows_an_indirect_appearance_state() {+        let mut doc = Document::with_version("1.7");+        let form = |content: &[u8]| -> Stream {+            Stream::new(+                dictionary! {+                    "Type" => name_obj("XObject"),+                    "Subtype" => name_obj("Form"),+                    "BBox" => rect_obj([0.0, 0.0, 10.0, 10.0]),+                },+                content.to_vec(),+            )+        };+        let on_id = doc.add_object(form(b"1 0 0 rg 0 0 10 10 re f"));+        let off_id = doc.add_object(form(b"0 1 0 rg 0 0 10 10 re f"));+        // The checked state, reachable only if /AS is dereferenced.+        let as_ref = doc.add_object(Object::Name(b"On".to_vec()));+        let annot_id = doc.add_object(dictionary! {+            "Type" => name_obj("Annot"),+            "Subtype" => name_obj("Widget"),+            "Rect" => rect_obj([0.0, 0.0, 10.0, 10.0]),+            "AS" => Object::Reference(as_ref),+            "AP" => dictionary! { "N" => dictionary! { "On" => on_id, "Off" => off_id } },+        });+        let pages_id = doc.new_object_id();+        let page_id = doc.add_object(dictionary! {+            "Type" => name_obj("Page"),+            "Parent" => Object::Reference(pages_id),+            "MediaBox" => rect_obj([0.0, 0.0, 612.0, 792.0]),+            "Annots" => Object::Array(vec![Object::Reference(annot_id)]),+        });+        doc.objects.insert(+            pages_id,+            Object::Dictionary(dictionary! {+                "Type" => name_obj("Pages"),+                "Kids" => Object::Array(vec![Object::Reference(page_id)]),+                "Count" => 1,+            }),+        );+        let cat = doc.add_object(dictionary! {+            "Type" => name_obj("Catalog"),+            "Pages" => Object::Reference(pages_id),+        });+        doc.trailer.set("Root", cat);+        let handle = next_handle();+        registry().lock().unwrap_or_else(|e| e.into_inner()).insert(handle, doc);++        assert!(flatten_document(handle), "flatten failed");++        let text = String::from_utf8_lossy(&page_bytes(handle, page_id)).into_owned();+        let name = text+            .split_whitespace()+            .collect::<Vec<_>>()+            .windows(2)+            .find(|w| w[1] == "Do")+            .map(|w| w[0].trim_start_matches('/').to_string())+            .unwrap_or_else(|| panic!("no `Do` in the flattened content: {text}"));++        let reg = registry().lock().unwrap_or_else(|e| e.into_inner());+        let doc = reg.get(&handle).expect("handle is registered");+        let res = resources_dict(doc, page_id).expect("resources");+        let baked = res+            .get(b"XObject")+            .ok()+            .and_then(|o| deref(doc, o))+            .and_then(|o| o.as_dict().ok())+            .and_then(|xo| xo.get(name.as_bytes()).ok())+            .and_then(|o| o.as_reference().ok())+            .expect("the baked appearance must be in /Resources /XObject");+        assert_ne!(baked, off_id, "an indirect /AS must not fall through to the /Off art");+        assert_eq!(baked, on_id, "an indirect /AS On must bake the CHECKED art");+        drop(reg);+        close_document(handle);+    }+     fn flattenable_doc(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> (i64, ObjectId) {         let mut doc = Document::with_version("1.7");         let ap_dict = dictionary! {
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 efaec767df..4edf0cf163 100644--- a/pdf/src/main/rust/src/draw.rs+++ b/pdf/src/main/rust/src/draw.rs@@ -1,5 +1,18 @@ use crate::*; +/// Nesting depth allowed for expanding a Type 3 CharProc.+///+/// This shares the interpreter's single `depth` counter with form XObjects, so it+/// must match the `depth < 10` guard in the `Do` arm ([`MAX_GROUP_DEPTH`]) rather+/// than [`MAX_PATTERN_RECURSION`]. It was gated on the latter (4), which is the+/// SOFT-MASK expansion cap and is deliberately low for reasons `interpret.rs`+/// documents — an unmetered mask branches unbounded. Borrowing it here meant two+/// subsystems capped the same counter at different depths: an annotation appearance+/// enters at depth 1, so just three nested form XObjects inside one exhausted the+/// Type 3 budget and every glyph of the run vanished, unsearchable as well as+/// unpainted, while a plain form at the same depth carried on to 10.+const MAX_TYPE3_DEPTH: u32 = MAX_GROUP_DEPTH;+ /// Everything on `Prim::Text` is derived from unvalidated file input (`Tf`, `Tz`, /// `/Widths`, the CTM), and a non-finite value can survive even validated operands: /// `f64 as f32` saturates to infinity above ~3.4e38. It cannot be left to the@@ -209,13 +222,29 @@ pub(crate) fn show_string_in(     // must still reach the text index or the document is unsearchable. `argb: 0`     // here plus the `rm != 3` paint guard in SafePdfViewerScreen.kt keep it unseen.     let invisible = gs.render_mode == 3;+    let clip_only = gs.render_mode == 7;      let fi = match fonts.get(&gs.font_key) {         Some(fi) => fi,         None => {             // No font metrics: emit the run at the origin and estimate advance.             let run_advance = bytes.len() as f64 * 0.5 * tfs * th;-            if (drawable || invisible) && !bytes.is_empty() {+            // Mode 7 is included deliberately. §9.3.6 Table 106 separates 4-6 from 7+            // only by whether ink is laid down; their §9.4.3 clip contribution is+            // identical, and 4-6 already emit here. Excluding 7 made the operator a+            // total no-op whenever the font resource was missing, which also broke the+            // commitment in `hidden_render_mode`: it maps a 4-6 run inside an OFF+            // optional-content group to 7 precisely so the clip still contributes, and+            // that clip then disappeared. This gate and the latch must stay IDENTICAL:+            // `latches_text_clip`'s no-font arm is `!bytes.is_empty()`, the same+            // condition as here, so every clip it latches has a record to accumulate+            // from. The latch does NOT follow prim emission — that predicate was+            // considered and rejected there, and a run whose glyphs all drop still+            // latches and clips to EMPTY. So narrowing this gate alone would not drop+            // the clip, it would apply an empty one and blank the rest of the text+            // object. The outline is a substitute face, so the shape is approximate;+            // that is the same approximation 4-6 already accept.+            if (drawable || invisible || clip_only) && !bytes.is_empty() {                 let (x, y) = transform(&trm, 0.0, gs.rise);                 let text: String =                     bytes.iter().filter_map(|&b| char::from_u32(b as u32)).collect();@@ -224,7 +253,7 @@ pub(crate) fn show_string_in(                         x: x as f32,                         y: y as f32,                         size,-                        argb: if invisible { 0 } else { apply_alpha_to_argb(gs.fill, gs.alpha_fill) },+                        argb: if invisible || clip_only { 0 } else { apply_alpha_to_argb(gs.fill, gs.alpha_fill) },                         text,                         stroke_argb: None,                         stroke_width: None,@@ -255,12 +284,14 @@ pub(crate) fn show_string_in(     }      let mut pen = 0.0_f64;-    // Fix high #12: device stroke width should use Trm scale (includes Tm·Tfs·Th), not just CTM-    let trm = mat_mul(text_matrix, &gs.ctm);-    let sx_trm = (trm[0] * trm[0] + trm[1] * trm[1]).sqrt();-    let sy_trm = (trm[2] * trm[2] + trm[3] * trm[3]).sqrt();-    let avg_trm_scale = (sx_trm + sy_trm) * 0.5;-    let device_stroke_w = (gs.line_width * avg_trm_scale) as f32;+    // §8.4.3.2: the line width is a distance in USER space, so the pen is scaled by+    // the CTM alone. The text matrix and font size scale the GLYPH, not the pen —+    // §9.3.6 does not override this. Scaling by Trm made a `12 0 0 12 ...` Tm (the+    // shape cairo emits) paint a 0.5pt pen as 6pt, closing every counter.+    let ctm = &gs.ctm;+    let sx_ctm = (ctm[0] * ctm[0] + ctm[1] * ctm[1]).sqrt();+    let sy_ctm = (ctm[2] * ctm[2] + ctm[3] * ctm[3]).sqrt();+    let device_stroke_w = (gs.line_width * (sx_ctm + sy_ctm) * 0.5) as f32;     // Constant per-font attributes hoisted out of the per-glyph closure.     let bold = fi.style.bold;     let italic = fi.style.italic;@@ -328,9 +359,20 @@ pub(crate) fn show_string_in(                 // `advance > 0f` guard PASSES infinity, so one overflowed glyph                 // would stretch every remaining glyph's rectangle in the run.                 let glyph_device_adv = finite_or_zero(glyph_device_adv);-                // Real embedded outline for pure paint modes (0/1/2). Clip modes-                // (4-7) keep the subst

Diff truncated.