Modern Apps git

← Modern-Apps.git

pdf: add tests for viewer, capture, native document and UI

Commit
38d276d7bdc23e5a4575784fa6e961e1f0ef055f
Author
Vayun Mathur <[email protected]>
When
2026-11-07 04:43 UTC (29 days ago)
Parents
cbdb33f
Coverage (merged INSTRUCTION): 9.6% -> 85.14% (45491/53432),
verified with :pdf:createMergedCoverageReport in this worktree.

Tests (24 files: 23 unit + 1 androidTest): pure geometry/frame
detection (grayscale/blur/threshold/dilate/trace/findBestQuad),
Quadrilateral, SafePdf models and image budgets, viewer-model
geometry (shape polygons, zoom/pan, flattenSmooth), scroll/zoom
state and selection-glyph math including selectionText, listings
happy paths and blend-mode mappings.

Native-backed tests run the real Rust engine on the JVM: a minimal
hand-built PDF is opened/rendered/searched/saved, annotation edits
round-trip (add/edit/move/duplicate/detach/delete, highlight,
markup, note, callout, shapes, ink, image stamp, redactions,
encryption), ComposePdfDocument appends/moves/removes/saves, and
exportCapturedPdf runs through PdfViewModel.

Robolectric/Compose tests cover MainActivity navigation, the viewer
screen loading a real PDF and rejecting a non-PDF, viewer chrome in
read/search/edit states, page item/canvas, form-field overlays of
every type, capture/crop/cut-glue screens, toolbar menus, all
pending dialogs, and draw phases via captureToImage. EditOverlay
gestures are driven for all eleven tools with assertions on the
annotations they create in a real document and on the
note/image/text/polyline/callout/select/move callbacks.
TextSelectionLayer is driven with long-press word selection,
handle drag, scroll and tap-dismiss. Activity-result flows
(pickers, save launchers) are driven through a fake
ActivityResultRegistry that delivers a file Uri, covering the
CutGlueScreen and CapturePdfScreen launcher callbacks and the
CutGlue save launcher.

A separate device test (PdfExporterDeviceTest, androidTest) covers
savePdfToUri page rendering, scan filters and the perspective warp
with real PdfDocument/ImageDecoder; it was not run to completion
here because the pre-existing PdfHomeTest crashes the instrumented
process on the x86_64 emulator (pdf_render has no x86_64 ABI
packaged, so CutGlueScreen's createEmptyDocument throws
UnsatisfiedLinkError) and the resulting truncated .ec breaks the
merged report reader until deleted. That crash exists without
this change.

Bug fix in its own commit on main: the opacity string's bare '%'
crashing StyleDialog (UnknownFormatConversionException).

Remaining uncovered (~15%): OCR glyph synthesis (ncnn native lib
absent on this host), CameraX binding in CameraPreview, the OCR
text layer in PdfExporter, CropScreen's AutoFrameDetector coroutine
(ImageDecoder unimplemented under Robolectric), and the deepest
coroutine/gesture branches of SafePdfPageViewer.

Verified: gslot ./gradlew :pdf:testDevUnitTest (full suite green)
and :pdf:createMergedCoverageReport at 85.14%.
(cherry picked from commit 939f38771ab108068d44f62997d80d120361ef5a)

Diff

pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.kt
diff --git a/pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.kt b/pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.ktnew file mode 100644index 0000000000..41dad68880--- /dev/null+++ b/pdf/src/androidTest/java/com/vayunmathur/pdf/ui/PdfExporterDeviceTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.pdf.ui++import android.graphics.Bitmap+import android.graphics.Color+import android.net.Uri+import androidx.compose.ui.geometry.Rect+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.pdf.model.CapturedImage+import com.vayunmathur.pdf.model.Quadrilateral+import com.vayunmathur.pdf.util.ScanFilter+import com.vayunmathur.pdf.util.savePdfToUri+import com.vayunmathur.pdf.util.warpQuadToBitmap+import java.io.File+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * On-device exporter tests: the JVM/Robolectric PdfDocument cannot write a real+ * PDF stream and its ImageDecoder is unimplemented, so [savePdfToUri]'s page+ * rendering, scan filters and perspective warp are only honestly exercisable+ * here on the emulator.+ */+@RunWith(AndroidJUnit4::class)+class PdfExporterDeviceTest {++    private val ctx get() = InstrumentationRegistry.getInstrumentation().targetContext++    private fun pngFile(name: String, w: Int = 60, h: Int = 80): File {+        val f = File(ctx.cacheDir, name)+        f.outputStream().use {+            Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply {+                eraseColor(Color.WHITE)+                val canvas = android.graphics.Canvas(this)+                val paint = android.graphics.Paint().apply { color = Color.BLACK }+                canvas.drawRect(10f, 10f, 30f, 40f, paint)+            }.compress(Bitmap.CompressFormat.PNG, 100, it)+        }+        return f+    }++    @Test+    fun savePdfToUriWritesRealPdfForEachFilter() { runBlocking {+        val src = pngFile("page.png")+        for (filter in ScanFilter.entries) {+            val out = File(ctx.cacheDir, "out-$filter.pdf")+            val ok = savePdfToUri(ctx, listOf(CapturedImage(Uri.fromFile(src))), Uri.fromFile(out), filter)+            assertTrue("save with filter $filter should succeed", ok)+            assertTrue("out $filter should be non-empty", out.length() > 100)+            // Real PDF header+            assertEquals("%PDF", out.inputStream().use { String(it.readNBytes(4)) })+        }+    } }++    @Test+    fun savePdfToUriWithCropAndQuad() { runBlocking {+        val src = pngFile("page2.png", 100, 100)+        val out = File(ctx.cacheDir, "out-crop.pdf")+        val cropped = CapturedImage(Uri.fromFile(src), cropRect = Rect(0.1f, 0.1f, 0.9f, 0.9f))+        assertTrue(savePdfToUri(ctx, listOf(cropped), Uri.fromFile(out)))+        val quad = CapturedImage(Uri.fromFile(src), quadrilateral = Quadrilateral.default())+        val out2 = File(ctx.cacheDir, "out-quad.pdf")+        assertTrue(savePdfToUri(ctx, listOf(quad, cropped), Uri.fromFile(out2), ScanFilter.CONTRAST))+        assertTrue(out2.length() > 100)+    } }++    @Test+    fun savePdfToUriBadSourceFailsCleanly() { runBlocking {+        val out = File(ctx.cacheDir, "out-bad.pdf")+        val bad = savePdfToUri(ctx, listOf(CapturedImage(Uri.parse("content://missing/1"))), Uri.fromFile(out))+        assertFalse("no decodable pages must fail cleanly", bad)+        // OCR variant also degrades cleanly on this host+        savePdfToUri(ctx, listOf(CapturedImage(Uri.fromFile(pngFile("page3.png")))), Uri.fromFile(File(ctx.cacheDir, "out-ocr.pdf")), ScanFilter.NONE, addOcr = true)+    } }++    @Test+    fun warpQuadOnDevice() {+        val src = Bitmap.createBitmap(40, 40, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.BLUE) }+        val out = warpQuadToBitmap(src, Quadrilateral.default(), 20, 10)+        assertEquals(20, out.width); assertEquals(10, out.height)+        assertEquals(Color.BLUE, out.getPixel(5, 5))+        // Degenerate quad falls back to a bounding-box crop without crashing+        val flat = Quadrilateral(+            androidx.compose.ui.geometry.Offset(0.5f, 0.5f), androidx.compose.ui.geometry.Offset(0.5f, 0.5f),+            androidx.compose.ui.geometry.Offset(0.5f, 0.5f), androidx.compose.ui.geometry.Offset(0.5f, 0.5f),+        )+        val fallback = warpQuadToBitmap(src, flat, 10, 10)+        assertTrue(fallback.width >= 1 && fallback.height >= 1)+    }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/EditOverlayGesturesTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/EditOverlayGesturesTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/EditOverlayGesturesTest.ktnew file mode 100644index 0000000000..f5caffc746--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/EditOverlayGesturesTest.kt@@ -0,0 +1,233 @@+package com.vayunmathur.pdf.ui++import android.content.Context+import android.net.Uri+import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.test.click+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.pdf.util.SafeAnnotation+import com.vayunmathur.pdf.util.SafePdfDocument+import com.vayunmathur.pdf.util.addHighlight+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class EditOverlayGesturesTest {+    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun minimalPdf(): ByteArray {+        val content = "BT /F1 24 Tf 100 700 Td (Hello) Tj ET"+        val objs = listOf(+            "<< /Type /Catalog /Pages 2 0 R >>",+            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",+            "<< /Length ${content.length} >>\nstream\n$content\nendstream",+            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+        )+        val sb = StringBuilder("%PDF-1.4\n"); val offsets = mutableListOf<Int>()+        objs.forEachIndexed { i, body -> offsets.add(sb.length); sb.append("${i + 1} 0 obj\n$body\nendobj\n") }+        val xref = sb.length+        sb.append("xref\n0 ${objs.size + 1}\n0000000000 65535 f \n")+        offsets.forEach { sb.append(it.toString().padStart(10, '0')).append(" 00000 n \n") }+        sb.append("trailer\n<< /Size ${objs.size + 1} /Root 1 0 R >>\nstartxref\n$xref\n%%EOF")+        return sb.toString().toByteArray(Charsets.US_ASCII)+    }++    private fun openDoc(): SafePdfDocument = runBlocking {+        val f = File(ctx.cacheDir, "gest-${System.nanoTime()}.pdf"); f.writeBytes(minimalPdf())+        val doc = SafePdfDocument.open(ctx, Uri.fromFile(f))!!+        doc+    }++    private class Callbacks {+        var selected: Long? = -99L+        var created: Long = -1L+        var edited: Int = 0+        var movedId: Long? = null+        var startText: TextSession? = null+        var imageReq: Offset? = null+        var noteReq: Offset? = null+        var callout: Pair<Offset, Offset>? = null+        var polyPoint: Offset? = null+    }++    private class Harness(tool: EditTool, shape: ShapeKind = ShapeKind.RECT_OUTLINE, markup: MarkupKind = MarkupKind.HIGHLIGHT, annotations: List<SafeAnnotation> = emptyList(), selected: Long? = null) {+        var tool by mutableStateOf(tool)+        var shape by mutableStateOf(shape)+        var markup by mutableStateOf(markup)+        var annotations by mutableStateOf(annotations)+        var selected by mutableStateOf(selected)+    }++    private fun render(doc: SafePdfDocument, h: Harness, cb: Callbacks) {+        rule.setContent {+            DynamicTheme {+                Box(Modifier.size(300.dp)) {+                    EditOverlay(+                        annotations = h.annotations, selected = h.selected, tool = h.tool,+                        shape = h.shape, markup = h.markup, color = Color.Red, strokeWidth = 2f,+                        ch = 800f, scale = 1f, toPage = { it },+                        document = doc, index = 0, scope = CoroutineScope(Dispatchers.Default),+                        onSelect = { cb.selected = it }, onEdited = { cb.edited++ }, onCreated = { cb.created = it },+                        onMoved = { id, _, _ -> cb.movedId = id }, onStartText = { cb.startText = it },+                        onRequestImage = { cb.imageReq = it }, onRequestNote = { cb.noteReq = it },+                        onRequestCallout = { a, b -> cb.callout = a to b },+                        polyDraft = null, onAddPolyPoint = { cb.polyPoint = it },+                    )+                }+            }+        }+        rule.waitForIdle()+    }++    private fun switch(h: Harness, tool: EditTool? = null, shape: ShapeKind? = null, markup: MarkupKind? = null, annotations: List<SafeAnnotation>? = null, selected: Long? = -999L) {+        rule.runOnUiThread {+            if (tool != null) h.tool = tool+            if (shape != null) h.shape = shape+            if (markup != null) h.markup = markup+            if (annotations != null) h.annotations = annotations+            if (selected != -999L) h.selected = selected+        }+        rule.waitForIdle()+    }++    private suspend fun awaitAnnots(doc: SafePdfDocument, atLeast: Int) =+        withTimeout(8000) { while (doc.annotations(0).size < atLeast) delay(25) }++    private fun drag(from: Offset, to: Offset) {+        rule.onRoot().performTouchInput { swipe(from, to, 250) }+        rule.waitForIdle()+    }++    private fun tap(at: Offset) {+        rule.onRoot().performTouchInput { click(at) }+        rule.waitForIdle()+    }++    @Test fun highlightDragCreatesAnnotation() { runBlocking {+        val doc = openDoc(); val cb = Callbacks()+        try {+            render(doc, Harness(EditTool.HIGHLIGHT), cb)+            drag(Offset(60f, 60f), Offset(220f, 120f))+            awaitAnnots(doc, 1)+            assertTrue(cb.created != 0L && cb.created != -1L, "created=${cb.created}")+        } finally { doc.close() }+    } }++    @Test fun markupStrikeoutDragCreatesAnnotation() { runBlocking {+        val doc = openDoc(); val cb = Callbacks()+        try {+            render(doc, Harness(EditTool.MARKUP, markup = MarkupKind.STRIKEOUT), cb)+            drag(Offset(60f, 60f), Offset(220f, 120f))+            awaitAnnots(doc, 1); assertTrue(cb.created != 0L)+        } finally { doc.close() }+    } }++    @Test fun shapeDragsCreateRectOvalAndPolygon() { runBlocking {+        val doc = openDoc(); val cb = Callbacks()+        try {+            val h = Harness(EditTool.SHAPE, shape = ShapeKind.RECT_FILL); render(doc, h, cb)+            drag(Offset(50f, 50f), Offset(200f, 150f)); awaitAnnots(doc, 1)+            switch(h, shape = ShapeKind.OVAL_OUTLINE)+            drag(Offset(50f, 50f), Offset(200f, 150f)); awaitAnnots(doc, 2)+            switch(h, shape = ShapeKind.TRIANGLE_FILL)+            drag(Offset(50f, 50f), Offset(200f, 150f)); awaitAnnots(doc, 3)+        } finally { doc.close() }+    } }++    @Test fun lineRedactAndDrawDragsCreateAnnotations() { runBlocking {+        val doc = openDoc(); val cb = Callbacks()+        try {+            val h = Harness(EditTool.LINE); render(doc, h, cb)+            drag(Offset(50f, 80f), Offset(250f, 80f)); awaitAnnots(doc, 1)+            switch(h, tool = EditTool.REDACT)+            drag(Offset(50f, 50f), Offset(200f, 150f)); awaitAnnots(doc, 2)+            switch(h, tool = EditTool.DRAW)+            drag(Offset(50f, 50f), Offset(250f, 150f)); awaitAnnots(doc, 3)+        } finally { doc.close() }+    } }++    @Test fun calloutDragRequestsCallout() {+        val doc = openDoc(); val cb = Callbacks()+        try {+            render(doc, Harness(EditTool.CALLOUT), cb)+            drag(Offset(50f, 50f), Offset(200f, 150f))+            assertNotNull(cb.callout)+            assertEquals(Offset(50f, 50f), cb.callout!!.first)+        } finally { doc.close() }+    }++    @Test fun tapToolsRequestTheirActions() {+        val doc = openDoc(); val cb = Callbacks()+        try {+            val h = Harness(EditTool.TEXT); render(doc, h, cb); tap(Offset(80f, 80f))+            assertNotNull(cb.startText); assertEquals("Text", cb.startText!!.value.text); assertEquals(null, cb.startText!!.annotId)+            switch(h, tool = EditTool.IMAGE); tap(Offset(90f, 90f)); assertEquals(Offset(90f, 90f), cb.imageReq)+            switch(h, tool = EditTool.NOTE); tap(Offset(70f, 70f)); assertEquals(Offset(70f, 70f), cb.noteReq)+            switch(h, tool = EditTool.POLYLINE); tap(Offset(60f, 60f)); assertEquals(Offset(60f, 60f), cb.polyPoint)+            switch(h, tool = EditTool.BEZIER); tap(Offset(55f, 55f)); assertEquals(Offset(55f, 55f), cb.polyPoint)+        } finally { doc.close() }+    }++    @Test fun selectTapSelectsFreeTextEditAndEmptyDeselects() {+        val doc = openDoc(); val cb = Callbacks()+        val annots = listOf(+            SafeAnnotation(7L, 2, 50f, 50f, 250f, 150f, 0xFF000000.toInt(), "box"),+            SafeAnnotation(8L, 1, 160f, 160f, 280f, 195f, 0xFF000000.toInt(), "editable"),+        )+        try {+            val h = Harness(EditTool.SELECT, annotations = annots, selected = null); render(doc, h, cb)+            tap(Offset(100f, 100f)); assertEquals(7L, cb.selected)+            // Tap already-selected FreeText (subtype 1) starts a text edit+            switch(h, selected = 8L)+            tap(Offset(200f, 175f))+            assertNotNull(cb.startText); assertEquals(8L, cb.startText!!.annotId); assertEquals("editable", cb.startText!!.value.text)+            // Tap empty space deselects (the harness overlay occupies the 300dp box at the origin;+            // use a point inside it with no annotation)+            switch(h, selected = 7L)+            tap(Offset(20f, 280f)); assertEquals(null, cb.selected)+        } finally { doc.close() }+    }++    @Test fun selectDragMovesAnnotation() { runBlocking {+        val doc = openDoc(); val cb = Callbacks()+        try {+            val id = doc.addHighlight(0, 50f, 500f, 250f, 560f, 0xFFFFFF00.toInt())+            assertTrue(id != 0L)+            val id2 = doc.addHighlight(0, 50f, 50f, 250f, 150f, 0xFFFFFF00.toInt())+            val annots2 = doc.annotations(0)+            render(doc, Harness(EditTool.SELECT, annotations = annots2, selected = null), cb)+            drag(Offset(100f, 100f), Offset(160f, 130f))+            withTimeout(8000) { while (cb.movedId == null) delay(25) }+            assertTrue(cb.movedId == id || cb.movedId == id2, "moved=${cb.movedId} id=$id id2=$id2")+        } finally { doc.close() }+    } }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/LauncherFlowsTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/LauncherFlowsTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/LauncherFlowsTest.ktnew file mode 100644index 0000000000..6ee8eb562a--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/LauncherFlowsTest.kt@@ -0,0 +1,220 @@+package com.vayunmathur.pdf.ui++import android.app.Activity+import android.app.Application+import android.content.Context+import android.content.Intent+import android.graphics.Bitmap+import android.net.Uri+import androidx.activity.ComponentActivity+import androidx.activity.compose.LocalActivityResultRegistryOwner+import androidx.activity.result.ActivityResult+import androidx.activity.result.ActivityResultRegistry+import androidx.activity.result.ActivityResultRegistryOwner+import androidx.activity.result.contract.ActivityResultContract+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onFirst+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.onLast+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.printToLog+import androidx.compose.ui.unit.IntSize+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ocr.OcrEngine+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.pdf.util.PdfViewModel+import com.vayunmathur.pdf.util.SafePdfDocument+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class LauncherFlowsTest {+    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    /** Registry that immediately delivers [uri] for every contract, like a user picking that file. */+    private fun fakeOwner(uri: Uri): ActivityResultRegistryOwner {+        val realRegistry = object : ActivityResultRegistry() {+            override fun <I, O> onLaunch(+                requestCode: Int, contract: ActivityResultContract<I, O>, input: I,+                options: androidx.core.app.ActivityOptionsCompat?,+            ) {+                dispatchResult(requestCode, Activity.RESULT_OK, Intent().setData(uri))+            }+        }+        return object : ActivityResultRegistryOwner {+            override val activityResultRegistry: ActivityResultRegistry get() = realRegistry+        }+    }+++    /** Click the rightmost top-app-bar action (Save), avoiding bottom thumbnails/pickers. */+    private fun clickSaveAction() {+        val nodes = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes()+        val top = nodes.withIndex().filter { it.value.boundsInRoot.top < 80f }+        val target = top.maxByOrNull { it.value.boundsInRoot.left } ?: error("no top-bar actions")+        rule.onAllNodes(hasClickAction())[target.index].performClick()+        rule.waitForIdle()+    }++    private fun minimalPdfFile(name: String): File {+        val content = "BT /F1 24 Tf 100 700 Td (Hello) Tj ET"+        val objs = listOf(+            "<< /Type /Catalog /Pages 2 0 R >>",+            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",+            "<< /Length ${content.length} >>\nstream\n$content\nendstream",+            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+        )+        val sb = StringBuilder("%PDF-1.4\n"); val offsets = mutableListOf<Int>()+        objs.forEachIndexed { i, body -> offsets.add(sb.length); sb.append("${i + 1} 0 obj\n$body\nendobj\n") }+        val xref = sb.length+        sb.append("xref\n0 ${objs.size + 1}\n0000000000 65535 f \n")+        offsets.forEach { sb.append(it.toString().padStart(10, '0')).append(" 00000 n \n") }+        sb.append("trailer\n<< /Size ${objs.size + 1} /Root 1 0 R >>\nstartxref\n$xref\n%%EOF")+        return File(ctx.cacheDir, name).apply { writeBytes(sb.toString().toByteArray(Charsets.US_ASCII)) }+    }++    private fun pngFile(name: String): File {+        val f = File(ctx.cacheDir, name)+        f.outputStream().use { Bitmap.createBitmap(30, 30, Bitmap.Config.ARGB_8888).apply { eraseColor(android.graphics.Color.WHITE) }.compress(Bitmap.CompressFormat.PNG, 100, it) }+        return f+    }++    @Test fun cutGlueAppendPdfViaPickerThenSave() {+        val pdf = minimalPdfFile("picked.pdf")+        val outUri = Uri.fromFile(File(ctx.cacheDir, "composed-out.pdf"))+        // Picker delivers the pdf for OpenDocument; save delivers outUri for CreateDocument.+        // Both go through the same fake owner keyed by launch order is not possible, so use pdf uri+        // for append and verify the grid appears; save flow uses a second composition below.+        rule.setContent {+            CompositionLocalProvider(LocalActivityResultRegistryOwner provides fakeOwner(Uri.fromFile(pdf))) {+                DynamicTheme { CutGlueScreen(onBack = {}) }+            }+        }+        rule.onNodeWithText("Tap + to append a PDF or image").assertIsDisplayed()+        // FAB is the last click-action node; open the append menu+        rule.onAllNodes(hasClickAction()).onLast().performClick()+        rule.onNodeWithText("Append PDF").assertIsDisplayed().performClick()+        // After the picker callback appends, the empty hint disappears and the save action appears+        rule.waitUntil(timeoutMillis = 10_000) {+            rule.onAllNodes(hasText("Tap + to append a PDF or image")).fetchSemanticsNodes().isEmpty()+        }+        rule.waitForIdle()+        // Save action now exists in the top bar; clicking every click-action node in turn+        // hits it (back is a no-op here, the FAB reopens the menu harmlessly). The fake+        // registry delivers the same file Uri for CreateDocument, so the composed+        // document is written back over it by the Rust save.+        clickSaveAction()+        // Robolectric's ContentResolver cannot open an output stream for a file:// Uri,+        // so the save callback's write is swallowed by its runCatching; the launcher and+        // callback themselves have run (their coverage is the assertion available here),+        // and the appended page is still present.+        assertTrue(rule.onAllNodes(hasText("Tap + to append a PDF or image")).fetchSemanticsNodes().isEmpty())+    }++    @Test fun cutGlueAppendImageViaPicker() {+        val png = pngFile("picked.png")+        rule.setContent {+            CompositionLocalProvider(LocalActivityResultRegistryOwner provides fakeOwner(Uri.fromFile(png))) {+                DynamicTheme { CutGlueScreen(onBack = {}) }+            }+        }+        rule.onAllNodes(hasClickAction()).onLast().performClick()+        rule.onNodeWithText("Append image").assertIsDisplayed().performClick()+        rule.waitUntil(timeoutMillis = 10_000) {+            rule.onAllNodes(hasText("Tap + to append a PDF or image")).fetchSemanticsNodes().isEmpty()+        }+        rule.waitForIdle()+    }++    @Test fun captureGalleryPickOpensCrop() {+        val png = pngFile("gallery.png")+        val vm = PdfViewModel(ctx as Application)+        rule.setContent {+            CompositionLocalProvider(LocalActivityResultRegistryOwner provides fakeOwner(Uri.fromFile(png))) {+                DynamicTheme { CapturePdfScreen(vm, onBack = {}, onPdfCreated = {}) }+            }+        }+        rule.onNodeWithText("Upload Image").assertIsDisplayed().performClick()+        rule.waitUntil(timeoutMillis = 10_000) {+            vm.capturedImages.value.isNotEmpty()+        }+        assertEquals(1, vm.capturedImages.value.size)+        rule.waitForIdle()+        // Picking enters crop mode for the new image+        rule.onNodeWithText("Crop Image").assertIsDisplayed()+    }++    @Test fun captureSaveViaCreateDocument() {+        val png = pngFile("tosave.png")+        val out = File(ctx.cacheDir, "capture-out.pdf")+        val vm = PdfViewModel(ctx as Application)+        vm.addCapturedImage(Uri.fromFile(png))+        var created: Uri? = null+        rule.setContent {+            CompositionLocalProvider(LocalActivityResultRegistryOwner provides fakeOwner(Uri.fromFile(out))) {+                DynamicTheme { CapturePdfScreen(vm, onBack = {}, onPdfCreated = { created = it }) }+            }+        }+        rule.waitForIdle()+        // Top-bar click order: back, upload, more-options, save. Clicking Save runs+        // CreateDocument, whose fake result runs PdfViewModel.exportCapturedPdf and the+        // screen's result collector (under Robolectric the PDF write itself fails, so+        // onPdfCreated is not called and the image list stays intact).+        clickSaveAction()+        assertEquals(1, vm.capturedImages.value.size)+        assertEquals(null, created)+    }++    @Test fun pageViewerDoubleTapZoomAndScroll() { runBlocking {+        val pdf = minimalPdfFile("viewer-gesture.pdf")+        val doc = SafePdfDocument.open(ctx, Uri.fromFile(pdf))!!+        try {+            val state = SafePdfViewerState(kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined))+            state.pageCount = doc.pageCount+            val scroll = SafePdfScrollState()+            var zoomRef: SafePdfZoomState? = null+            val bundle = SafePdfDocumentBundle(LoadState.Loaded(doc), doc, emptyList(), false, OcrEngine(ctx))+            rule.setContent {+                DynamicTheme {+                    val (z, tr) = rememberSafePdfZoomState(scroll)+                    zoomRef = z+                    SafePdfPageViewer(+                        bundle = bundle, state = state, zoom = z, transform = tr, scroll = scroll,+                        launchers = SafePdfLauncherSet({}, {}, {}),+                    )+                }+            }+            rule.waitForIdle()+            // Double tap on the page area (root) triggers the zoom animation lambda+            rule.onRoot().performTouchInput {+                down(Offset(200f, 300f)); up()+                advanceEventTime(50)+                down(Offset(200f, 300f)); up()+            }+            rule.waitForIdle()+            // Vertical swipe scrolls the document+            rule.onRoot().performTouchInput {+                down(Offset(200f, 600f)); moveBy(Offset(200f, 300f)); up()+            }+            rule.waitForIdle()+            assertTrue(zoomRef!!.viewportSize != IntSize.Zero || scroll.viewportSize != IntSize.Zero)+        } finally { doc.close() }+    } }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/PageItemLoadedTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/PageItemLoadedTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/PageItemLoadedTest.ktnew file mode 100644index 0000000000..111ec6fb44--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/PageItemLoadedTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.pdf.ui++import android.content.Context+import android.net.Uri+import androidx.activity.ComponentActivity+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.pdf.util.SafePdfDocument+import java.io.File+import kotlin.test.Test+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class PageItemLoadedTest {+    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun minimalPdf(): ByteArray {+        val content = "BT /F1 24 Tf 100 700 Td (Hello) Tj ET"+        val objs = listOf(+            "<< /Type /Catalog /Pages 2 0 R >>",+            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",+            "<< /Length ${content.length} >>\nstream\n$content\nendstream",+            "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+        )+        val sb = StringBuilder("%PDF-1.4\n"); val offsets = mutableListOf<Int>()+        objs.forEachIndexed { i, body -> offsets.add(sb.length); sb.append("${i + 1} 0 obj\n$body\nendobj\n") }+        val xref = sb.length+        sb.append("xref\n0 ${objs.size + 1}\n0000000000 65535 f \n")+        offsets.forEach { sb.append(it.toString().padStart(10, '0')).append(" 00000 n \n") }+        sb.append("trailer\n<< /Size ${objs.size + 1} /Root 1 0 R >>\nstartxref\n$xref\n%%EOF")+        return sb.toString().toByteArray(Charsets.US_ASCII)+    }++    private fun openDoc(): SafePdfDocument = runBlocking {+        val f = File(ctx.cacheDir, "pageitem-${System.nanoTime()}.pdf"); f.writeBytes(minimalPdf())+        SafePdfDocument.open(ctx, Uri.fromFile(f))!!.also { it.renderPage(0) }+    }++    private fun renderItem(editMode: Boolean, tool: EditTool, onWidth: (Float) -> Unit) {+        val doc = openDoc()+        rule.setContent {+            DynamicTheme {+                SafePdfPageItem(+                    document = doc, index = 0, version = 0, ocr = null,+                    editMode = editMode, tool = tool, shape = ShapeKind.RECT_OUTLINE,+                    markup = MarkupKind.HIGHLIGHT, color = Color.Red, strokeWidth = 2f,+                    selected = null,+                    highlights = if (editMode) emptyList() else listOf(androidx.compose.ui.geometry.Rect(70f, 680f, 220f, 715f)),+                    currentHighlight = if (editMode) androidx.compose.ui.geometry.Rect(70f, 680f, 220f, 715f) else null,+                    scope = CoroutineScope(Dispatchers.Default),+                    onSelect = {}, onEdited = {}, onCreated = {}, onMoved = { _, _, _ -> },+                    onFormEdited = {}, onPageWidth = onWidth,+                    textSession = null, onStartText = {}, onTextChange = {},+                    onCommitText = {}, onRequestImage = {}, onRequestNote = {}, onRequestCallout = { _, _ -> },+                    polyDraft = null, onAddPolyPoint = {}, onLinkPage = {},+                )+            }+        }+        // Wait until the decoded page reports its width (proves the overlay slot composed)+        rule.waitUntil(timeoutMillis = 10_000) { widthSeen }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+        docRef = doc+    }++    private var widthSeen = false+    private var docRef: SafePdfDocument? = null++    @Test fun pageItemReadOnlyLoadedDrawsOverlays() {+        widthSeen = false+        renderItem(editMode = false, tool = EditTool.SELECT) { widthSeen = true }+        assertTrue(widthSeen)+        rule.onRoot().performTouchInput { swipe(centerLeft, centerRight, 200) }+        rule.waitForIdle()+        docRef?.close()+    }++    @Test fun pageItemEditLoadedDrawsOverlays() {+        widthSeen = false+        renderItem(editMode = true, tool = EditTool.DRAW) { widthSeen = true }+        assertTrue(widthSeen)+        rule.onRoot().performTouchInput { swipe(centerLeft, centerRight, 200) }+        rule.waitForIdle()+        docRef?.close()+    }++    @Test fun pageItemFailedPageShowsPlaceholder() {+        val doc = openDoc()+        widthSeen = false+        rule.setContent {+            DynamicTheme {+                SafePdfPageItem(+                    document = doc, index = 99, version = 0, ocr = null,+                    editMode = false, tool = EditTool.SELECT, shape = ShapeKind.RECT_OUTLINE,+                    markup = MarkupKind.HIGHLIGHT, color = Color.Red, strokeWidth = 2f,+                    selected = null, highlights = emptyList(), currentHighlight = null,+                    scope = CoroutineScope(Dispatchers.Default),+                    onSelect = {}, onEdited = {}, onCreated = {}, onMoved = { _, _, _ -> },+                    onFormEdited = {}, textSession = null, onStartText = {}, onTextChange = {},+                    onCommitText = {}, onRequestImage = {}, onRequestNote = {}, onRequestCallout = { _, _ -> },+                    polyDraft = null, onAddPolyPoint = {}, onLinkPage = {},+                )+            }+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+        doc.close()+    }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/TextSelectionGestureTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/TextSelectionGestureTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/TextSelectionGestureTest.ktnew file mode 100644index 0000000000..43a98a14c2--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/TextSelectionGestureTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.pdf.ui++import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.pdf.util.PdfPrimitive+import com.vayunmathur.pdf.util.SafePdfPage+import kotlin.test.Test+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class TextSelectionGestureTest {+    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++    // Page is 612x792; the layer box is 306dp square-ish so scale = boxPx/612 and+    // glyph (72,700) lands inside. ch is set from the measured box height in px.+    private fun renderLayer(): Pair<Offset, Float> {+        var boxPx = 0f+        val page = SafePdfPage(612f, 792f, listOf(+            PdfPrimitive.Text(Offset(72f, 700f), 16f, 0xFF000000.toInt(), "Hello selectable world"),+            PdfPrimitive.Text(Offset(72f, 650f), 16f, 0xFF000000.toInt(), "Second line of text here"),+        ))+        rule.setContent {+            val density = LocalDensity.current+            val px = with(density) { 400.dp.toPx() }+            boxPx = px+            DynamicTheme {+                Box(Modifier.size(400.dp)) {+                    // Scale by page HEIGHT so the 792pt page fits the square box:+                    // glyph baseline 700pt lands at px - 700*scale, inside the box.+                    TextSelectionLayer(page = page, ch = px, scale = px / 792f, ocr = null)+                }+            }+        }+        rule.waitForIdle()+        val scale = boxPx / 792f+        // Centre of the first glyph run: x ~ (72+40)pt, baseline y 700pt -> canvas y = px - 692*scale+        return Offset(112f * scale, boxPx - 692f * scale) to scale+    }++    @Test fun longPressSelectsWordThenDragExtendsAndTapDismisses() {+        val (centre, _) = renderLayer()+        // Long press: hold past the long-press timeout, then drag to extend+        rule.onRoot().performTouchInput {+            down(centre)+            advanceEventTime(800)+            moveBy(centre + Offset(120f, 0f))+            advanceEventTime(100)+            up()+        }+        rule.waitForIdle()+        // Settled selection should draw handles/highlight and show the toolbar effect+        rule.onRoot().captureToImage()+        rule.waitForIdle()+        // Drag the end handle: press near the selection end and move+        rule.onRoot().performTouchInput {+            down(centre + Offset(120f, 0f))+            moveBy(centre + Offset(180f, 0f))+            up()+        }+        rule.waitForIdle()+        // Quick tap dismisses+        rule.onRoot().performTouchInput { down(centre); up() }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun scrollGestureDoesNotSelect() {+        val (centre, _) = renderLayer()+        // Fast swipe is a scroll: no selection, no crash+        rule.onRoot().performTouchInput {+            down(centre)+            moveBy(centre + Offset(0f, -150f))+            up()+        }+        rule.waitForIdle()+        rule.onRoot().captureToImage()+    }++    @Test fun longPressFarFromGlyphSelectsNothing() {+        renderLayer()+        rule.onRoot().performTouchInput {+            down(Offset(10f, 10f))+            advanceEventTime(800)+            up()+        }+        rule.waitForIdle()+    }+}