pdf: add safe PDF models, parser and native document bridge
- Commit
065f9e40d92459c2522854b90d318a951c8c80be- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-08 18:04 UTC (5 months ago)
- Parents
347cd8c
Diff
pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.ktnew file mode 100644index 0000000000..9fd859eb96--- /dev/null+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfNative.kt@@ -0,0 +1,91 @@+package com.vayunmathur.pdf.util++/**+ * JNI bridge to the native Rust PDF renderer (`libpdf_render.so`, built from+ * `pdf/rust/`). Loads the library once; [isAvailable] is false if the native+ * lib is missing for the current ABI so the safe viewer can show a clean error+ * instead of crashing.+ *+ * All entry points are blocking and must be called off the main thread. Handles+ * returned by [openDocument] are opaque; pass 0 to mean "no document".+ */+object PdfNative {++ val isAvailable: Boolean =+ try {+ System.loadLibrary("pdf_render")+ android.util.Log.i("PdfNative", "libpdf_render loaded")+ true+ } catch (t: Throwable) {+ android.util.Log.e("PdfNative", "System.loadLibrary(pdf_render) failed", t)+ false+ }++ /**+ * Parse [data] (the raw PDF bytes) and return an opaque handle, or 0 on+ * parse failure or if the document is encrypted (v1 does not decrypt).+ */+ external fun openDocument(data: ByteArray): Long++ /** Number of pages in the document behind [handle], or 0 if unknown. */+ external fun getPageCount(handle: Long): Int++ /**+ * Render page [index] (0-based) into the serialized primitive buffer+ * consumed by [SafePdfParser], or `null` on any error.+ */+ external fun renderPage(handle: Long, index: Int): ByteArray?++ /** Release the document behind [handle]. Safe to call with 0. */+ external fun closeDocument(handle: Long)++ // --- Editing: annotations, forms, save ---------------------------------++ /** Serialized annotations on [page] for the overlay/hit-testing. */+ external fun listAnnotations(handle: Long, page: Int): ByteArray?++ /** Serialized AcroForm widget fields on [page]. */+ external fun listFormFields(handle: Long, page: Int): ByteArray?++ /** Add a FreeText annotation; returns its id (0 on failure). */+ external fun addTextAnnotation(+ handle: Long, page: Int,+ x0: Float, y0: Float, x1: Float, y1: Float,+ argb: Int, size: Float, text: String,+ ): Long++ external fun addHighlight(+ handle: Long, page: Int, x0: Float, y0: Float, x1: Float, y1: Float, argb: Int,+ ): Long++ external fun addRectAnnotation(+ handle: Long, page: Int,+ x0: Float, y0: Float, x1: Float, y1: Float, argb: Int, lineWidth: Float,+ ): Long++ /** [pts] are flat page-space x,y pairs of one ink stroke. */+ external fun addInkAnnotation(+ handle: Long, page: Int, argb: Int, lineWidth: Float, pts: FloatArray,+ ): Long++ external fun addImageStamp(+ handle: Long, page: Int,+ x0: Float, y0: Float, x1: Float, y1: Float,+ imgW: Int, imgH: Int, jpeg: ByteArray,+ ): Long++ external fun updateAnnotationRect(+ handle: Long, annotId: Long, x0: Float, y0: Float, x1: Float, y1: Float,+ ): Boolean++ external fun updateTextAnnotation(handle: Long, annotId: Long, text: String): Boolean++ external fun deleteAnnotation(handle: Long, page: Int, annotId: Long): Boolean++ external fun setTextField(handle: Long, widgetId: Long, value: String): Boolean++ external fun setCheckbox(handle: Long, widgetId: Long, on: Boolean): Boolean++ /** Serialize the modified document to PDF bytes, or null on failure. */+ external fun saveDocument(handle: Long): ByteArray?+}
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.ktnew file mode 100644index 0000000000..092f11c064--- /dev/null+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfDocument.kt@@ -0,0 +1,132 @@+package com.vayunmathur.pdf.util++import android.content.Context+import android.net.Uri+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.util.concurrent.ConcurrentHashMap++/**+ * A parsed PDF for the "safe" viewer, backed by the native Rust renderer.+ *+ * Reads the [Uri] bytes through the [Context]'s content resolver, hands them to+ * [PdfNative.openDocument], and exposes the [pageCount] plus a per-page+ * [renderPage]. Rendered pages are cached so scrolling back does not re-decode.+ * All native work happens on [Dispatchers.IO]; callers must [close] when done.+ */+class SafePdfDocument private constructor(+ private val handle: Long,+ val pageCount: Int,+) {+ private val cache = ConcurrentHashMap<Int, SafePdfPage>()++ /** Decode page [index] (0-based), or `null` if the native render fails. */+ suspend fun renderPage(index: Int): SafePdfPage? = withContext(Dispatchers.IO) {+ cache[index]?.let { return@withContext it }+ val bytes = PdfNative.renderPage(handle, index) ?: return@withContext null+ val page = SafePdfParser.parse(bytes)+ cache[index] = page+ page+ }++ /** Release native resources. Idempotent-safe to call once. */+ fun close() {+ PdfNative.closeDocument(handle)+ }++ private fun invalidate(index: Int) {+ cache.remove(index)+ }++ /** Annotations on [index] for the editing overlay. */+ suspend fun annotations(index: Int): List<SafeAnnotation> = withContext(Dispatchers.IO) {+ PdfNative.listAnnotations(handle, index)+ ?.let { SafePdfParser.parseAnnotations(it) } ?: emptyList()+ }++ /** AcroForm widget fields on [index]. */+ suspend fun formFields(index: Int): List<SafeFormField> = withContext(Dispatchers.IO) {+ PdfNative.listFormFields(handle, index)+ ?.let { SafePdfParser.parseFormFields(it) } ?: emptyList()+ }++ suspend fun addText(+ index: Int, x0: Float, y0: Float, x1: Float, y1: Float, argb: Int, size: Float, text: String,+ ): Long = withContext(Dispatchers.IO) {+ PdfNative.addTextAnnotation(handle, index, x0, y0, x1, y1, argb, size, text)+ .also { invalidate(index) }+ }++ suspend fun addHighlight(+ index: Int, x0: Float, y0: Float, x1: Float, y1: Float, argb: Int,+ ): Long = withContext(Dispatchers.IO) {+ PdfNative.addHighlight(handle, index, x0, y0, x1, y1, argb).also { invalidate(index) }+ }++ suspend fun addRect(+ index: Int, x0: Float, y0: Float, x1: Float, y1: Float, argb: Int, lineWidth: Float,+ ): Long = withContext(Dispatchers.IO) {+ PdfNative.addRectAnnotation(handle, index, x0, y0, x1, y1, argb, lineWidth)+ .also { invalidate(index) }+ }++ suspend fun addInk(+ index: Int, argb: Int, lineWidth: Float, pts: FloatArray,+ ): Long = withContext(Dispatchers.IO) {+ PdfNative.addInkAnnotation(handle, index, argb, lineWidth, pts).also { invalidate(index) }+ }++ suspend fun addImageStamp(+ index: Int, x0: Float, y0: Float, x1: Float, y1: Float, imgW: Int, imgH: Int, jpeg: ByteArray,+ ): Long = withContext(Dispatchers.IO) {+ PdfNative.addImageStamp(handle, index, x0, y0, x1, y1, imgW, imgH, jpeg)+ .also { invalidate(index) }+ }++ suspend fun moveAnnotation(+ index: Int, annotId: Long, x0: Float, y0: Float, x1: Float, y1: Float,+ ): Boolean = withContext(Dispatchers.IO) {+ PdfNative.updateAnnotationRect(handle, annotId, x0, y0, x1, y1).also { invalidate(index) }+ }++ suspend fun editText(index: Int, annotId: Long, text: String): Boolean =+ withContext(Dispatchers.IO) {+ PdfNative.updateTextAnnotation(handle, annotId, text).also { invalidate(index) }+ }++ suspend fun deleteAnnotation(index: Int, annotId: Long): Boolean = withContext(Dispatchers.IO) {+ PdfNative.deleteAnnotation(handle, index, annotId).also { invalidate(index) }+ }++ suspend fun setTextField(index: Int, widgetId: Long, value: String): Boolean =+ withContext(Dispatchers.IO) {+ PdfNative.setTextField(handle, widgetId, value).also { invalidate(index) }+ }++ suspend fun setCheckbox(index: Int, widgetId: Long, on: Boolean): Boolean =+ withContext(Dispatchers.IO) {+ PdfNative.setCheckbox(handle, widgetId, on).also { invalidate(index) }+ }++ /** Serialize the (possibly edited) document to PDF bytes. */+ suspend fun save(): ByteArray? = withContext(Dispatchers.IO) { PdfNative.saveDocument(handle) }++ companion object {+ /**+ * Open [uri] as a safe PDF, or return `null` when the native lib is+ * unavailable, the bytes can't be read, or parsing fails (e.g. the PDF+ * is encrypted). Runs entirely off the main thread.+ */+ suspend fun open(context: Context, uri: Uri): SafePdfDocument? =+ withContext(Dispatchers.IO) {+ if (!PdfNative.isAvailable) return@withContext null+ val bytes = runCatching {+ context.contentResolver.openInputStream(uri)?.use { it.readBytes() }+ }.getOrNull() ?: return@withContext null++ val handle = PdfNative.openDocument(bytes)+ if (handle == 0L) return@withContext null+ SafePdfDocument(handle, PdfNative.getPageCount(handle))+ }+ }+}
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.ktnew file mode 100644index 0000000000..8554871560--- /dev/null+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt@@ -0,0 +1,78 @@+package com.vayunmathur.pdf.util++import androidx.compose.ui.geometry.Offset++/**+ * A single drawing primitive decoded from the native renderer, in PDF page+ * space (origin bottom-left). [SafePdfViewerScreen] applies the Y-flip and the+ * fit-to-width scale when drawing.+ *+ * Colors are packed ARGB ([Int]) matching Android's color ints.+ */+sealed interface PdfPrimitive {+ /** A run of text with its baseline origin, on-page size and color. */+ data class Text(+ val origin: Offset,+ val size: Float,+ val color: Int,+ val text: String,+ ) : PdfPrimitive++ /** A filled polygon (one subpath). */+ data class FillPath(+ val color: Int,+ val evenOdd: Boolean,+ val points: List<Offset>,+ ) : PdfPrimitive++ /** A stroked polyline (one subpath). [dash] is empty for a solid line. */+ data class StrokePath(+ val color: Int,+ val width: Float,+ val dash: FloatArray,+ val dashPhase: Float,+ val points: List<Offset>,+ ) : PdfPrimitive++ /**+ * A raster image. [ctm] is the 6-element PDF matrix (a,b,c,d,e,f) mapping+ * the unit square to page space; [bitmap] is the decoded image (null if it+ * could not be decoded).+ */+ data class Image(+ val ctm: FloatArray,+ val bitmap: android.graphics.Bitmap?,+ ) : PdfPrimitive+}++/** One decoded page: its PDF page dimensions plus the primitives to draw. */+data class SafePdfPage(+ val width: Float,+ val height: Float,+ val primitives: List<PdfPrimitive>,+)++/** An annotation on a page (from the native listing), in page space. */+data class SafeAnnotation(+ val id: Long,+ val subtype: Int, // 1 FreeText, 2 Highlight, 3 Square, 4 Ink, 5 Stamp, 6 Widget, ...+ val x0: Float,+ val y0: Float,+ val x1: Float,+ val y1: Float,+ val color: Int,+ val contents: String,+)++/** An AcroForm widget field on a page, in page space. */+data class SafeFormField(+ val id: Long,+ val type: Int, // 0 text, 1 checkbox/button, 2 choice, 3 other+ val x0: Float,+ val y0: Float,+ val x1: Float,+ val y1: Float,+ val name: String,+ val value: String,+ val checked: Boolean,+)
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.ktnew file mode 100644index 0000000000..2507500fd2--- /dev/null+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -0,0 +1,167 @@+package com.vayunmathur.pdf.util++import androidx.compose.ui.geometry.Offset+import java.nio.ByteBuffer+import java.nio.ByteOrder++/**+ * Decodes the compact little-endian primitive buffer produced by the native+ * renderer ([PdfNative.renderPage]) into a [SafePdfPage].+ *+ * Wire format (must stay in sync with `pdf/rust/src/lib.rs` `wire` module):+ * ```+ * header: f32 pageWidth, f32 pageHeight, u32 primitiveCount+ * per primitive: u8 tag, then payload+ * 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8 bytes]+ * 2 Fill: u32 argb, u16 nPts, [f32 x, f32 y]...+ * 3 Stroke: u32 argb, f32 width, u16 nPts, [f32 x, f32 y]...+ * ```+ * Pure function → unit-testable with no Android dependencies beyond [Offset].+ */+object SafePdfParser {++ private const val TAG_TEXT = 1+ private const val TAG_FILL = 2+ private const val TAG_STROKE = 3+ private const val TAG_IMAGE = 4++ fun parse(bytes: ByteArray): SafePdfPage {+ val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)++ val width = buf.float+ val height = buf.float+ val count = buf.int // primitive count (u32, fits in Int in practice)++ val primitives = ArrayList<PdfPrimitive>(count.coerceAtLeast(0))+ repeat(count) {+ when (val tag = buf.get().toInt()) {+ TAG_TEXT -> {+ val x = buf.float+ val y = buf.float+ val size = buf.float+ val argb = buf.int+ val len = buf.short.toInt() and 0xFFFF+ val strBytes = ByteArray(len)+ buf.get(strBytes)+ primitives.add(+ PdfPrimitive.Text(+ origin = Offset(x, y),+ size = size,+ color = argb,+ text = String(strBytes, Charsets.UTF_8),+ )+ )+ }++ TAG_FILL -> {+ val argb = buf.int+ val evenOdd = buf.get().toInt() != 0+ primitives.add(PdfPrimitive.FillPath(argb, evenOdd, readPoints(buf)))+ }++ TAG_STROKE -> {+ val argb = buf.int+ val strokeWidth = buf.float+ val nDash = buf.get().toInt() and 0xFF+ val dash = FloatArray(nDash) { buf.float }+ val dashPhase = buf.float+ primitives.add(+ PdfPrimitive.StrokePath(argb, strokeWidth, dash, dashPhase, readPoints(buf))+ )+ }++ TAG_IMAGE -> {+ val ctm = FloatArray(6) { buf.float }+ val w = buf.int+ val h = buf.int+ val format = buf.get().toInt()+ val len = buf.int+ val data = ByteArray(len)+ buf.get(data)+ primitives.add(PdfPrimitive.Image(ctm, decodeBitmap(w, h, format, data)))+ }++ else -> throw IllegalArgumentException("Unknown primitive tag: $tag")+ }+ }++ return SafePdfPage(width, height, primitives)+ }++ /** Decode the annotation listing buffer from `listAnnotations`. */+ fun parseAnnotations(bytes: ByteArray): List<SafeAnnotation> {+ val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)+ val count = buf.int+ val out = ArrayList<SafeAnnotation>(count.coerceAtLeast(0))+ repeat(count) {+ val id = buf.long+ val subtype = buf.get().toInt()+ val x0 = buf.float; val y0 = buf.float; val x1 = buf.float; val y1 = buf.float+ val color = buf.int+ val contents = readString(buf)+ out.add(SafeAnnotation(id, subtype, x0, y0, x1, y1, color, contents))+ }+ return out+ }++ /** Decode the form-field listing buffer from `listFormFields`. */+ fun parseFormFields(bytes: ByteArray): List<SafeFormField> {+ val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)+ val count = buf.int+ val out = ArrayList<SafeFormField>(count.coerceAtLeast(0))+ repeat(count) {+ val id = buf.long+ val type = buf.get().toInt()+ val x0 = buf.float; val y0 = buf.float; val x1 = buf.float; val y1 = buf.float+ val name = readString(buf)+ val value = readString(buf)+ val checked = buf.get().toInt() != 0+ out.add(SafeFormField(id, type, x0, y0, x1, y1, name, value, checked))+ }+ return out+ }++ private fun readString(buf: ByteBuffer): String {+ val len = buf.short.toInt() and 0xFFFF+ val b = ByteArray(len)+ buf.get(b)+ return String(b, Charsets.UTF_8)+ }++ private fun readPoints(buf: ByteBuffer): List<Offset> {+ val n = buf.short.toInt() and 0xFFFF+ val points = ArrayList<Offset>(n)+ repeat(n) {+ val x = buf.float+ val y = buf.float+ points.add(Offset(x, y))+ }+ return points+ }++ /** Decode an image payload: format 1 = JPEG bytes, 0 = raw RGBA8888. */+ private fun decodeBitmap(w: Int, h: Int, format: Int, data: ByteArray): android.graphics.Bitmap? {+ return runCatching {+ when (format) {+ 1 -> android.graphics.BitmapFactory.decodeByteArray(data, 0, data.size)+ 0 -> {+ if (w <= 0 || h <= 0 || data.size < w * h * 4) return null+ val pixels = IntArray(w * h)+ var p = 0+ for (i in pixels.indices) {+ val r = data[p].toInt() and 0xFF+ val g = data[p + 1].toInt() and 0xFF+ val b = data[p + 2].toInt() and 0xFF+ val a = data[p + 3].toInt() and 0xFF+ pixels[i] = (a shl 24) or (r shl 16) or (g shl 8) or b+ p += 4+ }+ android.graphics.Bitmap.createBitmap(+ pixels, w, h, android.graphics.Bitmap.Config.ARGB_8888+ )+ }+ else -> null+ }+ }.getOrNull()+ }+}