Modern Apps git

← Modern-Apps.git

pdf: add native lopdf PDF renderer (Rust/JNI)

Commit
347cd8c6f56e7af80a471337f7285c96472c1007
Author
Vayun Mathur <[email protected]>
When
2026-07-08 18:04 UTC (5 months ago)
Parents
ac188f3

Diff

pdf/build.gradle.kts
diff --git a/pdf/build.gradle.kts b/pdf/build.gradle.ktsindex 7b680c968b..9cbec21456 100644--- a/pdf/build.gradle.kts+++ b/pdf/build.gradle.kts@@ -1,3 +1,5 @@+import java.util.Properties+ plugins {     id("common-conventions-app")     id("common-conventions-metadata")@@ -7,6 +9,98 @@ android {     defaultConfig {         applicationId = "com.vayunmathur.pdf"     }+    // The Rust build drops <abi>/libpdf_render.so under this dir; register it as+    // a jniLibs source so AGP packages the native lib.+    sourceSets["main"].jniLibs.srcDir(layout.buildDirectory.dir("rustJniLibs").get().asFile)+}++// ---------------------------------------------------------------------------+// Native PDF renderer (Rust + lopdf). See pdf/rust/.+//+// Powers the "Open PDF (safe)" viewer: parses PDFs entirely in memory-safe Rust+// and returns plain drawing primitives, never touching the system PDF stack.+// Cross-compiled per-ABI with the NDK's clang, driven directly from cargo (same+// approach as :weather).+//+// Contributor/CI prerequisite:+//   rustup target add aarch64-linux-android+// arm64 is the device/release ABI; the release build filters to arm64-v8a (see+// the build convention). Apple-Silicon emulators are arm64 too.+// ---------------------------------------------------------------------------++val ndkVersionForRust = "29.0.14206865"+val androidApiLevel = 31++fun resolveSdkDir(): String =+    System.getenv("ANDROID_HOME")+        ?: System.getenv("ANDROID_SDK_ROOT")+        ?: rootProject.file("local.properties").takeIf { it.exists() }?.let { f ->+            Properties().apply { f.inputStream().use { load(it) } }.getProperty("sdk.dir")+        }+        ?: error("Android SDK not found (set ANDROID_HOME or sdk.dir in local.properties)")++val cargoBin = "${System.getProperty("user.home")}/.cargo/bin"+val ndkRoot = "${resolveSdkDir()}/ndk/$ndkVersionForRust"+// The NDK ships an x86_64 host toolchain (runs under Rosetta on Apple Silicon).+val hostTag = when {+    org.gradle.internal.os.OperatingSystem.current().isMacOsX -> "darwin-x86_64"+    org.gradle.internal.os.OperatingSystem.current().isLinux -> "linux-x86_64"+    org.gradle.internal.os.OperatingSystem.current().isWindows -> "windows-x86_64"+    else -> error("Unsupported host OS for NDK toolchain")+}+val ndkBin = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/bin"+val ndkSysroot = "$ndkRoot/toolchains/llvm/prebuilt/$hostTag/sysroot"++// (jniLibs ABI dir, Rust target triple)+// Only arm64-v8a: the dev build type inherits the convention's+// `abiFilters = ["arm64-v8a"]` (same as release), so any other ABI would be+// filtered out of the APK anyway. To support Intel-host emulators, add+// `"x86_64" to "x86_64-linux-android"` here and drop the abiFilter for dev.+val rustAbis = listOf(+    "arm64-v8a" to "aarch64-linux-android",+)++val perAbiBuildTasks = rustAbis.map { (abiDir, triple) ->+    tasks.register<Exec>("cargoBuild_${abiDir.replace('-', '_')}") {+        description = "Cross-compiles the Rust PDF renderer for $abiDir."+        workingDir = file("rust")++        val clang = "$ndkBin/$triple$androidApiLevel-clang"+        val linkerVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_LINKER"+        val soOut = file("rust/target/$triple/release/libpdf_render.so")+        val destSo = layout.buildDirectory.file("rustJniLibs/$abiDir/libpdf_render.so").get().asFile++        inputs.dir("rust/src")+        inputs.file("rust/Cargo.toml")+        outputs.file(destSo)++        // Prepend the rustup toolchain (has the Android targets) ahead of any+        // Homebrew rust on PATH.+        environment("PATH", "$cargoBin:${System.getenv("PATH")}")+        // The per-API NDK clang wrapper bakes in --target and the sysroot.+        environment("CC", clang)+        environment("AR", "$ndkBin/llvm-ar")+        environment("SYSROOT", ndkSysroot)+        environment(linkerVar, clang)+        // Keep host-side C tooling (if any build dep needs it) on the host clang.+        environment("HOST_CC", "/usr/bin/clang")++        commandLine("$cargoBin/cargo", "build", "--release", "--target", triple)++        doLast {+            destSo.parentFile.mkdirs()+            soOut.copyTo(destSo, overwrite = true)+        }+    }+}++val cargoNdkBuild by tasks.registering {+    description = "Builds libpdf_render.so for all Android ABIs."+    dependsOn(perAbiBuildTasks)+}++tasks.matching { it.name == "preBuild" }.configureEach {+    dependsOn(cargoNdkBuild) }  dependencies {
pdf/rust/.gitignore
diff --git a/pdf/rust/.gitignore b/pdf/rust/.gitignorenew file mode 100644index 0000000000..ea8c4bf7f3--- /dev/null+++ b/pdf/rust/.gitignore@@ -0,0 +1 @@+/target
pdf/rust/Cargo.lock
diff --git a/pdf/rust/Cargo.lock b/pdf/rust/Cargo.locknew file mode 100644index 0000000000..71193a8de8--- /dev/null+++ b/pdf/rust/Cargo.lock@@ -0,0 +1,1177 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "aes"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"+dependencies = [+ "cfg-if",+ "cipher",+ "cpufeatures",+]++[[package]]+name = "android_system_properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"+dependencies = [+ "libc",+]++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "block-padding"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"+dependencies = [+ "generic-array",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytecount"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "cbc"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"+dependencies = [+ "cipher",+]++[[package]]+name = "cc"+version = "1.2.66"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "num-traits",+ "windows-link",+]++[[package]]+name = "cipher"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"+dependencies = [+ "crypto-common",+ "inout",+]++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "defmt"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"+dependencies = [+ "bitflags 1.3.2",+ "defmt-macros",+]++[[package]]+name = "defmt-macros"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"+dependencies = [+ "defmt-parser",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "defmt-parser"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"+dependencies = [+ "thiserror 2.0.18",+]++[[package]]+name = "deranged"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "ecb"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a8bfa975b1aec2145850fcaa1c6fe269a16578c44705a532ae3edc92b8881c7"+dependencies = [+ "cipher",+]++[[package]]+name = "either"+version = "1.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"++[[package]]+name = "encoding_rs"+version = "0.8.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"+dependencies = [+ "cfg-if",+]++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"++[[package]]+name = "flate2"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"+dependencies = [+ "crc32fast",+ "miniz_oxide",+]++[[package]]+name = "futures-core"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"++[[package]]+name = "futures-task"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"++[[package]]+name = "futures-util"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+dependencies = [+ "futures-core",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+ "wasip2",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "indexmap"+version = "2.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"+dependencies = [+ "equivalent",+ "hashbrown",+]++[[package]]+name = "inout"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"+dependencies = [+ "block-padding",+ "generic-array",+]++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "jiff"+version = "0.2.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccfe6121cbe750cf81efa362d85c0bde7ea298ec43092d3a193baca59cdbd634"+dependencies = [+ "defmt",+ "jiff-static",+ "jiff-tzdb-platform",+ "log",+ "portable-atomic",+ "portable-atomic-util",+ "serde_core",+ "windows-link",+]++[[package]]+name = "jiff-static"+version = "0.2.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e165e897f662d428f3cd3828a919dbe067c2d42bb1031eede74ef9d27ecdedd2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "jiff-tzdb"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6142247df1a93c2b3587402a19710be3e6e942f1581a1702e76408f2c21d6590"++[[package]]+name = "jiff-tzdb-platform"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"+dependencies = [+ "jiff-tzdb",+]++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror 1.0.69",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "js-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "libc"+version = "0.2.186"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "lopdf"+version = "0.36.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59fa2559e99ba0f26a12458aabc754432c805bbb8cba516c427825a997af1fb7"+dependencies = [+ "aes",+ "bitflags 2.13.0",+ "cbc",+ "chrono",+ "ecb",+ "encoding_rs",+ "flate2",+ "indexmap",+ "itoa",+ "jiff",+ "log",+ "md-5",+ "nom",+ "nom_locate",+ "rand",+ "rangemap",+ "rayon",+ "sha2",+ "stringprep",+ "thiserror 2.0.18",+ "time",+ "weezl",+]++[[package]]+name = "md-5"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"+dependencies = [+ "cfg-if",+ "digest",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "nom"+version = "8.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"+dependencies = [+ "memchr",+]++[[package]]+name = "nom_locate"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b577e2d69827c4740cba2b52efaad1c4cc7c73042860b199710b3575c68438d"+dependencies = [+ "bytecount",+ "memchr",+ "nom",+]++[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "pdf_render"+version = "0.1.0"+dependencies = [+ "jni",+ "lopdf",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "portable-atomic"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"++[[package]]+name = "portable-atomic-util"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"+dependencies = [+ "portable-atomic",+]++[[package]]+name = "powerfmt"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "rand"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"+dependencies = [+ "rand_chacha",+ "rand_core",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom",+]++[[package]]+name = "rangemap"+version = "1.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68"++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "simd-adler32"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "stringprep"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"+dependencies = [+ "unicode-bidi",+ "unicode-normalization",+ "unicode-properties",+]++[[package]]+name = "syn"+version = "2.0.118"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl 2.0.18",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "time"+version = "0.3.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50"+dependencies = [+ "deranged",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"++[[package]]+name = "time-macros"+version = "0.2.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f"+dependencies = [+ "num-conv",+ "time-core",+]++[[package]]+name = "tinyvec"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"+dependencies = [+ "tinyvec_macros",+]++[[package]]+name = "tinyvec_macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-bidi"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "unicode-normalization"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"+dependencies = [+ "tinyvec",+]++[[package]]+name = "unicode-properties"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "weezl"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "zerocopy"+version = "0.8.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75726053136156d419e285b9b7eddaaea9e3fea6ce32eed44a89901f0bd98de1"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4714fd92cf900833d49538023a9b3915155210801d1c1169eba513b2addefd71"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]
pdf/rust/Cargo.toml
diff --git a/pdf/rust/Cargo.toml b/pdf/rust/Cargo.tomlnew file mode 100644index 0000000000..7edaecbe64--- /dev/null+++ b/pdf/rust/Cargo.toml@@ -0,0 +1,21 @@+[package]+name = "pdf_render"+version = "0.1.0"+edition = "2021"+description = "Memory-safe PDF content-stream interpreter (lopdf) for the 'Open PDF (safe)' viewer, exposed to Kotlin via JNI"+license = "GPL-2.0-only"++[lib]+name = "pdf_render"+crate-type = ["cdylib", "rlib"]++[dependencies]+lopdf = "0.36"+jni = "0.21"++[profile.release]+opt-level = 3+lto = true+codegen-units = 1+panic = "abort"+strip = true
pdf/rust/README.md
diff --git a/pdf/rust/README.md b/pdf/rust/README.mdnew file mode 100644index 0000000000..3cf41b734e--- /dev/null+++ b/pdf/rust/README.md@@ -0,0 +1,51 @@+# pdf_render — memory-safe PDF renderer (Rust + JNI)++Parses PDFs entirely in Rust with [`lopdf`] (no pdfium / no system PDF stack)+and reduces each page to plain drawing primitives — text runs, filled polygons+and stroked polylines — for the "Open PDF (safe)" viewer. Built into+`libpdf_render.so` and called from Kotlin via `PdfNative`.++The point of "safe": all untrusted binary parsing happens in memory-safe Rust,+and the JNI boundary only ever passes a flat little-endian buffer of geometry ++UTF-8 text, so Kotlin never touches the raw PDF bytes.++## Scope (v1)++- Text with `/ToUnicode` CMap decoding (1-byte simple fonts and 2-byte+  Identity-H / Type0), Latin-1 fallback.+- Vector paths: lines, rectangles, filled/stroked paths, flattened beziers,+  positioned via the content-stream graphics state (CTM + text matrix).+- Deferred: embedded raster images (XObjects), encryption/passwords, form+  fields, annotations, shadings/patterns.++Encrypted PDFs return a 0 handle so the viewer shows a clean error instead of+attempting decryption.++## Prerequisites (local + CI)++The `:pdf` module cross-compiles this crate for Android using the NDK's clang,+driven directly from a Gradle task (`cargoNdkBuild` in `pdf/build.gradle.kts`).+You need `rustup` with the Android target:++```sh+rustup target add aarch64-linux-android+```++`aarch64-linux-android` (`arm64-v8a`) is the only ABI the app ships (dev and+release both filter to `arm64-v8a`). The Android NDK is required (pinned via+`ndkVersion` in the build convention).++`./gradlew :pdf:assembleDebug` runs `cargoNdkBuild` automatically (wired into+`preBuild`) and packages the `.so` from `build/rustJniLibs/<abi>/`.++## Host tests++The interpreter, CMap parser and wire format are validated on the host (no+Android / NDK needed):++```sh+cd pdf/rust+cargo test+```++[`lopdf`]: https://crates.io/crates/lopdf
pdf/rust/src/lib.rs
diff --git a/pdf/rust/src/lib.rs b/pdf/rust/src/lib.rsnew file mode 100644index 0000000000..f16b69217c--- /dev/null+++ b/pdf/rust/src/lib.rs@@ -0,0 +1,3418 @@+//! Memory-safe PDF renderer for the "Open PDF (safe)" viewer.+//!+//! Parses a PDF entirely in Rust with `lopdf` (no pdfium / no native system+//! PDF stack) and reduces each page to plain drawing primitives — text runs,+//! filled polygons and stroked polylines — positioned in PDF page space. The+//! Kotlin side (`com.vayunmathur.pdf.util.SafePdfParser`) decodes the compact+//! little-endian buffer produced here and draws it on a Compose `Canvas`.+//!+//! Design goals: all untrusted binary parsing happens in memory-safe Rust; the+//! JNI boundary only ever passes a flat byte buffer of geometry + UTF-8 text,+//! so Kotlin never touches the raw PDF bytes.+//!+//! v1 scope: text (with `/ToUnicode` decoding) + vector paths (lines,+//! rectangles, filled/stroked paths, flattened beziers). No embedded raster+//! images (XObjects), no encryption, no shadings/patterns. See the plan and the+//! app README for the deferred list.++use std::collections::HashMap;+use std::sync::{Mutex, OnceLock};++use lopdf::content::Content;+use lopdf::{Dictionary, Document, Object, ObjectId, Stream};++// ---------------------------------------------------------------------------+// Document registry+// ---------------------------------------------------------------------------++/// Process-wide registry of parsed documents keyed by an opaque `i64` handle,+/// mirroring the weather crate's `cached_backend`. Keeping the parsed+/// `Document` alive lets Kotlin re-render / re-scroll pages without re-parsing+/// the file.+fn registry() -> &'static Mutex<HashMap<i64, Document>> {+    static REG: OnceLock<Mutex<HashMap<i64, Document>>> = OnceLock::new();+    REG.get_or_init(|| Mutex::new(HashMap::new()))+}++fn next_handle() -> i64 {+    static NEXT: OnceLock<Mutex<i64>> = OnceLock::new();+    let m = NEXT.get_or_init(|| Mutex::new(0));+    let mut guard = m.lock().unwrap();+    *guard += 1;+    *guard+}++/// Parse `bytes` into a document and store it, returning a non-zero handle.+/// Returns 0 on parse failure or if the document is encrypted (v1 shows a+/// clean error rather than attempting decryption).+fn open_document(bytes: &[u8]) -> i64 {+    let doc = match Document::load_mem(bytes) {+        Ok(d) => d,+        Err(_) => return 0,+    };+    if doc.trailer.get(b"Encrypt").is_ok() {+        return 0;+    }+    let handle = next_handle();+    registry().lock().unwrap().insert(handle, doc);+    handle+}++fn page_count(handle: i64) -> i32 {+    let reg = registry().lock().unwrap();+    match reg.get(&handle) {+        Some(doc) => doc.get_pages().len() as i32,+        None => 0,+    }+}++fn close_document(handle: i64) {+    registry().lock().unwrap().remove(&handle);+}++/// Serialize page `index` (0-based) of the document behind `handle` into the+/// wire buffer, or `None` on any error.+fn render_page(handle: i64, index: i32) -> Option<Vec<u8>> {+    let reg = registry().lock().unwrap();+    let doc = reg.get(&handle)?;+    let pages = doc.get_pages();+    let page_id = *pages.get(&((index as u32) + 1))?;+    let page = interpret_page(doc, page_id).ok()?;+    Some(wire::serialize(&page))+}++// ---------------------------------------------------------------------------+// Geometry / matrix helpers+// ---------------------------------------------------------------------------++/// A PDF transformation matrix `[a b c d e f]` representing+/// `[[a b 0] [c d 0] [e f 1]]`.+type Mat = [f64; 6];++const IDENTITY: Mat = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];++/// `m1 * m2` in PDF convention (m1 is applied first).+fn mat_mul(m1: &Mat, m2: &Mat) -> Mat {+    [+        m1[0] * m2[0] + m1[1] * m2[2],+        m1[0] * m2[1] + m1[1] * m2[3],+        m1[2] * m2[0] + m1[3] * m2[2],+        m1[2] * m2[1] + m1[3] * m2[3],+        m1[4] * m2[0] + m1[5] * m2[2] + m2[4],+        m1[4] * m2[1] + m1[5] * m2[3] + m2[5],+    ]+}++/// Transform point `(x, y)` by `m`.+fn transform(m: &Mat, x: f64, y: f64) -> (f64, f64) {+    (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5])+}++fn translate(tx: f64, ty: f64) -> Mat {+    [1.0, 0.0, 0.0, 1.0, tx, ty]+}++// ---------------------------------------------------------------------------+// Primitives+// ---------------------------------------------------------------------------++/// Drawing primitives in PDF page space (origin bottom-left). Kotlin performs+/// the Y-flip and fit-to-width scale.+enum Prim {+    Text {+        x: f32,+        y: f32,+        size: f32,+        argb: u32,+        text: String,+    },+    Fill {+        argb: u32,+        even_odd: bool,+        pts: Vec<(f32, f32)>,+    },+    Stroke {+        argb: u32,+        width: f32,+        /// Dash segment lengths in device space (empty = solid).+        dash: Vec<f32>,+        dash_phase: f32,+        pts: Vec<(f32, f32)>,+    },+    /// A raster image placed by mapping the unit square through `ctm` (PDF image+    /// space). `format`: 0 = raw RGBA8888 (`w*h*4` bytes), 1 = JPEG bytes.+    Image {+        ctm: Mat,+        w: u32,+        h: u32,+        format: u8,+        data: Vec<u8>,+    },+}++struct PageData {+    width: f32,+    height: f32,+    prims: Vec<Prim>,+}++// ---------------------------------------------------------------------------+// Object helpers+// ---------------------------------------------------------------------------++/// Numeric value of an integer or real object, else `None`.+fn num(obj: &Object) -> Option<f64> {+    match obj {+        Object::Integer(i) => Some(*i as f64),+        Object::Real(r) => Some(*r as f64),+        _ => None,+    }+}++/// Follow a chain of references to the underlying object.+fn deref<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a Object> {+    match doc.dereference(obj) {+        Ok((_, o)) => Some(o),+        Err(_) => None,+    }+}++// ---------------------------------------------------------------------------+// Fonts + ToUnicode+// ---------------------------------------------------------------------------++struct FontInfo {+    /// Type0 (Identity-H) fonts use 2-byte codes; simple fonts use 1 byte.+    two_byte: bool,+    /// `code -> unicode string` from the font's `/ToUnicode` CMap, if any.+    to_unicode: Option<HashMap<u32, String>>,+    /// `code -> unicode char` from the simple-font encoding (base + Differences),+    /// used when `/ToUnicode` is absent or lacks the code.+    encoding: HashMap<u32, char>,+    /// `code (or CID) -> glyph width` in text-space units (glyph units / 1000).+    widths: HashMap<u32, f64>,+    /// Fallback width (glyph units / 1000) for codes absent from `widths`.+    default_width: f64,+}++impl FontInfo {+    /// Decode a shown PDF string's raw bytes into text using this font.+    fn decode(&self, bytes: &[u8]) -> String {+        let mut out = String::new();+        self.for_each_code(bytes, |code, _| self.push_code(code, &mut out));+        out+    }++    /// Invoke `f(code, is_single_byte_space)` for each character code in the+    /// string, honoring this font's code width (1 or 2 bytes).+    fn for_each_code(&self, bytes: &[u8], mut f: impl FnMut(u32, bool)) {+        if self.two_byte {+            let mut i = 0;+            while i + 1 < bytes.len() {+                let code = ((bytes[i] as u32) << 8) | bytes[i + 1] as u32;+                f(code, false);+                i += 2;+            }+        } else {+            for &b in bytes {+                f(b as u32, b == 32);+            }+        }+    }++    /// Width of `code` in text-space units (glyph units / 1000).+    fn width(&self, code: u32) -> f64 {+        self.widths.get(&code).copied().unwrap_or(self.default_width)+    }++    /// Total horizontal advance (user-space units) of `bytes` given the current+    /// text state, per PDF 9.4.4:+    /// `tx = Σ ((w0)*Tfs + Tc + Tw[space]) * Th`.+    fn advance(&self, bytes: &[u8], tfs: f64, tc: f64, tw: f64, th: f64) -> f64 {+        let mut adv = 0.0;+        self.for_each_code(bytes, |code, is_space| {+            let mut t = self.width(code) * tfs + tc;+            if is_space {+                t += tw;+            }+            adv += t;+        });+        adv * th+    }++    fn push_code(&self, code: u32, out: &mut String) {+        if let Some(map) = &self.to_unicode {+            if let Some(s) = map.get(&code) {+                out.push_str(s);+                return;+            }+        }+        if let Some(c) = self.encoding.get(&code) {+            out.push(*c);+            return;+        }+        // Last resort: Latin-1 for single-byte codes; best-effort otherwise.+        if let Some(c) = char::from_u32(code) {+            out.push(c);+        }+    }+}++/// Build a `font resource name -> FontInfo` map from a resources dictionary.+fn fonts_from_resources(doc: &Document, res_dict: &lopdf::Dictionary) -> HashMap<Vec<u8>, FontInfo> {+    let mut fonts = HashMap::new();+    let font_dict = match res_dict.get(b"Font").ok().and_then(|o| deref(doc, o)) {+        Some(Object::Dictionary(d)) => d,+        _ => return fonts,+    };+    for (name, font_ref) in font_dict.iter() {+        if let Some(Object::Dictionary(fd)) = deref(doc, font_ref) {+            fonts.insert(name.clone(), font_info(doc, fd));+        }+    }+    fonts+}++fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo {+    let two_byte = matches!(+        font.get(b"Subtype").ok().and_then(|o| o.as_name().ok()),+        Some(b"Type0")+    );+    let to_unicode = font+        .get(b"ToUnicode")+        .ok()+        .and_then(|o| deref(doc, o))+        .and_then(|o| match o {+            Object::Stream(s) => s.decompressed_content().ok(),+            _ => None,+        })+        .map(|data| cmap::parse(&data));++    let (widths, default_width) = if two_byte {+        cid_widths(doc, font)+    } else {+        simple_widths(doc, font)+    };++    let encoding = if two_byte {+        HashMap::new()+    } else {+        encoding::build(doc, font)+    };++    FontInfo {+        two_byte,+        to_unicode,+        encoding,+        widths,+        default_width,+    }+}++/// Widths for a simple (1-byte) font from `/Widths` + `/FirstChar`, with the+/// `/FontDescriptor /MissingWidth` fallback. Values are glyph units / 1000.+fn simple_widths(doc: &Document, font: &lopdf::Dictionary) -> (HashMap<u32, f64>, f64) {+    let mut widths = HashMap::new();+    let first_char = font+        .get(b"FirstChar")+        .ok()+        .and_then(num)+        .unwrap_or(0.0) as u32;+    if let Some(Object::Array(arr)) = font.get(b"Widths").ok().and_then(|o| deref(doc, o)) {+        for (i, w) in arr.iter().enumerate() {+            if let Some(w) = deref(doc, w).and_then(num) {+                widths.insert(first_char + i as u32, w / 1000.0);+            }+        }+    }+    let missing = font+        .get(b"FontDescriptor")+        .ok()+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_dict().ok())+        .and_then(|d| d.get(b"MissingWidth").ok())+        .and_then(num)+        .unwrap_or(0.0)+        / 1000.0;+    // Simple fonts without a /Widths array (e.g. the standard 14) get a+    // reasonable default so advances are non-degenerate.+    let default_width = if widths.is_empty() { 0.5 } else { missing };+    (widths, default_width)+}++/// Widths for a Type0/CID font from the descendant font's `/W` array + `/DW`.+/// The map is keyed by CID (== 2-byte code for Identity-H). Units glyph/1000.+fn cid_widths(doc: &Document, font: &lopdf::Dictionary) -> (HashMap<u32, f64>, f64) {+    let mut widths = HashMap::new();+    let mut default_width = 1.0; // /DW default is 1000 glyph units.++    let descendant = font+        .get(b"DescendantFonts")+        .ok()+        .and_then(|o| deref(doc, o))+        .and_then(|o| match o {+            Object::Array(a) => a.first(),+            _ => None,+        })+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_dict().ok());++    let df = match descendant {+        Some(d) => d,+        None => return (widths, default_width),+    };++    if let Some(dw) = df.get(b"DW").ok().and_then(num) {+        default_width = dw / 1000.0;+    }++    // /W: [ c [w1 w2 ...]  cFirst cLast w  ... ]+    if let Some(Object::Array(w)) = df.get(b"W").ok().and_then(|o| deref(doc, o)) {+        let mut i = 0;+        while i < w.len() {+            let c = match deref(doc, &w[i]).and_then(num) {+                Some(v) => v as u32,+                None => break,+            };+            match w.get(i + 1).and_then(|o| deref(doc, o)) {+                Some(Object::Array(list)) => {+                    for (j, item) in list.iter().enumerate() {+                        if let Some(v) = deref(doc, item).and_then(num) {+                            widths.insert(c + j as u32, v / 1000.0);+                        }+                    }+                    i += 2;+                }+                _ => {+                    let c_last = w.get(i + 1).and_then(|o| deref(doc, o)).and_then(num);+                    let width = w.get(i + 2).and_then(|o| deref(doc, o)).and_then(num);+                    if let (Some(c_last), Some(width)) = (c_last, width) {+                        for cid in c..=(c_last as u32) {+                            widths.insert(cid, width / 1000.0);+                        }+                    }+                    i += 3;+                }+            }+        }+    }+    (widths, default_width)+}++/// Look up `key` on the page dict, walking up `/Parent` for inherited+/// attributes (`MediaBox`, `Resources`).+fn inherited<'a>(doc: &'a Document, page_id: ObjectId, key: &[u8]) -> Option<&'a Object> {+    let mut current = page_id;+    for _ in 0..32 {+        let dict = doc.get_dictionary(current).ok()?;+        if let Ok(obj) = dict.get(key) {+            return Some(obj);+        }+        match dict.get(b"Parent").ok().and_then(|o| o.as_reference().ok()) {+            Some(parent) => current = parent,+            None => return None,+        }+    }+    None+}++/// Page MediaBox as `[x0, y0, x1, y1]`, defaulting to US Letter.+fn media_box(doc: &Document, page_id: ObjectId) -> [f64; 4] {+    let default = [0.0, 0.0, 612.0, 792.0];+    let obj = match inherited(doc, page_id, b"MediaBox").and_then(|o| deref(doc, o)) {+        Some(o) => o,+        None => return default,+    };+    let arr = match obj.as_array() {+        Ok(a) => a,+        Err(_) => return default,+    };+    if arr.len() != 4 {+        return default;+    }+    let mut out = [0.0; 4];+    for (i, v) in arr.iter().enumerate() {+        out[i] = match deref(doc, v).and_then(num) {+            Some(n) => n,+            None => return default,+        };+    }+    out+}++// ---------------------------------------------------------------------------+// Colors+// ---------------------------------------------------------------------------++fn rgb_to_argb(r: f64, g: f64, b: f64) -> u32 {+    let c = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u32;+    0xFF00_0000 | (c(r) << 16) | (c(g) << 8) | c(b)+}++fn gray_to_argb(v: f64) -> u32 {+    rgb_to_argb(v, v, v)+}++fn cmyk_to_argb(c: f64, m: f64, y: f64, k: f64) -> u32 {+    let r = (1.0 - c) * (1.0 - k);+    let g = (1.0 - m) * (1.0 - k);+    let b = (1.0 - y) * (1.0 - k);+    rgb_to_argb(r, g, b)+}++// ---------------------------------------------------------------------------+// Content-stream interpreter+// ---------------------------------------------------------------------------++#[derive(Clone)]+struct GraphicsState {+    ctm: Mat,+    fill: u32,+    stroke: u32,+    line_width: f64,+    font_key: Vec<u8>,+    font_size: f64,+    /// Character spacing (Tc), user-space units.+    char_spacing: f64,+    /// Word spacing (Tw), user-space units (applies to single-byte code 32).+    word_spacing: f64,+    /// Horizontal scaling (Tz) as a fraction (100% = 1.0).+    h_scale: f64,+    /// Text rise (Ts), user-space units.+    rise: f64,+    /// Text rendering mode (Tr). 3 = invisible, 7 = clip-only (not drawn).+    render_mode: i64,+    /// Dash pattern (user-space segment lengths) and phase; empty = solid.+    dash: Vec<f64>,+    dash_phase: f64,+}++impl Default for GraphicsState {+    fn default() -> Self {+        GraphicsState {+            ctm: IDENTITY,+            fill: 0xFF00_0000,+            stroke: 0xFF00_0000,+            line_width: 1.0,+            font_key: Vec::new(),+            font_size: 0.0,+            char_spacing: 0.0,+            word_spacing: 0.0,+            h_scale: 1.0,+            rise: 0.0,+            render_mode: 0,+            dash: Vec::new(),+            dash_phase: 0.0,+        }+    }+}++/// Number of line segments a bezier curve is flattened into.+const BEZIER_STEPS: usize = 16;++fn interpret_page(doc: &Document, page_id: ObjectId) -> Result<PageData, String> {+    let mb = media_box(doc, page_id);+    let width = (mb[2] - mb[0]).abs() as f32;+    let height = (mb[3] - mb[1]).abs() as f32;++    let content = doc+        .get_and_decode_page_content(page_id)+        .map_err(|e| format!("decode content failed: {e:?}"))?;+    let res = resources_dict(doc, page_id);++    let mut prims = Vec::new();+    interpret_content(+        doc,+        &content.operations,+        res.as_ref(),+        GraphicsState::default(),+        &mut prims,+        0,+    );+    render_annotations(doc, page_id, &mut prims);++    Ok(PageData {+        width,+        height,+        prims,+    })+}++/// Interpret a content stream (`ops`) against a `resources` dictionary into+/// drawing primitives, starting from `init` graphics state. Reused for page+/// content, form XObjects (`Do`), and annotation appearance streams. `depth`+/// bounds recursion through nested form XObjects.+fn interpret_content(+    doc: &Document,+    ops: &[lopdf::content::Operation],+    resources: Option<&lopdf::Dictionary>,+    init: GraphicsState,+    prims: &mut Vec<Prim>,+    depth: u32,+) {+    let fonts = resources+        .map(|r| fonts_from_resources(doc, r))+        .unwrap_or_default();+    let xobjects = resources+        .map(|r| xobjects_from_resources(doc, r))+        .unwrap_or_default();++    let mut gs = init;+    let mut stack: Vec<GraphicsState> = Vec::new();++    // Text state.+    let mut text_matrix = IDENTITY;+    let mut line_matrix = IDENTITY;+    let mut leading = 0.0_f64;++    // Path state: a list of subpaths, each a list of device-space points, plus+    // the current point in *user* space for bezier control-point ops.+    let mut subpaths: Vec<Vec<(f64, f64)>> = Vec::new();+    let mut cur_user: (f64, f64) = (0.0, 0.0);+    let mut start_user: (f64, f64) = (0.0, 0.0);++    let dev = |gs: &GraphicsState, x: f64, y: f64| transform(&gs.ctm, x, y);++    for op in ops {+        let o = &op.operands;+        match op.operator.as_str() {+            // Graphics state stack.+            "q" => stack.push(gs.clone()),+            "Q" => {+                if let Some(s) = stack.pop() {+                    gs = s;+                }+            }+            "cm" => {+                if let Some(m) = read_matrix(o) {+                    gs.ctm = mat_mul(&m, &gs.ctm);+                }+            }+            "w" => {+                if let Some(v) = o.first().and_then(num) {+                    gs.line_width = v;+                }+            }+            "d" => {+                if let Some(Object::Array(arr)) = o.first() {+                    gs.dash = arr.iter().filter_map(num).collect();+                }+                gs.dash_phase = o.get(1).and_then(num).unwrap_or(0.0);+            }++            // Path construction.+            "m" => {+                if let (Some(x), Some(y)) = (o.first().and_then(num), o.get(1).and_then(num)) {+                    cur_user = (x, y);+                    start_user = (x, y);+                    subpaths.push(vec![dev(&gs, x, y)]);+                }+            }+            "l" => {+                if let (Some(x), Some(y)) = (o.first().and_then(num), o.get(1).and_then(num)) {+                    cur_user = (x, y);+                    if let Some(sp) = subpaths.last_mut() {+                        sp.push(dev(&gs, x, y));+                    } else {+                        subpaths.push(vec![dev(&gs, x, y)]);+                    }+                }+            }+            "c" | "v" | "y" => {+                let nums: Vec<f64> = o.iter().filter_map(num).collect();+                let (p1, p2, p3) = match op.operator.as_str() {+                    "c" if nums.len() == 6 => (+                        (nums[0], nums[1]),+                        (nums[2], nums[3]),+                        (nums[4], nums[5]),+                    ),+                    "v" if nums.len() == 4 => {+                        (cur_user, (nums[0], nums[1]), (nums[2], nums[3]))+                    }+                    "y" if nums.len() == 4 => {+                        ((nums[0], nums[1]), (nums[2], nums[3]), (nums[2], nums[3]))+                    }+                    _ => continue,+                };+                let p0 = cur_user;+                for step in 1..=BEZIER_STEPS {+                    let t = step as f64 / BEZIER_STEPS as f64;+                    let (bx, by) = cubic_bezier(p0, p1, p2, p3, t);+                    if let Some(sp) = subpaths.last_mut() {+                        sp.push(dev(&gs, bx, by));+                    }+                }+                cur_user = p3;+            }+            "re" => {+                let nums: Vec<f64> = o.iter().filter_map(num).collect();+                if nums.len() == 4 {+                    let (x, y, w, h) = (nums[0], nums[1], nums[2], nums[3]);+                    let rect = vec![+                        dev(&gs, x, y),+                        dev(&gs, x + w, y),+                        dev(&gs, x + w, y + h),+                        dev(&gs, x, y + h),+                        dev(&gs, x, y),+                    ];+                    subpaths.push(rect);+                    cur_user = (x, y);+                    start_user = (x, y);+                }+            }+            "h" => {+                if let Some(sp) = subpaths.last_mut() {+                    sp.push(dev(&gs, start_user.0, start_user.1));+                }+                cur_user = start_user;+            }++            // Path painting.+            "S" | "s" => {+                if op.operator == "s" {+                    if let Some(sp) = subpaths.last_mut() {+                        sp.push(dev(&gs, start_user.0, start_user.1));+                    }+                }+                emit_stroke(prims, &subpaths, &gs);+                subpaths.clear();+            }+            "f" | "F" | "f*" => {+                emit_fill(prims, &subpaths, gs.fill, op.operator == "f*");+                subpaths.clear();+            }+            "B" | "B*" | "b" | "b*" => {+                if op.operator.starts_with('b') {+                    if let Some(sp) = subpaths.last_mut() {+                        sp.push(dev(&gs, start_user.0, start_user.1));+                    }+                }+                emit_fill(prims, &subpaths, gs.fill, op.operator.ends_with('*'));+                emit_stroke(prims, &subpaths, &gs);+                subpaths.clear();+            }+            "n" => subpaths.clear(),++            // XObjects: image XObjects are rasterized; form XObjects are inlined+            // (interpreted with their own resources + Matrix), depth-limited.+            "Do" => {+                if let Some(Object::Name(name)) = o.first() {+                    if let Some(&id) = xobjects.get(name) {+                        if let Ok(Object::Stream(stream)) = doc.get_object(id) {+                            let subtype = stream+                                .dict+                                .get(b"Subtype")+                                .ok()+                                .and_then(|o| o.as_name().ok());+                            if subtype == Some(b"Image") {+                                if let Some(img) = extract_image(doc, stream, gs.fill) {+                                    prims.push(Prim::Image {+                                        ctm: gs.ctm,+                                        w: img.w,+                                        h: img.h,+                                        format: img.format,+                                        data: img.data,+                                    });+                                }+                            } else if subtype == Some(b"Form") && depth < 10 {+                                let form_matrix = stream+                                    .dict+                                    .get(b"Matrix")+                                    .ok()+                                    .and_then(read_matrix_obj)+                                    .unwrap_or(IDENTITY);+                                let form_res = stream+                                    .dict+                                    .get(b"Resources")+                                    .ok()+                                    .and_then(|o| deref(doc, o))+                                    .and_then(|o| o.as_dict().ok())+                                    .cloned();+                                if let Ok(bytes) = stream.decompressed_content() {+                                    if let Ok(sub) = Content::decode(&bytes) {+                                        let mut sub_gs = gs.clone();+                                        sub_gs.ctm = mat_mul(&form_matrix, &gs.ctm);+                                        let res_ref = form_res.as_ref().or(resources);+                                        interpret_content(+                                            doc,+                                            &sub.operations,+                                            res_ref,+                                            sub_gs,+                                            prims,+                                            depth + 1,+                                        );+                                    }+                                }+                            }+                        }+                    }+                }+            }++            // Color.+            "rg" => {+                let n: Vec<f64> = o.iter().filter_map(num).collect();+                if n.len() == 3 {+                    gs.fill = rgb_to_argb(n[0], n[1], n[2]);+                }+            }+            "RG" => {+                let n: Vec<f64> = o.iter().filter_map(num).collect();+                if n.len() == 3 {+                    gs.stroke = rgb_to_argb(n[0], n[1], n[2]);+                }+            }+            "g" => {+                if let Some(v) = o.first().and_then(num) {+                    gs.fill = gray_to_argb(v);+                }+            }+            "G" => {+                if let Some(v) = o.first().and_then(num) {+                    gs.stroke = gray_to_argb(v);+                }+            }+            "k" => {+                let n: Vec<f64> = o.iter().filter_map(num).collect();+                if n.len() == 4 {+                    gs.fill = cmyk_to_argb(n[0], n[1], n[2], n[3]);+                }+            }+            "K" => {+                let n: Vec<f64> = o.iter().filter_map(num).collect();+                if n.len() == 4 {+                    gs.stroke = cmyk_to_argb(n[0], n[1], n[2], n[3]);+                }+            }++            // Text objects.+            "BT" => {+                text_matrix = IDENTITY;+                line_matrix = IDENTITY;+            }+            "ET" => {}+            "Tf" => {+                if let Some(Object::Name(name)) = o.first() {+                    gs.font_key = name.clone();+                }+                if let Some(sz) = o.get(1).and_then(num) {+                    gs.font_size = sz;+                }+            }+            "TL" => {+                if let Some(v) = o.first().and_then(num) {+                    leading = v;+                }+            }+            "Tc" => {+                if let Some(v) = o.first().and_then(num) {+                    gs.char_spacing = v;+                }+            }+            "Tw" => {+                if let Some(v) = o.first().and_then(num) {+                    gs.word_spacing = v;+                }+            }+            "Tz" => {+                if let Some(v) = o.first().and_then(num) {+                    gs.h_scale = v / 100.0;+                }+            }+            "Ts" => {+                if let Some(v) = o.first().and_then(num) {+                    gs.rise = v;+                }+            }+            "Tr" => {+                if let Some(v) = o.first().and_then(num) {+                    gs.render_mode = v as i64;+                }+            }+            "Td" => {+                if let (Some(tx), Some(ty)) = (o.first().and_then(num), o.get(1).and_then(num)) {+                    line_matrix = mat_mul(&translate(tx, ty), &line_matrix);+                    text_matrix = line_matrix;+                }+            }+            "TD" => {+                if let (Some(tx), Some(ty)) = (o.first().and_then(num), o.get(1).and_then(num)) {+                    leading = -ty;+                    line_matrix = mat_mul(&translate(tx, ty), &line_matrix);+                    text_matrix = line_matrix;+                }+            }+            "Tm" => {+                if let Some(m) = read_matrix(o) {+                    line_matrix = m;+                    text_matrix = m;+                }+            }+            "T*" => {+                line_matrix = mat_mul(&translate(0.0, -leading), &line_matrix);+                text_matrix = line_matrix;+            }+            "Tj" => {+                if let Some(Object::String(bytes, _)) = o.first() {+                    let adv = show_string(prims, &gs, &fonts, &text_matrix, bytes);+                    text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+                }+            }+            "'" => {+                line_matrix = mat_mul(&translate(0.0, -leading), &line_matrix);+                text_matrix = line_matrix;+                if let Some(Object::String(bytes, _)) = o.first() {+                    let adv = show_string(prims, &gs, &fonts, &text_matrix, bytes);+                    text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+                }+            }+            "\"" => {+                if let Some(aw) = o.first().and_then(num) {+                    gs.word_spacing = aw;+                }+                if let Some(ac) = o.get(1).and_then(num) {+                    gs.char_spacing = ac;+                }+                line_matrix = mat_mul(&translate(0.0, -leading), &line_matrix);+                text_matrix = line_matrix;+                if let Some(Object::String(bytes, _)) = o.get(2) {+                    let adv = show_string(prims, &gs, &fonts, &text_matrix, bytes);+                    text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+                }+            }+            "TJ" => {+                if let Some(Object::Array(arr)) = o.first() {+                    for el in arr {+                        match el {+                            Object::String(bytes, _) => {+                                let adv =+                                    show_string(prims, &gs, &fonts, &text_matrix, bytes);+                                text_matrix = mat_mul(&translate(adv, 0.0), &text_matrix);+                            }+                            Object::Integer(_) | Object::Real(_) => {+                                // Kerning adjustment: tx = -n/1000 * Tfs * Th.+                                let n = num(el).unwrap_or(0.0);+                                let tx = -n / 1000.0 * gs.font_size * gs.h_scale;+                                text_matrix = mat_mul(&translate(tx, 0.0), &text_matrix);+                            }+                            _ => {}+                        }+                    }+                }+            }++            _ => {}+        }+    }+}++fn read_matrix(operands: &[Object]) -> Option<Mat> {+    let n: Vec<f64> = operands.iter().filter_map(num).collect();+    if n.len() == 6 {+        Some([n[0], n[1], n[2], n[3], n[4], n[5]])+    } else {+        None+    }+}++/// Read a 6-element matrix from an array object.+fn read_matrix_obj(obj: &Object) -> Option<Mat> {+    match obj {+        Object::Array(a) => read_matrix(a),+        _ => None,+    }+}++/// Read a 4-number array (e.g. `/Rect`, `/BBox`) resolving references.+fn read_rect(doc: &Document, obj: &Object) -> Option<[f64; 4]> {+    let arr = deref(doc, obj)?.as_array().ok()?;+    if arr.len() != 4 {+        return None;+    }+    let mut out = [0.0; 4];+    for (i, v) in arr.iter().enumerate() {+        out[i] = deref(doc, v).and_then(num)?;+    }+    Some(out)+}++/// The matrix mapping an appearance stream's form space to page space, fitting+/// the (Matrix-transformed) `/BBox` into the annotation `/Rect` (PDF 12.5.5).+fn appearance_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> Mat {+    let corners = [+        (bbox[0], bbox[1]),+        (bbox[2], bbox[1]),+        (bbox[2], bbox[3]),+        (bbox[0], bbox[3]),+    ];+    let mut tx0 = f64::INFINITY;+    let mut ty0 = f64::INFINITY;+    let mut tx1 = f64::NEG_INFINITY;+    let mut ty1 = f64::NEG_INFINITY;+    for (x, y) in corners {+        let (px, py) = transform(&matrix, x, y);+        tx0 = tx0.min(px);+        ty0 = ty0.min(py);+        tx1 = tx1.max(px);+        ty1 = ty1.max(py);+    }+    let rx0 = rect[0].min(rect[2]);+    let ry0 = rect[1].min(rect[3]);+    let rx1 = rect[0].max(rect[2]);+    let ry1 = rect[1].max(rect[3]);+    let bw = tx1 - tx0;+    let bh = ty1 - ty0;+    let sx = if bw.abs() > 1e-6 { (rx1 - rx0) / bw } else { 1.0 };+    let sy = if bh.abs() > 1e-6 { (ry1 - ry0) / bh } else { 1.0 };+    let fit = [sx, 0.0, 0.0, sy, rx0 - sx * tx0, ry0 - sy * ty0];+    mat_mul(&matrix, &fit)+}++/// Render each visible page annotation's normal appearance (`/AP /N`) into+/// primitives, mapping the appearance BBox into the annotation Rect.+fn render_annotations(doc: &Document, page_id: ObjectId, prims: &mut Vec<Prim>) {+    let annots = 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.clone(),+        _ => return,+    };++    for a in &annots {+        let dict = match deref(doc, a).and_then(|o| o.as_dict().ok()) {+            Some(d) => d,+            None => continue,+        };+        // Skip Hidden (bit 2) and NoView (bit 6) annotations.+        let flags = dict.get(b"F").ok().and_then(num).unwrap_or(0.0) as i64;+        if flags & 0b10 != 0 || flags & 0b10_0000 != 0 {+            continue;+        }+        render_annotation(doc, dict, prims);+    }+}++fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, prims: &mut Vec<Prim>) {+    let rect = match dict.get(b"Rect").ok().and_then(|o| read_rect(doc, o)) {+        Some(r) => r,+        None => return,+    };++    // Resolve the normal appearance: /AP /N is either a stream or a subdictionary+    // of appearance states selected by /AS.+    let ap = match dict.get(b"AP").ok().and_then(|o| deref(doc, o)) {+        Some(Object::Dictionary(d)) => d,+        _ => return,+    };+    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());+            let picked = as_name+                .and_then(|n| states.get(n).ok())+                .or_else(|| states.iter().next().map(|(_, v)| v));+            match picked.and_then(|o| deref(doc, o)) {+                Some(Object::Stream(s)) => s,+                _ => return,+            }+        }+        _ => return,+    };++    let bbox = normal+        .dict+        .get(b"BBox")+        .ok()+        .and_then(|o| read_rect(doc, o))+        .unwrap_or([0.0, 0.0, 1.0, 1.0]);+    let matrix = normal+        .dict+        .get(b"Matrix")+        .ok()+        .and_then(read_matrix_obj)+        .unwrap_or(IDENTITY);+    let res = normal+        .dict+        .get(b"Resources")+        .ok()+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_dict().ok())+        .cloned();++    let bytes = match normal.decompressed_content() {+        Ok(b) => b,+        Err(_) => return,+    };+    let ops = match Content::decode(&bytes) {+        Ok(c) => c.operations,+        Err(_) => return,+    };++    let mut gs = GraphicsState::default();+    gs.ctm = appearance_matrix(rect, bbox, matrix);+    interpret_content(doc, &ops, res.as_ref(), gs, prims, 1);+}++// ---------------------------------------------------------------------------+// Editing: annotations, form filling, and save (lopdf write-back)+// ---------------------------------------------------------------------------+//+// The "safe" viewer edits via an overlay model written back through lopdf: new+// content is added as annotations (with generated appearance streams so other+// viewers render them) or as AcroForm field values. Existing body-text glyph+// runs are not editable in this architecture.++/// Encode a lopdf `ObjectId` (num, gen) into a single `i64` handle for Kotlin.+fn encode_id(id: ObjectId) -> i64 {+    ((id.0 as i64) << 16) | (id.1 as i64)+}++fn decode_id(v: i64) -> ObjectId {+    (((v >> 16) & 0xFFFF_FFFF) as u32, (v & 0xFFFF) as u16)+}++fn nth_page_id(doc: &Document, index: i32) -> Option<ObjectId> {+    doc.get_pages().get(&((index as u32) + 1)).copied()+}++fn name_obj(s: &str) -> Object {+    Object::Name(s.as_bytes().to_vec())+}++fn rect_obj(r: [f64; 4]) -> Object {+    Object::Array(vec![r[0].into(), r[1].into(), r[2].into(), r[3].into()])+}++fn argb_rgb(argb: u32) -> (f64, f64, f64) {+    (+        ((argb >> 16) & 0xFF) as f64 / 255.0,+        ((argb >> 8) & 0xFF) as f64 / 255.0,+        (argb & 0xFF) as f64 / 255.0,+    )+}++fn normalize_rect(r: [f64; 4]) -> [f64; 4] {+    [+        r[0].min(r[2]),+        r[1].min(r[3]),+        r[0].max(r[2]),+        r[1].max(r[3]),+    ]+}++/// Escape a string for use inside a PDF content-stream literal `(...)`.+fn escape_pdf_literal(s: &str) -> String {+    let mut out = String::with_capacity(s.len());+    for c in s.chars() {+        match c {+            '(' => out.push_str("\\("),+            ')' => out.push_str("\\)"),+            '\\' => out.push_str("\\\\"),+            _ => out.push(c),+        }+    }+    out+}++/// Decode a PDF text string (`/Contents`, `/V`): UTF-16BE if it has a BOM, else+/// treated as Latin-1 (a superset-safe approximation of PDFDocEncoding).+fn decode_pdf_text(bytes: &[u8]) -> String {+    if bytes.len() >= 2 && bytes[0] == 0xFE && bytes[1] == 0xFF {+        let units: Vec<u16> = bytes[2..]+            .chunks(2)+            .map(|c| ((c[0] as u16) << 8) | *c.get(1).unwrap_or(&0) as u16)+            .collect();+        String::from_utf16_lossy(&units)+    } else {+        bytes.iter().map(|&b| b as char).collect()+    }+}++/// Resources dictionary with a single Helvetica font under `/F1`.+fn helvetica_resources() -> Dictionary {+    let mut font = Dictionary::new();+    font.set("Type", name_obj("Font"));+    font.set("Subtype", name_obj("Type1"));+    font.set("BaseFont", name_obj("Helvetica"));+    let mut fonts = Dictionary::new();+    fonts.set("F1", Object::Dictionary(font));+    let mut res = Dictionary::new();+    res.set("Font", Object::Dictionary(fonts));+    res+}++/// Build a Form XObject appearance stream with the given BBox size, content and+/// resources, returning its object id.+fn make_appearance(doc: &mut Document, w: f64, h: f64, content: Vec<u8>, res: Dictionary) -> ObjectId {+    let mut d = Dictionary::new();+    d.set("Type", name_obj("XObject"));+    d.set("Subtype", name_obj("Form"));+    d.set("FormType", 1);+    d.set(+        "BBox",+        Object::Array(vec![0.into(), 0.into(), w.into(), h.into()]),+    );+    d.set("Resources", Object::Dictionary(res));+    doc.add_object(Stream::new(d, content))+}++/// Append an annotation reference to a page's `/Annots` array (creating it if+/// needed), handling both inline and indirect arrays.+fn append_annot(doc: &mut Document, page_id: ObjectId, annot_id: ObjectId) {+    let indirect = match doc.get_dictionary(page_id).ok().and_then(|d| d.get(b"Annots").ok()) {+        Some(Object::Reference(id)) => Some(*id),+        _ => None,+    };+    if let Some(arr_id) = indirect {+        if let Ok(Object::Array(a)) = doc.get_object_mut(arr_id) {+            a.push(Object::Reference(annot_id));+        }+        return;+    }+    if let Ok(page) = doc.get_dictionary_mut(page_id) {+        match page.get_mut(b"Annots") {+            Ok(Object::Array(a)) => a.push(Object::Reference(annot_id)),+            _ => page.set("Annots", Object::Array(vec![Object::Reference(annot_id)])),+        }+    }+}++/// Attach `Rect` + `AP /N` to an annotation dict.+fn set_appearance(annot: &mut Dictionary, rect: [f64; 4], ap_id: ObjectId) {+    annot.set("Rect", rect_obj(rect));+    let mut ap = Dictionary::new();+    ap.set("N", Object::Reference(ap_id));+    annot.set("AP", Object::Dictionary(ap));+}++fn add_annotation_object(doc: &mut Document, page_index: i32, annot: Dictionary) -> Option<i64> {+    let page_id = nth_page_id(doc, page_index)?;+    let annot_id = doc.add_object(annot);+    append_annot(doc, page_id, annot_id);+    Some(encode_id(annot_id))+}++/// Content stream drawing a (possibly multi-line) text block in a `w`×`h` box.+fn free_text_content(w: f64, h: f64, text: &str, argb: u32, size: f64) -> Vec<u8> {+    let (r, g, b) = argb_rgb(argb);+    let leading = size * 1.2;+    let mut c = format!(+        "q {r:.3} {g:.3} {b:.3} rg BT /F1 {size} Tf {leading} TL {x} {y} Td",+        x = 2.0,+        y = h - size,+    );+    let _ = w;+    for line in text.split('\n') {+        c.push_str(&format!(" ({}) Tj T*", escape_pdf_literal(line)));+    }+    c.push_str(" ET Q");+    c.into_bytes()+}++fn add_free_text(+    handle: i64,+    page_index: i32,+    rect: [f64; 4],+    argb: u32,+    size: f64,+    text: &str,+) -> Option<i64> {+    let mut reg = registry().lock().unwrap();+    let doc = reg.get_mut(&handle)?;+    let r = normalize_rect(rect);+    let (w, h) = (r[2] - r[0], r[3] - r[1]);+    let content = free_text_content(w, h, text, argb, size);+    let ap_id = make_appearance(doc, w, h, content, helvetica_resources());+    let (cr, cg, cb) = argb_rgb(argb);++    let mut annot = Dictionary::new();+    annot.set("Type", name_obj("Annot"));+    annot.set("Subtype", name_obj("FreeText"));+    annot.set("Contents", Object::string_literal(text));+    annot.set(+        "DA",+        Object::string_literal(format!("{cr:.3} {cg:.3} {cb:.3} rg /F1 {size} Tf")),+    );+    annot.set("C", Object::Array(vec![cr.into(), cg.into(), cb.into()]));+    set_appearance(&mut annot, r, ap_id);+    add_annotation_object(doc, page_index, annot)+}++fn add_highlight(handle: i64, page_index: i32, rect: [f64; 4], argb: u32) -> Option<i64> {+    let mut reg = registry().lock().unwrap();+    let doc = reg.get_mut(&handle)?;+    let r = normalize_rect(rect);+    let (w, h) = (r[2] - r[0], r[3] - r[1]);+    let (cr, cg, cb) = argb_rgb(argb);+    // Multiply-blended translucent fill so underlying text shows through.+    let content = format!(+        "q /GS1 gs {cr:.3} {cg:.3} {cb:.3} rg 0 0 {w} {h} re f Q"+    )+    .into_bytes();+    let mut gs = Dictionary::new();+    gs.set("Type", name_obj("ExtGState"));+    gs.set("ca", Object::Real(0.4));+    gs.set("BM", name_obj("Multiply"));+    let mut gss = Dictionary::new();+    gss.set("GS1", Object::Dictionary(gs));+    let mut res = Dictionary::new();+    res.set("ExtGState", Object::Dictionary(gss));+    let ap_id = make_appearance(doc, w, h, content, res);++    let mut annot = Dictionary::new();+    annot.set("Type", name_obj("Annot"));+    annot.set("Subtype", name_obj("Highlight"));+    annot.set(+        "QuadPoints",+        Object::Array(vec![+            r[0].into(), r[3].into(), r[2].into(), r[3].into(),+            r[0].into(), r[1].into(), r[2].into(), r[1].into(),+        ]),+    );+    annot.set("C", Object::Array(vec![cr.into(), cg.into(), cb.into()]));+    set_appearance(&mut annot, r, ap_id);+    add_annotation_object(doc, page_index, annot)+}++fn add_square(+    handle: i64,+    page_index: i32,+    rect: [f64; 4],+    argb: u32,+    line_width: f64,+) -> Option<i64> {+    let mut reg = registry().lock().unwrap();+    let doc = reg.get_mut(&handle)?;+    let r = normalize_rect(rect);+    let (w, h) = (r[2] - r[0], r[3] - r[1]);+    let (cr, cg, cb) = argb_rgb(argb);+    let lw = line_width.max(0.5);+    let content = format!(+        "q {lw} w {cr:.3} {cg:.3} {cb:.3} RG {x} {y} {rw} {rh} re S Q",+        x = lw / 2.0,+        y = lw / 2.0,+        rw = w - lw,+        rh = h - lw,+    )+    .into_bytes();+    let ap_id = make_appearance(doc, w, h, content, Dictionary::new());++    let mut annot = Dictionary::new();+    annot.set("Type", name_obj("Annot"));+    annot.set("Subtype", name_obj("Square"));+    annot.set("C", Object::Array(vec![cr.into(), cg.into(), cb.into()]));+    let mut bs = Dictionary::new();+    bs.set("W", Object::Real(lw as f32));+    annot.set("BS", Object::Dictionary(bs));+    set_appearance(&mut annot, r, ap_id);+    add_annotation_object(doc, page_index, annot)+}++/// `points`: flat page-space x,y pairs of a single ink stroke.+fn add_ink(+    handle: i64,+    page_index: i32,+    argb: u32,+    line_width: f64,+    points: &[f32],+) -> Option<i64> {+    if points.len() < 4 {+        return None;+    }+    let mut reg = registry().lock().unwrap();+    let doc = reg.get_mut(&handle)?;+    let (cr, cg, cb) = argb_rgb(argb);+    let lw = line_width.max(0.5);++    let mut minx = f64::INFINITY;+    let mut miny = f64::INFINITY;+    let mut maxx = f64::NEG_INFINITY;+    let mut maxy = f64::NEG_INFINITY;+    let mut i = 0;+    while i + 1 < points.len() {+        let (x, y) = (points[i] as f64, points[i + 1] as f64);+        minx = minx.min(x);+        miny = miny.min(y);+        maxx = maxx.max(x);+        maxy = maxy.max(y);+        i += 2;+    }+    let pad = lw + 2.0;+    let rect = [minx - pad, miny - pad, maxx + pad, maxy + pad];+    let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]);++    // Appearance content in BBox space (origin at rect min).+    let mut c = format!("q {lw} w {cr:.3} {cg:.3} {cb:.3} RG ");+    let mut ink = Vec::new();+    let mut j = 0;+    let mut first = true;+    while j + 1 < points.len() {+        let px = points[j] as f64;+        let py = points[j + 1] as f64;+        ink.push(px.into());+        ink.push(py.into());+        let (lx, ly) = (px - rect[0], py - rect[1]);+        if first {+            c.push_str(&format!("{lx:.2} {ly:.2} m "));+            first = false;+        } else {+            c.push_str(&format!("{lx:.2} {ly:.2} l "));+        }+        j += 2;+    }+    c.push_str("S Q");+    let ap_id = make_appearance(doc, w, h, c.into_bytes(), Dictionary::new());++    let mut annot = Dictionary::new();+    annot.set("Type", name_obj("Annot"));+    annot.set("Subtype", name_obj("Ink"));+    annot.set("InkList", Object::Array(vec![Object::Array(ink)]));+    annot.set("C", Object::Array(vec![cr.into(), cg.into(), cb.into()]));+    let mut bs = Dictionary::new();+    bs.set("W", Object::Real(lw as f32));+    annot.set("BS", Object::Dictionary(bs));+    set_appearance(&mut annot, rect, ap_id);+    add_annotation_object(doc, page_index, annot)+}++/// `jpeg`: raw JPEG bytes for a Stamp annotation image.+fn add_stamp(+    handle: i64,+    page_index: i32,+    rect: [f64; 4],+    img_w: u32,+    img_h: u32,+    jpeg: &[u8],+) -> Option<i64> {+    let mut reg = registry().lock().unwrap();+    let doc = reg.get_mut(&handle)?;+    let r = normalize_rect(rect);+    let (w, h) = (r[2] - r[0], r[3] - r[1]);++    let mut img_dict = Dictionary::new();+    img_dict.set("Type", name_obj("XObject"));+    img_dict.set("Subtype", name_obj("Image"));+    img_dict.set("Width", Object::Integer(img_w as i64));+    img_dict.set("Height", Object::Integer(img_h as i64));+    img_dict.set("BitsPerComponent", Object::Integer(8));+    img_dict.set("ColorSpace", name_obj("DeviceRGB"));+    img_dict.set("Filter", name_obj("DCTDecode"));+    let img_id = doc.add_object(Stream::new(img_dict, jpeg.to_vec()));++    let mut xobj = Dictionary::new();+    xobj.set("Im0", Object::Reference(img_id));+    let mut res = Dictionary::new();+    res.set("XObject", Object::Dictionary(xobj));+    let content = format!("q {w} 0 0 {h} 0 0 cm /Im0 Do Q").into_bytes();+    let ap_id = make_appearance(doc, w, h, content, res);++    let mut annot = Dictionary::new();+    annot.set("Type", name_obj("Annot"));+    annot.set("Subtype", name_obj("Stamp"));+    set_appearance(&mut annot, r, ap_id);+    add_annotation_object(doc, page_index, annot)+}++fn update_annotation_rect(handle: i64, annot_id: i64, rect: [f64; 4]) -> bool {+    let mut reg = registry().lock().unwrap();+    let doc = match reg.get_mut(&handle) {+        Some(d) => d,+        None => return false,+    };+    let id = decode_id(annot_id);+    if let Ok(dict) = doc.get_dictionary_mut(id) {+        dict.set("Rect", rect_obj(normalize_rect(rect)));+        true+    } else {+        false+    }+}++fn update_free_text(handle: i64, annot_id: i64, text: &str) -> bool {+    let mut reg = registry().lock().unwrap();+    let doc = match reg.get_mut(&handle) {+        Some(d) => d,+        None => return false,+    };+    let id = decode_id(annot_id);+    // Read existing rect / color / size.+    let (rect, argb, size) = {+        let dict = match doc.get_dictionary(id) {+            Ok(d) => d,+            Err(_) => return false,+        };+        let rect = dict+            .get(b"Rect")+            .ok()+            .and_then(|o| read_rect(doc, o))+            .map(normalize_rect)+            .unwrap_or([0.0, 0.0, 100.0, 20.0]);+        let argb = dict+            .get(b"C")+            .ok()+            .and_then(|o| o.as_array().ok())+            .filter(|a| a.len() == 3)+            .map(|a| {+                let r = a[0].as_float().unwrap_or(0.0);+                let g = a[1].as_float().unwrap_or(0.0);+                let b = a[2].as_float().unwrap_or(0.0);+                rgb_to_argb(r as f64, g as f64, b as f64)+            })+            .unwrap_or(0xFF00_0000);+        let size = dict+            .get(b"DA")+            .ok()+            .and_then(|o| o.as_str().ok())+            .and_then(|s| parse_da_size(s))+            .unwrap_or(12.0);+        (rect, argb, size)+    };+    let (w, h) = (rect[2] - rect[0], rect[3] - rect[1]);+    let content = free_text_content(w, h, text, argb, size);+    let ap_id = make_appearance(doc, w, h, content, helvetica_resources());+    if let Ok(dict) = doc.get_dictionary_mut(id) {+        dict.set("Contents", Object::string_literal(text));+        let mut ap = Dictionary::new();+        ap.set("N", Object::Reference(ap_id));+        dict.set("AP", Object::Dictionary(ap));+        true+    } else {+        false+    }+}++/// Extract the font size preceding `Tf` in a `/DA` string.+fn parse_da_size(da: &[u8]) -> Option<f64> {+    let s = String::from_utf8_lossy(da);+    let toks: Vec<&str> = s.split_whitespace().collect();+    let tf = toks.iter().position(|t| *t == "Tf")?;+    if tf == 0 {+        return None;+    }+    toks[tf - 1].parse::<f64>().ok()+}++fn delete_annotation(handle: i64, page_index: i32, annot_id: i64) -> bool {+    let mut reg = registry().lock().unwrap();+    let doc = match reg.get_mut(&handle) {+        Some(d) => d,+        None => return false,+    };+    let id = decode_id(annot_id);+    let page_id = match nth_page_id(doc, page_index) {+        Some(p) => p,+        None => return false,+    };+    // Remove the reference from the page's /Annots (inline or indirect).+    let indirect = match doc.get_dictionary(page_id).ok().and_then(|d| d.get(b"Annots").ok()) {+        Some(Object::Reference(aid)) => Some(*aid),+        _ => None,+    };+    let removed = if let Some(arr_id) = indirect {+        if let Ok(Object::Array(a)) = doc.get_object_mut(arr_id) {+            let before = a.len();+            a.retain(|o| o.as_reference().ok() != Some(id));+            before != a.len()+        } else {+            false+        }+    } else if let Ok(page) = doc.get_dictionary_mut(page_id) {+        if let Ok(Object::Array(a)) = page.get_mut(b"Annots") {+            let before = a.len();+            a.retain(|o| o.as_reference().ok() != Some(id));+            before != a.len()+        } else {+            false+        }+    } else {+        false+    };+    doc.objects.remove(&id);+    removed+}++// --- Serialized listing for the UI ---------------------------------------++fn subtype_code(subtype: &[u8]) -> u8 {+    match subtype {+        b"FreeText" => 1,+        b"Highlight" => 2,+        b"Square" => 3,+        b"Ink" => 4,+        b"Stamp" => 5,+        b"Widget" => 6,+        b"Text" => 7,+        b"Line" => 8,+        _ => 0,+    }+}++fn annot_color(doc: &Document, dict: &Dictionary) -> u32 {+    dict.get(b"C")+        .ok()+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_array().ok())+        .filter(|a| a.len() == 3)+        .map(|a| {+            rgb_to_argb(+                a[0].as_float().unwrap_or(0.0) as f64,+                a[1].as_float().unwrap_or(0.0) as f64,+                a[2].as_float().unwrap_or(0.0) as f64,+            )+        })+        .unwrap_or(0xFF00_0000)+}++fn list_annotations(handle: i64, page_index: i32) -> Option<Vec<u8>> {+    let reg = registry().lock().unwrap();+    let doc = reg.get(&handle)?;+    let page_id = nth_page_id(doc, page_index)?;++    let mut records: Vec<(i64, u8, [f64; 4], u32, String)> = Vec::new();+    if let Some(Object::Array(annots)) = doc+        .get_dictionary(page_id)+        .ok()+        .and_then(|d| d.get(b"Annots").ok())+        .and_then(|o| deref(doc, o))+    {+        for a in annots {+            let id = match a.as_reference() {+                Ok(id) => id,+                Err(_) => continue,+            };+            let dict = match doc.get_dictionary(id) {+                Ok(d) => d,+                Err(_) => continue,+            };+            let subtype = dict.get(b"Subtype").ok().and_then(|o| o.as_name().ok());+            let code = subtype.map(subtype_code).unwrap_or(0);+            let rect = match dict.get(b"Rect").ok().and_then(|o| read_rect(doc, o)) {+                Some(r) => normalize_rect(r),+                None => continue,+            };+            let color = annot_color(doc, dict);+            let contents = dict+                .get(b"Contents")+                .ok()+                .and_then(|o| o.as_str().ok())+                .map(decode_pdf_text)+                .unwrap_or_default();+            records.push((encode_id(id), code, rect, color, contents));+        }+    }++    let mut buf = Vec::new();+    buf.extend_from_slice(&(records.len() as u32).to_le_bytes());+    for (id, code, rect, color, contents) in records {+        buf.extend_from_slice(&id.to_le_bytes());+        buf.push(code);+        for v in rect {+            buf.extend_from_slice(&(v as f32).to_le_bytes());+        }+        buf.extend_from_slice(&color.to_le_bytes());+        let b = contents.as_bytes();+        let len = b.len().min(u16::MAX as usize);+        buf.extend_from_slice(&(len as u16).to_le_bytes());+        buf.extend_from_slice(&b[..len]);+    }+    Some(buf)+}++/// Field type + name inherited through the widget's `/Parent` chain.+fn field_attr<'a>(doc: &'a Document, mut id: ObjectId, key: &[u8]) -> Option<&'a Object> {+    for _ in 0..16 {+        let dict = doc.get_dictionary(id).ok()?;+        if let Ok(v) = dict.get(key) {+            return Some(v);+        }+        id = dict.get(b"Parent").ok().and_then(|o| o.as_reference().ok())?;+    }+    None+}++fn list_form_fields(handle: i64, page_index: i32) -> Option<Vec<u8>> {+    let reg = registry().lock().unwrap();+    let doc = reg.get(&handle)?;+    let page_id = nth_page_id(doc, page_index)?;++    // (widgetId, typeCode, rect, name, value, checked)+    let mut fields: Vec<(i64, u8, [f64; 4], String, String, u8)> = Vec::new();+    if let Some(Object::Array(annots)) = doc+        .get_dictionary(page_id)+        .ok()+        .and_then(|d| d.get(b"Annots").ok())+        .and_then(|o| deref(doc, o))+    {+        for a in annots {+            let id = match a.as_reference() {+                Ok(id) => id,+                Err(_) => continue,+            };+            let dict = match doc.get_dictionary(id) {+                Ok(d) => d,+                Err(_) => continue,+            };+            let is_widget = dict.get(b"Subtype").ok().and_then(|o| o.as_name().ok())+                == Some(b"Widget".as_ref());+            let ft = field_attr(doc, id, b"FT").and_then(|o| o.as_name().ok());+            if !is_widget || ft.is_none() {+                continue;+            }+            let ft = ft.unwrap();+            let type_code = match ft {+                b"Tx" => 0u8,+                b"Btn" => 1u8,+                b"Ch" => 2u8,+                _ => 3u8,+            };+            let rect = match dict.get(b"Rect").ok().and_then(|o| read_rect(doc, o)) {+                Some(r) => normalize_rect(r),+                None => continue,+            };+            let name = field_attr(doc, id, b"T")+                .and_then(|o| o.as_str().ok())+                .map(decode_pdf_text)+                .unwrap_or_default();+            let value = field_attr(doc, id, b"V")+                .map(|o| match o {+                    Object::String(s, _) => decode_pdf_text(s),+                    Object::Name(n) => String::from_utf8_lossy(n).into_owned(),+                    _ => String::new(),+                })+                .unwrap_or_default();+            let checked = if type_code == 1 {+                let as_state = dict.get(b"AS").ok().and_then(|o| o.as_name().ok());+                let on = as_state.map(|s| s != b"Off").unwrap_or(false)+                    || (!value.is_empty() && value != "Off");+                on as u8+            } else {+                0+            };+            fields.push((encode_id(id), type_code, rect, name, value, checked));+        }+    }++    let mut buf = Vec::new();+    buf.extend_from_slice(&(fields.len() as u32).to_le_bytes());+    for (id, tc, rect, name, value, checked) in fields {+        buf.extend_from_slice(&id.to_le_bytes());+        buf.push(tc);+        for v in rect {+            buf.extend_from_slice(&(v as f32).to_le_bytes());+        }+        for s in [&name, &value] {+            let b = s.as_bytes();+            let len = b.len().min(u16::MAX as usize);+            buf.extend_from_slice(&(len as u16).to_le_bytes());+            buf.extend_from_slice(&b[..len]);+        }+        buf.push(checked);+    }+    Some(buf)+}++/// Set the AcroForm `/NeedAppearances` flag so conformant viewers regenerate+/// field appearances after a value change.+fn set_need_appearances(doc: &mut Document) {+    let acro_id = doc+        .catalog()+        .ok()+        .and_then(|c| c.get(b"AcroForm").ok())+        .and_then(|o| o.as_reference().ok());+    if let Some(id) = acro_id {+        if let Ok(af) = doc.get_dictionary_mut(id) {+            af.set("NeedAppearances", Object::Boolean(true));+        }+    }+}++fn set_text_field(handle: i64, widget_id: i64, value: &str) -> bool {+    let mut reg = registry().lock().unwrap();+    let doc = match reg.get_mut(&handle) {+        Some(d) => d,+        None => return false,+    };+    let id = decode_id(widget_id);+    let rect = doc+        .get_dictionary(id)+        .ok()+        .and_then(|d| d.get(b"Rect").ok())+        .and_then(|o| read_rect(doc, o))+        .map(normalize_rect);+    // Regenerate a simple left-aligned, vertically-centered appearance.+    let ap_id = rect.map(|r| {+        let (w, h) = (r[2] - r[0], r[3] - r[1]);+        let size = (h - 4.0).clamp(6.0, 14.0);+        let content = format!(+            "q 0 0 0 rg BT /F1 {size} Tf 2 {y:.2} Td ({}) Tj ET Q",+            escape_pdf_literal(value),+            y = (h - size) / 2.0,+        )+        .into_bytes();+        make_appearance(doc, w, h, content, helvetica_resources())+    });++    if let Ok(dict) = doc.get_dictionary_mut(id) {+        dict.set("V", Object::string_literal(value));+        if let Some(ap_id) = ap_id {+            let mut ap = Dictionary::new();+            ap.set("N", Object::Reference(ap_id));+            dict.set("AP", Object::Dictionary(ap));+        }+    } else {+        return false;+    }+    set_need_appearances(doc);+    true+}++fn set_checkbox(handle: i64, widget_id: i64, on: bool) -> bool {+    let mut reg = registry().lock().unwrap();+    let doc = match reg.get_mut(&handle) {+        Some(d) => d,+        None => return false,+    };+    let id = decode_id(widget_id);+    // Determine the "on" state name from the widget's /AP /N sub-dictionary.+    let on_state = doc+        .get_dictionary(id)+        .ok()+        .and_then(|d| d.get(b"AP").ok())+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_dict().ok())+        .and_then(|ap| ap.get(b"N").ok())+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_dict().ok())+        .and_then(|states| {+            states+                .iter()+                .map(|(k, _)| k.clone())+                .find(|k| k.as_slice() != b"Off")+        })+        .unwrap_or_else(|| b"Yes".to_vec());++    let state = if on { on_state } else { b"Off".to_vec() };+    if let Ok(dict) = doc.get_dictionary_mut(id) {+        dict.set("AS", Object::Name(state.clone()));+        dict.set("V", Object::Name(state));+        true+    } else {+        false+    }+}++fn save_document(handle: i64) -> Option<Vec<u8>> {+    let mut reg = registry().lock().unwrap();+    let doc = reg.get_mut(&handle)?;+    let mut buf = Vec::new();+    doc.save_to(&mut buf).ok()?;+    Some(buf)+}++fn cubic_bezier(+    p0: (f64, f64),+    p1: (f64, f64),+    p2: (f64, f64),+    p3: (f64, f64),+    t: f64,+) -> (f64, f64) {+    let u = 1.0 - t;+    let w0 = u * u * u;+    let w1 = 3.0 * u * u * t;+    let w2 = 3.0 * u * t * t;+    let w3 = t * t * t;+    (+        w0 * p0.0 + w1 * p1.0 + w2 * p2.0 + w3 * p3.0,+        w0 * p0.1 + w1 * p1.1 + w2 * p2.1 + w3 * p3.1,+    )+}++fn emit_fill(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], argb: u32, even_odd: bool) {+    for sp in subpaths {+        if sp.len() >= 3 {+            prims.push(Prim::Fill {+                argb,+                even_odd,+                pts: sp.iter().map(|&(x, y)| (x as f32, y as f32)).collect(),+            });+        }+    }+}++fn emit_stroke(prims: &mut Vec<Prim>, subpaths: &[Vec<(f64, f64)>], gs: &GraphicsState) {+    // Approximate device-space scale via the CTM's average axis length.+    let ctm = &gs.ctm;+    let sx = (ctm[0] * ctm[0] + ctm[1] * ctm[1]).sqrt();+    let sy = (ctm[2] * ctm[2] + ctm[3] * ctm[3]).sqrt();+    let scale = (sx + sy) / 2.0;+    let width = (gs.line_width * scale) as f32;+    let dash: Vec<f32> = gs+        .dash+        .iter()+        .map(|d| (d * scale) as f32)+        .filter(|d| *d >= 0.0)+        .collect();+    // A valid dash needs at least two positive entries with a non-zero sum.+    let dash = if dash.len() >= 2 && dash.iter().sum::<f32>() > 0.0 {+        dash+    } else {+        Vec::new()+    };+    let dash_phase = (gs.dash_phase * scale) as f32;+    for sp in subpaths {+        if sp.len() >= 2 {+            prims.push(Prim::Stroke {+                argb: gs.stroke,+                width: width.max(0.1),+                dash: dash.clone(),+                dash_phase,+                pts: sp.iter().map(|&(x, y)| (x as f32, y as f32)).collect(),+            });+        }+    }+}++/// Emit a text primitive for `bytes` at the current text matrix (unless the+/// render mode is invisible/clip-only) and return the horizontal advance in+/// user-space units so the caller can step the text matrix.+fn show_string(+    prims: &mut Vec<Prim>,+    gs: &GraphicsState,+    fonts: &HashMap<Vec<u8>, FontInfo>,+    text_matrix: &Mat,+    bytes: &[u8],+) -> f64 {+    let fi = fonts.get(&gs.font_key);+    let tfs = gs.font_size;+    let advance = match fi {+        Some(fi) => fi.advance(bytes, tfs, gs.char_spacing, gs.word_spacing, gs.h_scale),+        // No font metrics: rough monospace-ish estimate keeps runs from stacking.+        None => bytes.len() as f64 * 0.5 * tfs * gs.h_scale,+    };++    // Modes 3 (invisible) and 7 (clip only) are not painted.+    if gs.render_mode == 3 || gs.render_mode == 7 || bytes.is_empty() {+        return advance;+    }++    let trm = mat_mul(text_matrix, &gs.ctm);+    // Origin includes text rise along the text-space y-axis.+    let (x, y) = transform(&trm, 0.0, gs.rise);+    let y_scale = (trm[2] * trm[2] + trm[3] * trm[3]).sqrt();+    let size = (tfs * y_scale) as f32;++    let text = match fi {+        Some(fi) => fi.decode(bytes),+        None => bytes.iter().filter_map(|&b| char::from_u32(b as u32)).collect(),+    };+    if !text.is_empty() {+        prims.push(Prim::Text {+            x: x as f32,+            y: y as f32,+            size,+            argb: gs.fill,+            text,+        });+    }+    advance+}++// ---------------------------------------------------------------------------+// Image XObjects+// ---------------------------------------------------------------------------++struct ImageData {+    w: u32,+    h: u32,+    /// 0 = raw RGBA8888, 1 = JPEG bytes.+    format: u8,+    data: Vec<u8>,+}++/// Map of XObject resource name -> object id from a resources dictionary.+fn xobjects_from_resources(doc: &Document, res_dict: &lopdf::Dictionary) -> HashMap<Vec<u8>, ObjectId> {+    let mut out = HashMap::new();+    if let Some(Object::Dictionary(xo)) = res_dict.get(b"XObject").ok().and_then(|o| deref(doc, o)) {+        for (name, v) in xo.iter() {+            if let Ok(id) = v.as_reference() {+                out.insert(name.clone(), id);+            }+        }+    }+    out+}++/// Resolve the page's (inherited) `/Resources` as an owned dictionary.+fn resources_dict(doc: &Document, page_id: ObjectId) -> Option<lopdf::Dictionary> {+    inherited(doc, page_id, b"Resources")+        .and_then(|o| deref(doc, o))+        .and_then(|o| o.as_dict().ok())+        .cloned()+}++/// Collect the `/Filter` names of a stream (single name or array).+fn filter_names(doc: &Document, dict: &lopdf::Dictionary) -> Vec<String> {+    match dict.get(b"Filter").ok().and_then(|o| deref(doc, o)) {+        Some(Object::Name(n)) => vec![String::from_utf8_lossy(n).into_owned()],+        Some(Object::Array(a)) => a+            .iter()+            .filter_map(|o| o.as_name().ok())+            .map(|n| String::from_utf8_lossy(n).into_owned())+            .collect(),+        _ => Vec::new(),+    }+}++/// Number of color components for a colorspace object, plus an optional Indexed+/// palette `(base_components, lookup_bytes)`.+fn colorspace_info(+    doc: &Document,+    cs: Option<&Object>,+) -> (u8, Option<(u8, Vec<u8>)>) {+    let cs = match cs.and_then(|o| deref(doc, o)) {+        Some(o) => o,+        None => return (1, None),+    };+    match cs {+        Object::Name(n) => match n.as_slice() {+            b"DeviceRGB" | b"RGB" | b"CalRGB" => (3, None),+            b"DeviceCMYK" | b"CMYK" => (4, None),+            _ => (1, None), // DeviceGray / CalGray / fallback+        },+        Object::Array(a) => {+            let head = a.first().and_then(|o| o.as_name().ok()).unwrap_or(b"");+            match head {+                b"ICCBased" => {+                    let n = a+                        .get(1)+                        .and_then(|o| deref(doc, o))+                        .and_then(|o| match o {+                            Object::Stream(s) => s.dict.get(b"N").ok().and_then(num),+                            _ => None,+                        })+                        .unwrap_or(1.0) as u8;+                    (n.max(1), None)+                }+                b"Indexed" | b"I" => {+                    let (base_n, _) = colorspace_info(doc, a.get(1));+                    let lookup = match a.get(3).and_then(|o| deref(doc, o)) {+                        Some(Object::String(s, _)) => s.clone(),+                        Some(Object::Stream(s)) => {+                            s.decompressed_content().unwrap_or_else(|_| s.content.clone())+                        }+                        _ => Vec::new(),+                    };+                    (1, Some((base_n, lookup)))+                }+                b"CalRGB" => (3, None),+                b"CalGray" => (1, None),+                b"DeviceN" => {+                    let n = a+                        .get(1)+                        .and_then(|o| deref(doc, o))+                        .and_then(|o| o.as_array().ok())+                        .map(|arr| arr.len() as u8)+                        .unwrap_or(1);+                    (n.max(1), None)+                }+                b"Separation" => (1, None),+                _ => (1, None),+            }+        }+        _ => (1, None),+    }+}++fn comps_to_rgb(comps: &[u8], n: u8) -> (u8, u8, u8) {+    match n {+        3 => (comps[0], comps[1], comps[2]),+        4 => {+            let c = comps[0] as f64 / 255.0;+            let m = comps[1] as f64 / 255.0;+            let y = comps[2] as f64 / 255.0;+            let k = comps[3] as f64 / 255.0;+            let r = (1.0 - c) * (1.0 - k);+            let g = (1.0 - m) * (1.0 - k);+            let b = (1.0 - y) * (1.0 - k);+            ((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8)+        }+        _ => (comps[0], comps[0], comps[0]),+    }+}++/// Extract a drawable image from an image XObject stream, or `None` if the+/// format is unsupported (e.g. JPEG2000, exotic color spaces).+fn extract_image(doc: &Document, stream: &lopdf::Stream, fill_argb: u32) -> Option<ImageData> {+    let dict = &stream.dict;+    let w = dict.get(b"Width").ok().and_then(num)? as u32;+    let h = dict.get(b"Height").ok().and_then(num)? as u32;+    if w == 0 || h == 0 || w > 20000 || h > 20000 {+        return None;+    }+    let filters = filter_names(doc, dict);+    let is_dct = filters.iter().any(|f| f == "DCTDecode" || f == "DCT");+    let is_jpx = filters.iter().any(|f| f == "JPXDecode");+    if is_jpx {+        return None; // JPEG2000 not supported.+    }+    if is_dct {+        // Hand the raw JPEG bytes to Android's BitmapFactory.+        return Some(ImageData {+            w,+            h,+            format: 1,+            data: stream.content.clone(),+        });+    }++    let image_mask = matches!(dict.get(b"ImageMask").ok(), Some(Object::Boolean(true)));+    let bpc = if image_mask {+        1+    } else {+        dict.get(b"BitsPerComponent").ok().and_then(num).unwrap_or(8.0) as u32+    };+    let samples = stream.decompressed_content().ok()?;+    let mut rgba = vec![0u8; (w * h * 4) as usize];+    let smask = read_smask(doc, dict, w, h);++    if image_mask {+        // 1-bit stencil: paint fill color where the (Decode-adjusted) sample is+        // 0; elsewhere transparent.+        let invert = matches!(+            dict.get(b"Decode").ok().and_then(|o| deref(doc, o)),+            Some(Object::Array(a)) if a.first().and_then(num) == Some(1.0)+        );+        let fr = ((fill_argb >> 16) & 0xFF) as u8;+        let fg = ((fill_argb >> 8) & 0xFF) as u8;+        let fb = (fill_argb & 0xFF) as u8;+        let row_bytes = ((w + 7) / 8) as usize;+        for y in 0..h as usize {+            for x in 0..w as usize {+                let byte = samples.get(y * row_bytes + x / 8).copied().unwrap_or(0);+                let mut bit = (byte >> (7 - (x % 8))) & 1;+                if invert {+                    bit ^= 1;+                }+                let idx = (y * w as usize + x) * 4;+                if bit == 0 {+                    rgba[idx] = fr;+                    rgba[idx + 1] = fg;+                    rgba[idx + 2] = fb;+                    rgba[idx + 3] = 255;+                }+            }+        }+        return Some(ImageData { w, h, format: 0, data: rgba });+    }++    let (ncomp, indexed) = colorspace_info(doc, dict.get(b"ColorSpace").ok());++    if bpc == 8 {+        let row_bytes = (w as usize) * (ncomp as usize);+        for y in 0..h as usize {+            for x in 0..w as usize {+                let base = y * row_bytes + x * ncomp as usize;+                let idx = (y * w as usize + x) * 4;+                let (r, g, b) = if let Some((base_n, lookup)) = &indexed {+                    let index = samples.get(base).copied().unwrap_or(0) as usize;+                    let off = index * *base_n as usize;+                    if off + *base_n as usize <= lookup.len() {+                        comps_to_rgb(&lookup[off..off + *base_n as usize], *base_n)+                    } else {+                        (0, 0, 0)+                    }+                } else if base + ncomp as usize <= samples.len() {+                    comps_to_rgb(&samples[base..base + ncomp as usize], ncomp)+                } else {+                    (0, 0, 0)+                };+                rgba[idx] = r;+                rgba[idx + 1] = g;+                rgba[idx + 2] = b;+                rgba[idx + 3] = 255;+            }+        }+        apply_smask(&mut rgba, &smask);+        return Some(ImageData { w, h, format: 0, data: rgba });+    }++    if bpc == 1 {+        // 1-bit grayscale (0 = black, 1 = white), or indexed 1-bit palette.+        let row_bytes = ((w + 7) / 8) as usize;+        for y in 0..h as usize {+            for x in 0..w as usize {+                let byte = samples.get(y * row_bytes + x / 8).copied().unwrap_or(0);+                let bit = (byte >> (7 - (x % 8))) & 1;+                let idx = (y * w as usize + x) * 4;+                let (r, g, b) = if let Some((base_n, lookup)) = &indexed {+                    let off = bit as usize * *base_n as usize;+                    if off + *base_n as usize <= lookup.len() {+                        comps_to_rgb(&lookup[off..off + *base_n as usize], *base_n)+                    } else {+                        (0, 0, 0)+                    }+                } else if bit == 1 {+                    (255, 255, 255)+                } else {+                    (0, 0, 0)+                };+                rgba[idx] = r;+                rgba[idx + 1] = g;+                rgba[idx + 2] = b;+                rgba[idx + 3] = 255;+            }+        }+        apply_smask(&mut rgba, &smask);+        return Some(ImageData { w, h, format: 0, data: rgba });+    }++    None+}++/// Apply a per-pixel soft-mask alpha (length `w*h`) to an RGBA buffer.+fn apply_smask(rgba: &mut [u8], smask: &Option<Vec<u8>>) {+    if let Some(alpha) = smask {+        let n = (rgba.len() / 4).min(alpha.len());+        for i in 0..n {+            rgba[i * 4 + 3] = alpha[i];+        }+    }+}++/// Decode an image's `/SMask` (soft mask) into a `w*h` 8-bit alpha buffer,+/// nearest-resampling if its dimensions differ. Returns `None` for absent or+/// unsupported (e.g. DCT/JPX, non-8-bit) masks.+fn read_smask(doc: &Document, dict: &lopdf::Dictionary, w: u32, h: u32) -> Option<Vec<u8>> {+    let sm = dict.get(b"SMask").ok().and_then(|o| deref(doc, o))?;+    let s = match sm {+        Object::Stream(s) => s,+        _ => return None,+    };+    let filters = filter_names(doc, &s.dict);+    if filters.iter().any(|f| f == "DCTDecode" || f == "JPXDecode") {+        return None;+    }+    let sbpc = s.dict.get(b"BitsPerComponent").ok().and_then(num).unwrap_or(8.0) as u32;+    if sbpc != 8 {+        return None;+    }+    let sw = s.dict.get(b"Width").ok().and_then(num)? as usize;+    let sh = s.dict.get(b"Height").ok().and_then(num)? as usize;+    if sw == 0 || sh == 0 {+        return None;+    }+    let data = s.decompressed_content().ok()?;+    let (w, h) = (w as usize, h as usize);+    let mut alpha = vec![255u8; w * h];+    for y in 0..h {+        for x in 0..w {+            let sx = x * sw / w;+            let sy = y * sh / h;+            alpha[y * w + x] = data.get(sy * sw + sx).copied().unwrap_or(255);+        }+    }+    Some(alpha)+}++// ---------------------------------------------------------------------------+// Simple-font encodings (base encoding + /Differences)+// ---------------------------------------------------------------------------++mod encoding {+    use super::{deref, num, Object};+    use lopdf::Document;+    use std::collections::HashMap;++    /// Build a `code -> unicode char` map for a simple font: start from the base+    /// encoding (WinAnsi / MacRoman / Standard, or Symbol / ZapfDingbats for+    /// those base fonts), then apply any `/Encoding /Differences`.+    pub fn build(doc: &Document, font: &lopdf::Dictionary) -> HashMap<u32, char> {+        let base_font = font+            .get(b"BaseFont")+            .ok()+            .and_then(|o| o.as_name().ok())+            .map(|n| String::from_utf8_lossy(n).into_owned())+            .unwrap_or_default();++        let enc_obj = font.get(b"Encoding").ok().and_then(|o| deref(doc, o));+        let base_name = match &enc_obj {+            Some(Object::Name(n)) => Some(String::from_utf8_lossy(n).into_owned()),+            Some(Object::Dictionary(d)) => d+                .get(b"BaseEncoding")+                .ok()+                .and_then(|o| o.as_name().ok())+                .map(|n| String::from_utf8_lossy(n).into_owned()),+            _ => None,+        };++        let mut map = if base_font.contains("Symbol") {+            symbol_table()+        } else if base_font.contains("ZapfDingbats") || base_font.contains("Dingbats") {+            zapf_table()+        } else {+            match base_name.as_deref() {+                Some("WinAnsiEncoding") => win_ansi(),+                Some("MacRomanEncoding") => win_ansi(), // close enough for Latin text+                Some("StandardEncoding") => standard(),+                // Default base encoding for most simple fonts is Standard, but+                // WinAnsi is the safest superset for modern PDFs.+                _ => win_ansi(),+            }+        };++        // Apply /Differences: [ code /name /name code /name ... ].+        if let Some(Object::Dictionary(d)) = &enc_obj {+            if let Some(Object::Array(diffs)) = d.get(b"Differences").ok().and_then(|o| deref(doc, o))+            {+                let mut code = 0u32;+                for item in diffs {+                    match item {+                        Object::Integer(_) | Object::Real(_) => {+                            code = num(item).unwrap_or(0.0) as u32;+                        }+                        Object::Name(name) => {+                            if let Some(c) = glyph_to_char(&String::from_utf8_lossy(name)) {+                                map.insert(code, c);+                            }+                            code += 1;+                        }+                        _ => {}+                    }+                }+            }+        }+        map+    }++    /// Resolve an Adobe glyph name to a Unicode scalar. Handles `uniXXXX`,+    /// single-character names, digit/letter names and a curated common subset.+    pub fn glyph_to_char(name: &str) -> Option<char> {+        if let Some(hex) = name.strip_prefix("uni") {+            if hex.len() >= 4 {+                if let Ok(cp) = u32::from_str_radix(&hex[..4], 16) {+                    return char::from_u32(cp);+                }+            }+        }+        if name.starts_with('u') && name.len() >= 5 {+            if let Ok(cp) = u32::from_str_radix(&name[1..], 16) {+                if let Some(c) = char::from_u32(cp) {+                    return Some(c);+                }+            }+        }+        if let Some(c) = curated(name) {+            return Some(c);+        }+        // Single-character glyph name (e.g. "A", "a", "1").+        let mut chars = name.chars();+        if let (Some(c), None) = (chars.next(), chars.clone().next()) {+            return Some(c);+        }+        None+    }++    fn curated(name: &str) -> Option<char> {+        let c = match name {+            "space" | "nbspace" => ' ',+            "bullet" => '\u{2022}',+            "periodcentered" => '\u{00B7}',+            "endash" => '\u{2013}',+            "emdash" => '\u{2014}',+            "hyphen" | "sfthyphen" => '-',+            "quoteleft" => '\u{2018}',+            "quoteright" => '\u{2019}',+            "quotedblleft" => '\u{201C}',+            "quotedblright" => '\u{201D}',+            "quotesingle" => '\'',+            "quotedbl" => '"',+            "comma" => ',',+            "period" => '.',+            "colon" => ':',+            "semicolon" => ';',+            "slash" => '/',+            "backslash" => '\\',+            "asterisk" => '*',+            "ampersand" => '&',+            "at" => '@',+            "numbersign" => '#',+            "percent" => '%',+            "dollar" => '$',+            "cent" => '\u{00A2}',+            "sterling" => '\u{00A3}',+            "euro" => '\u{20AC}',+            "yen" => '\u{00A5}',+            "trademark" => '\u{2122}',+            "registered" => '\u{00AE}',+            "copyright" => '\u{00A9}',+            "degree" => '\u{00B0}',+            "plusminus" => '\u{00B1}',+            "multiply" => '\u{00D7}',+            "divide" => '\u{00F7}',+            "ellipsis" => '\u{2026}',+            "dagger" => '\u{2020}',+            "daggerdbl" => '\u{2021}',+            "paragraph" => '\u{00B6}',+            "section" => '\u{00A7}',+            "fi" => '\u{FB01}',+            "fl" => '\u{FB02}',+            "exclam" => '!',+            "question" => '?',+            "parenleft" => '(',+            "parenright" => ')',+            "bracketleft" => '[',+            "bracketright" => ']',+            "braceleft" => '{',+            "braceright" => '}',+            "less" => '<',+            "greater" => '>',+            "equal" => '=',+            "plus" => '+',+            "minus" => '\u{2212}',+            "underscore" => '_',+            "hyphenminus" => '-',+            "arrowright" => '\u{2192}',+            "arrowleft" => '\u{2190}',+            "arrowup" => '\u{2191}',+            "arrowdown" => '\u{2193}',+            "zero" => '0',+            "one" => '1',+            "two" => '2',+            "three" => '3',+            "four" => '4',+            "five" => '5',+            "six" => '6',+            "seven" => '7',+            "eight" => '8',+            "nine" => '9',+            _ => return None,+        };+        Some(c)+    }++    /// WinAnsiEncoding (CP1252): Latin-1 with the 0x80–0x9F range remapped.+    pub fn win_ansi() -> HashMap<u32, char> {+        let mut m = latin1();+        let overrides: [(u32, u32); 27] = [+            (0x80, 0x20AC),+            (0x82, 0x201A),+            (0x83, 0x0192),+            (0x84, 0x201E),+            (0x85, 0x2026),+            (0x86, 0x2020),+            (0x87, 0x2021),+            (0x88, 0x02C6),+            (0x89, 0x2030),+            (0x8A, 0x0160),+            (0x8B, 0x2039),+            (0x8C, 0x0152),+            (0x8E, 0x017D),+            (0x91, 0x2018),+            (0x92, 0x2019),+            (0x93, 0x201C),+            (0x94, 0x201D),+            (0x95, 0x2022),+            (0x96, 0x2013),+            (0x97, 0x2014),+            (0x98, 0x02DC),+            (0x99, 0x2122),+            (0x9A, 0x0161),+            (0x9B, 0x203A),+            (0x9C, 0x0153),+            (0x9E, 0x017E),+            (0x9F, 0x0178),+        ];+        for (code, cp) in overrides {+            if let Some(c) = char::from_u32(cp) {+                m.insert(code, c);+            }+        }+        m+    }++    /// StandardEncoding: for the ASCII range it matches Latin-1; good enough as+    /// a base to which /Differences are applied.+    fn standard() -> HashMap<u32, char> {+        latin1()+    }++    /// Codes 0x20–0xFF mapped as Latin-1 (identity to Unicode).+    fn latin1() -> HashMap<u32, char> {+        let mut m = HashMap::new();+        for code in 0x20u32..=0xFF {+            if let Some(c) = char::from_u32(code) {+                m.insert(code, c);+            }+        }+        m+    }++    /// A minimal Symbol-font subset (common math/greek glyphs seen in PDFs).+    fn symbol_table() -> HashMap<u32, char> {+        let pairs: [(u32, u32); 8] = [+            (0x61, 0x03B1), // alpha+            (0x62, 0x03B2), // beta+            (0x64, 0x03B4), // delta+            (0x70, 0x03C0), // pi+            (0xB7, 0x2022), // bullet+            (0xE0, 0x2666), // diamond+            (0xAE, 0x2192), // arrowright+            (0xAC, 0x2190), // arrowleft+        ];+        pairs+            .iter()+            .filter_map(|&(code, cp)| char::from_u32(cp).map(|c| (code, c)))+            .collect()+    }++    /// A minimal ZapfDingbats subset (bullets/arrows commonly used as markers).+    fn zapf_table() -> HashMap<u32, char> {+        let pairs: [(u32, u32); 6] = [+            (0x6C, 0x25CF), // filled circle bullet+            (0x6E, 0x25A0), // filled square+            (0xA8, 0x2022), // bullet+            (0xE0, 0x2192), // arrow-like+            (0x4C, 0x2764), // heart-ish+            (0x48, 0x2666), // diamond+        ];+        pairs+            .iter()+            .filter_map(|&(code, cp)| char::from_u32(cp).map(|c| (code, c)))+            .collect()+    }++    #[cfg(test)]+    mod tests {+        use super::*;++        #[test]+        fn winansi_maps_bullet_and_dashes() {+            let m = win_ansi();+            assert_eq!(m.get(&0x95), Some(&'\u{2022}'));+            assert_eq!(m.get(&0x96), Some(&'\u{2013}'));+            assert_eq!(m.get(&0x97), Some(&'\u{2014}'));+            assert_eq!(m.get(&0x41), Some(&'A'));+        }++        #[test]+        fn glyph_names_resolve() {+            assert_eq!(glyph_to_char("bullet"), Some('\u{2022}'));+            assert_eq!(glyph_to_char("uni20AC"), Some('\u{20AC}'));+            assert_eq!(glyph_to_char("A"), Some('A'));+            assert_eq!(glyph_to_char("emdash"), Some('\u{2014}'));+        }+    }+}++// ---------------------------------------------------------------------------+// ToUnicode CMap parsing+// ---------------------------------------------------------------------------++mod cmap {+    use std::collections::HashMap;++    enum Token {+        Hex(Vec<u8>),+        ArrayOpen,+        ArrayClose,+        Keyword(String),+    }++    /// Parse a `/ToUnicode` CMap stream into a `code -> string` map, handling+    /// `beginbfchar`/`endbfchar` and `beginbfrange`/`endbfrange`.+    pub fn parse(data: &[u8]) -> HashMap<u32, String> {+        let tokens = tokenize(data);+        let mut map = HashMap::new();+        let mut i = 0;+        while i < tokens.len() {+            match &tokens[i] {+                Token::Keyword(k) if k == "beginbfchar" => {+                    i += 1;+                    while i < tokens.len() {+                        if let Token::Keyword(e) = &tokens[i] {+                            if e == "endbfchar" {+                                break;+                            }+                        }+                        if let (Token::Hex(src), Some(Token::Hex(dst))) =+                            (&tokens[i], tokens.get(i + 1))+                        {+                            map.insert(code(src), utf16be(dst));+                            i += 2;+                        } else {+                            i += 1;+                        }+                    }+                }+                Token::Keyword(k) if k == "beginbfrange" => {+                    i += 1;+                    while i < tokens.len() {+                        if let Token::Keyword(e) = &tokens[i] {+                            if e == "endbfrange" {+                                break;+                            }+                        }+                        match (tokens.get(i), tokens.get(i + 1), tokens.get(i + 2)) {+                            (Some(Token::Hex(lo)), Some(Token::Hex(hi)), Some(Token::Hex(dst))) => {+                                let (lo, hi) = (code(lo), code(hi));+                                let base = utf16be_units(dst);+                                for (n, c) in (lo..=hi).enumerate() {+                                    map.insert(c, units_to_string_incremented(&base, n as u32));+       

Diff truncated.