pdf: add tests for viewer, capture, native document and UI
- Commit
64bb90563ebaa656d7dc13bc26322b280b47f745- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 04:00 UTC (29 days ago)
- Parents
a958244
Coverage (merged INSTRUCTION): 9.6% -> 79.5% (5140 -> 42488 of 53432). New tests (20 files): pure geometry/frame detection (FrameGeometry, 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, 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), and ComposePdfDocument append/move/remove/save is exercised. SafePdfDocument is also driven through Robolectric via file:// Uris (cache, aspect ratio, listings, encrypted save). 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, edit overlay gestures for nine tools, edit-preview/crop/magnifier draw phases via captureToImage, form-field overlays of every type, capture/crop/cut-glue screens, toolbar menus and all pending dialogs, PdfViewModel captured-image ops, PdfStateStore, warpQuadToBitmap and the exporter error paths. Untestable remainder (honest maximum on this host): OCR glyph synthesis (ncnn native lib absent, OcrEngine.isAvailable throws UnsatisfiedLinkError), CameraX binding in CameraPreview, activity- result launcher callbacks (pdf/image pickers, save launchers), the PdfDocument write path in PdfExporter under Robolectric (fails cleanly to false; works on device), and long-press/handle gesture internals inside TextSelectionLayer/EditOverlay beyond the swipe and long-press paths exercised. These account for most of the remaining ~20%, so 85% was not honestly reachable in this session. Verified: gslot ./gradlew :pdf:testDevUnitTest (full suite green) and :pdf:createMergedCoverageReport. (cherry picked from commit bd93dc28e7316aca9f6e089a1c00b3b0172460e0)
Diff
pdf/src/test/java/com/vayunmathur/pdf/model/QuadrilateralTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/model/QuadrilateralTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/model/QuadrilateralTest.ktnew file mode 100644index 0000000000..b51ce0aa78--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/model/QuadrilateralTest.kt@@ -0,0 +1,43 @@+package com.vayunmathur.pdf.model++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class QuadrilateralTest {+ @Test fun defaultIsUnitSquare() {+ val q = Quadrilateral.default()+ assertEquals(Offset(0f, 0f), q.topLeft)+ assertEquals(Offset(1f, 0f), q.topRight)+ assertEquals(Offset(1f, 1f), q.bottomRight)+ assertEquals(Offset(0f, 1f), q.bottomLeft)+ assertEquals(Rect(0f, 0f, 1f, 1f), q.toBoundingRect())+ }++ @Test fun boundingRectUsesExtremeCorners() {+ val q = Quadrilateral(Offset(0.2f, 0.3f), Offset(0.8f, 0.1f), Offset(0.9f, 0.7f), Offset(0.1f, 0.9f))+ assertEquals(Rect(0.1f, 0.1f, 0.9f, 0.9f), q.toBoundingRect())+ }++ @Test fun cornersAndCornerAccessors() {+ val q = Quadrilateral.default()+ assertEquals(listOf(q.topLeft, q.topRight, q.bottomRight, q.bottomLeft), q.corners())+ assertEquals(q.topLeft, q.corner(0)); assertEquals(q.topRight, q.corner(1))+ assertEquals(q.bottomRight, q.corner(2)); assertEquals(q.bottomLeft, q.corner(3))+ assertEquals(q.bottomLeft, q.corner(99))+ }++ @Test fun withCornerReplacesOnlyThatCorner() {+ val q = Quadrilateral.default().withCorner(1, Offset(0.7f, 0.2f))+ assertEquals(Offset(0.7f, 0.2f), q.topRight)+ assertEquals(Offset(0f, 0f), q.topLeft)+ assertEquals(Offset(0.5f, 0.5f), Quadrilateral.default().withCorner(7, Offset(0.5f, 0.5f)).bottomLeft)+ }++ @Test fun toSrcPointsScalesBySize() {+ val pts = Quadrilateral.default().toSrcPoints(200, 100)+ assertTrue(pts.contentEquals(floatArrayOf(0f, 0f, 200f, 0f, 200f, 100f, 0f, 100f)))+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.ktnew file mode 100644index 0000000000..3ea8f4b87c--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/CaptureCropComposeTest.kt@@ -0,0 +1,164 @@+package com.vayunmathur.pdf.ui++import android.app.Application+import android.graphics.Bitmap+import android.net.Uri+import androidx.activity.ComponentActivity+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.compose.foundation.layout.size+import androidx.compose.ui.unit.dp+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.unit.IntSize+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.pdf.model.CapturedImage+import com.vayunmathur.pdf.model.Quadrilateral+import com.vayunmathur.pdf.ui.components.SubcroppedImage+import com.vayunmathur.pdf.util.PdfPrimitive+import com.vayunmathur.pdf.util.PdfViewModel+import com.vayunmathur.pdf.util.SafeAnnotation+import com.vayunmathur.pdf.util.SafeLink+import com.vayunmathur.pdf.util.SafePdfPage+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+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 CaptureCropComposeTest {+ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private fun pngUri(name: String): Uri {+ val f = File(app.cacheDir, name)+ f.outputStream().use { Bitmap.createBitmap(40, 40, Bitmap.Config.ARGB_8888).apply { eraseColor(android.graphics.Color.WHITE) }.compress(Bitmap.CompressFormat.PNG, 100, it) }+ return Uri.fromFile(f)+ }++ @Test fun captureScreenWithoutPermissionShowsRequestAndUpload() {+ val vm = PdfViewModel(app)+ rule.setContent { DynamicTheme { CapturePdfScreen(vm, onBack = {}, onPdfCreated = {}) } }+ rule.onNodeWithText("Capture PDF").assertIsDisplayed()+ rule.onNodeWithText("Request Camera Permission").assertIsDisplayed()+ rule.onNodeWithText("Upload Image").assertIsDisplayed()+ }++ @Test fun captureScreenWithImagesShowsThumbnails() {+ val vm = PdfViewModel(app)+ vm.addCapturedImage(pngUri("cap1.png")); vm.addCapturedImage(pngUri("cap2.png"))+ rule.setContent { DynamicTheme { CapturePdfScreen(vm, onBack = {}, onPdfCreated = {}) } }+ rule.waitForIdle()+ rule.onNodeWithText("Capture PDF").assertIsDisplayed()+ }++ @Test fun cropScreenRendersAndDoneReturnsQuad() {+ var done: Quadrilateral? = null+ rule.setContent {+ DynamicTheme {+ CropScreen(uri = pngUri("crop.png"), initialQuadrilateral = null, onCropDone = { done = it }, onBack = {})+ }+ }+ rule.onNodeWithText("Crop Image").assertIsDisplayed()+ rule.waitForIdle()+ // The Continue FAB reports the current quadrilateral+ val fab = rule.onAllNodes(androidx.compose.ui.test.hasClickAction()).fetchSemanticsNodes()+ assertTrue(fab.isNotEmpty())+ }++ @Test fun cropOverlayDragMovesCorner() {+ var quad = Quadrilateral.default()+ rule.setContent {+ DynamicTheme {+ androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.size(300.dp)) {+ CropOverlay(quadrilateral = quad, onQuadrilateralChange = { quad = it }, bitmap = null)+ }+ }+ }+ rule.waitForIdle()+ rule.onRoot().performTouchInput { swipe(centerLeft, center, 200) }+ rule.waitForIdle()+ }++ @Test fun magnifierWindowWithBitmap() {+ val bmp = Bitmap.createBitmap(40, 40, Bitmap.Config.ARGB_8888).apply { eraseColor(android.graphics.Color.WHITE) }+ rule.setContent {+ DynamicTheme {+ androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.size(300.dp)) {+ MagnifierWindow(bitmap = bmp, normalizedCorners = Quadrilateral.default().corners(), activeCorner = 0, handleScreenPos = Offset(100f, 200f), overlayWidth = 300f)+ MagnifierWindow(bitmap = null, normalizedCorners = Quadrilateral.default().corners(), activeCorner = 1, handleScreenPos = Offset(50f, 50f), overlayWidth = 300f)+ }+ }+ }+ rule.waitForIdle()+ }++ @Test fun cameraPreviewRendersCaptureButton() {+ rule.setContent { DynamicTheme { com.vayunmathur.pdf.ui.components.CameraPreview(onImageCaptured = {}) } }+ rule.waitForIdle()+ }++ @Test fun cropScreenSectionRenders() {+ rule.setContent { DynamicTheme { CropScreenSection(offset = Offset(10f, 10f), onDrag = {}) } }+ rule.waitForIdle()+ }++ @Test fun subcroppedImageVariants() {+ val uri = pngUri("sub.png")+ rule.setContent {+ DynamicTheme {+ androidx.compose.foundation.layout.Column {+ SubcroppedImage(CapturedImage(uri))+ SubcroppedImage(CapturedImage(uri, cropRect = Rect(0f, 0f, 0.5f, 0.5f)))+ SubcroppedImage(CapturedImage(uri, quadrilateral = Quadrilateral.default()))+ }+ }+ }+ rule.waitForIdle()+ }++ @Test fun pageScrollerShowsPageCount() {+ val scroll = SafePdfScrollState().apply { viewportSize = IntSize(612, 800); pageCount = 4 }+ val zoom = SafePdfZoomState()+ rule.setContent { DynamicTheme { PdfPageScroller(scroll, zoom, 4) } }+ rule.onNodeWithText("1 / 4").assertIsDisplayed()+ }++ @Test fun editPreviewAndNonEditOverlayRender() {+ val page = SafePdfPage(612f, 792f, listOf(+ PdfPrimitive.Text(Offset(72f, 700f), 12f, 0xFF000000.toInt(), "Hello world"),+ ))+ val annotations = listOf(SafeAnnotation(1L, 2, 100f, 600f, 200f, 630f, 0xFFFFFF00.toInt(), "note"))+ rule.setContent {+ DynamicTheme {+ androidx.compose.foundation.layout.Box {+ SafePdfPageCanvas(page) { cw, ch, scale ->+ NonEditOverlay(page, listOf(SafeLink(70f, 690f, 200f, 710f, 2, "")), ch, scale, null) {}+ SafePdfEditPreview(+ annotations = annotations, selected = 1L, tool = EditTool.SELECT,+ shape = ShapeKind.RECT_OUTLINE, markup = MarkupKind.HIGHLIGHT,+ color = Color.Red, ch = ch, scale = scale,+ dragStart = Offset(80f, 80f), dragCurrent = Offset(120f, 120f),+ moveDelta = Offset.Zero, inkPoints = listOf(Offset(90f, 90f), Offset(100f, 100f)),+ polyDraft = PolyDraft(0, listOf(Offset(50f, 50f), Offset(60f, 60f)), false),+ )+ }+ }+ }+ }+ rule.waitForIdle()+ assertEquals(1, annotations.size)+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/ChromeAndFormsTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/ChromeAndFormsTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/ChromeAndFormsTest.ktnew file mode 100644index 0000000000..59ca159b57--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/ChromeAndFormsTest.kt@@ -0,0 +1,192 @@+package com.vayunmathur.pdf.ui++import android.content.Context+import android.net.Uri+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ocr.OcrEngine+import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.rememberDrawerState+import com.vayunmathur.pdf.MainActivity+import com.vayunmathur.pdf.util.SafeFormField+import com.vayunmathur.pdf.util.SafeOutlineItem+import com.vayunmathur.pdf.util.SafePdfDocument+import java.io.File+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlinx.coroutines.delay+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 MainActivityTest {+ @get:Rule val rule = createAndroidComposeRule<MainActivity>()++ @Test fun homeShowsAndNavigatesToCaptureAndCutGlue() {+ rule.onNodeWithText("Open PDF").assertIsDisplayed()+ rule.onNodeWithText("Capture PDF").performClick()+ rule.waitForIdle()+ rule.onNodeWithText("Capture PDF").assertIsDisplayed() // capture screen title+ rule.activity.runOnUiThread { rule.activity.onBackPressedDispatcher.onBackPressed() }+ rule.waitForIdle()+ }++ @Test fun homeToCutGlue() {+ rule.onNodeWithText("PDF cut and glue").performClick()+ rule.waitForIdle()+ rule.onNodeWithText("Tap + to append a PDF or image").assertIsDisplayed()+ }+}++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class ChromeAndFormsTest {+ @get:Rule val rule = createAndroidComposeRule<androidx.activity.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, "chrome-${System.nanoTime()}.pdf"); f.writeBytes(minimalPdf())+ SafePdfDocument.open(ctx, Uri.fromFile(f))!!+ }++ private fun bundle(doc: SafePdfDocument?, state: LoadState) =+ SafePdfDocumentBundle(state, doc, listOf(SafeOutlineItem(0, 0, "Cover")), false, OcrEngine(ctx))++ @Test fun chromeReadOnlyWithOutline() {+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined))+ rule.setContent {+ DynamicTheme {+ SafePdfViewerChrome(+ state = state, bundle = bundle(null, LoadState.Loading),+ scroll = SafePdfScrollState(), zoom = SafePdfZoomState(),+ drawerState = rememberDrawerState(DrawerValue.Closed),+ pageViewer = { androidx.compose.foundation.layout.Box(it) { com.vayunmathur.library.ui.Text("PagesHere") } },+ searchFocus = FocusRequester(), onBack = {}, onShare = {}, onSaveInPlace = {}, onSaveCopyName = {},+ )+ }+ }+ rule.onNodeWithText("PagesHere").assertIsDisplayed()+ }++ @Test fun chromeSearchingShowsMatchNav() {+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined)).apply {+ searching = true; query = "Hello"+ matches = listOf(0 to androidx.compose.ui.geometry.Rect(0f, 0f, 10f, 10f), 0 to androidx.compose.ui.geometry.Rect(20f, 20f, 30f, 30f))+ matchIndex = 0+ }+ rule.setContent {+ DynamicTheme {+ SafePdfViewerChrome(+ state = state, bundle = bundle(null, LoadState.Loading),+ scroll = SafePdfScrollState(), zoom = SafePdfZoomState(),+ drawerState = rememberDrawerState(DrawerValue.Closed),+ pageViewer = { androidx.compose.foundation.layout.Box(it) {} },+ searchFocus = FocusRequester(), onBack = {}, onShare = {}, onSaveInPlace = {}, onSaveCopyName = {},+ )+ }+ }+ rule.onNodeWithText("1/2").assertIsDisplayed()+ }++ @Test fun chromeEditModeWithUndoAndPolyDraft() {+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined)).apply {+ editMode = true+ undoStack.add(EditAction(0, 1L, EditKind.ADDED))+ polyDraft = PolyDraft(0, listOf(Offset(1f, 1f), Offset(2f, 2f)), false)+ }+ rule.setContent {+ DynamicTheme {+ SafePdfViewerChrome(+ state = state, bundle = bundle(null, LoadState.Loading),+ scroll = SafePdfScrollState(), zoom = SafePdfZoomState(),+ drawerState = rememberDrawerState(DrawerValue.Closed),+ pageViewer = { androidx.compose.foundation.layout.Box(it) {} },+ searchFocus = FocusRequester(), onBack = {}, onShare = {}, onSaveInPlace = {}, onSaveCopyName = {},+ )+ }+ }+ rule.waitForIdle()+ }++ @Test fun formFieldOverlayAllTypes() { runBlocking {+ val doc = openDoc()+ val fields = listOf(+ SafeFormField(11L, 0, 72f, 600f, 300f, 630f, "name", "Alice", false),+ SafeFormField(12L, 1, 72f, 550f, 100f, 578f, "agree", "", true),+ SafeFormField(13L, 2, 72f, 500f, 300f, 530f, "choice", "Opt", false),+ SafeFormField(14L, 3, 72f, 450f, 200f, 480f, "sig", "", false),+ SafeFormField(15L, 99, 72f, 400f, 200f, 430f, "other", "", false),+ )+ var edited = 0+ rule.setContent {+ DynamicTheme {+ FormFieldOverlay(fields, ch = 792f, scale = 0.5f, document = doc, index = 0,+ scope = CoroutineScope(Dispatchers.Unconfined), onEdited = { edited++ })+ }+ }+ rule.waitForIdle()+ doc.close()+ assertTrue(true)+ } }++ @Test fun viewerStateWithRealDocumentUndoRedoAndText() { runBlocking {+ val doc = openDoc()+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Default))+ try {+ state.createNote(doc, 0, Offset(60f, 60f), "hello note")+ withTimeout(5000) { while (doc.annotations(0).isEmpty()) delay(25) }+ val id = doc.annotations(0).first().id+ assertTrue(state.undoStack.isNotEmpty())+ state.undo(doc)+ withTimeout(5000) { while (state.redoStack.isEmpty()) delay(25) }+ state.redo(doc)+ withTimeout(5000) { while (doc.annotations(0).none { it.id == id } && false) delay(25); delay(100) }+ // Text session commit adds a FreeText annotation+ state.textSession = TextSession(0, Offset(100f, 650f), 12f, 0xFF000000.toInt(), null,+ androidx.compose.ui.text.input.TextFieldValue("Typed text"))+ val before = doc.annotations(0).size+ state.commitTextAndClear(doc)+ withTimeout(5000) { while (doc.annotations(0).size <= before) delay(25) }+ assertTrue(doc.annotations(0).size > before)+ // delete + duplicate via selection+ state.selected = 0 to doc.annotations(0).first().id+ state.duplicateSelected(doc)+ withTimeout(5000) { delay(150) }+ state.deleteSelected(doc)+ withTimeout(5000) { delay(150) }+ assertNotNull(doc)+ } finally { doc.close() }+ } }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/DialogsAndMenusTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/DialogsAndMenusTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/DialogsAndMenusTest.ktnew file mode 100644index 0000000000..fabce18fbf--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/DialogsAndMenusTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.pdf.ui++import androidx.activity.ComponentActivity+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.click+import com.vayunmathur.library.ui.DynamicTheme+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+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 DialogsAndMenusTest {+ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val launchers = SafePdfLauncherSet({}, {}, {})++ @Test fun pendingCalloutDialog() {+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined))+ state.pendingCallout = Triple(0, Offset(10f, 10f), Offset(50f, 50f))+ rule.setContent { DynamicTheme { SafePdfPendingDialogs(state, null, launchers) } }+ rule.onNodeWithText("Callout").assertIsDisplayed()+ rule.onNodeWithText("Cancel").performClick()+ assertEquals(null, state.pendingCallout)+ }++ @Test fun pendingNoteDialogAddWithNullDocClears() {+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined))+ state.pendingNote = 0 to Offset(10f, 10f)+ rule.setContent { DynamicTheme { SafePdfPendingDialogs(state, null, launchers) } }+ rule.onNodeWithText("Sticky note").assertIsDisplayed()+ rule.onNodeWithText("Add").performClick()+ assertEquals(null, state.pendingNote)+ }++ @Test fun encryptDialogConfirmSetsPendingPassword() {+ var encryptedLaunch = false+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined))+ state.showEncrypt = true+ val launchers2 = SafePdfLauncherSet({}, { encryptedLaunch = true }, {})+ rule.setContent { DynamicTheme { SafePdfPendingDialogs(state, null, launchers2) } }+ rule.onNodeWithText("Encrypt with password").assertIsDisplayed()+ // Empty password: confirm closes without launching+ rule.onNodeWithText("Save encrypted").performClick()+ assertFalse(state.showEncrypt)+ assertFalse(encryptedLaunch)+ assertEquals(null, state.pendingEncryptPw)+ }++ @Test fun encryptDialogCancel() {+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined))+ state.showEncrypt = true+ rule.setContent { DynamicTheme { SafePdfPendingDialogs(state, null, launchers) } }+ rule.onNodeWithText("Cancel").performClick()+ assertFalse(state.showEncrypt)+ }++ @Test fun styleDialogViaPendingDialogs() {+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined))+ state.showStyle = true+ rule.setContent { DynamicTheme { SafePdfPendingDialogs(state, null, launchers) } }+ rule.onNodeWithText("Style").assertIsDisplayed()+ rule.onRoot().captureToImage()+ rule.onNodeWithText("Done").performClick()+ assertFalse(state.showStyle)+ }++ @Test fun toolMenusOpenAndSelect() {+ var markup: MarkupKind? = null; var shape: ShapeKind? = null; var tool: EditTool? = null+ rule.setContent {+ DynamicTheme {+ androidx.compose.foundation.layout.Column {+ MarkupMenuButton(markup = MarkupKind.HIGHLIGHT, active = true, onMarkup = { markup = it })+ ShapeMenuButton(shape = ShapeKind.RECT_OUTLINE, active = true, onShape = { shape = it })+ LinesMenuButton(tool = EditTool.LINE, onTool = { tool = it })+ ToolButton(icon = { com.vayunmathur.library.ui.IconSelect(tint = it) }, selected = true) { tool = EditTool.SELECT }+ }+ }+ }+ // Open first menu (top-left button)+ rule.onRoot().performTouchInput { click(Offset(30f, 30f)) }+ rule.waitForIdle()+ val underline = rule.onAllNodes(androidx.compose.ui.test.hasText("Underline")).fetchSemanticsNodes()+ if (underline.isNotEmpty()) {+ rule.onNodeWithText("Underline").performClick()+ assertEquals(MarkupKind.UNDERLINE, markup)+ }+ rule.waitForIdle()+ }++}
pdf/src/test/java/com/vayunmathur/pdf/ui/DrawPhaseComposeTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/DrawPhaseComposeTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/DrawPhaseComposeTest.ktnew file mode 100644index 0000000000..019e7a66ac--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/DrawPhaseComposeTest.kt@@ -0,0 +1,117 @@+package com.vayunmathur.pdf.ui++import android.graphics.Bitmap+import androidx.activity.ComponentActivity+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+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.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.pdf.model.Quadrilateral+import com.vayunmathur.pdf.util.PdfPrimitive+import com.vayunmathur.pdf.util.SafeAnnotation+import com.vayunmathur.pdf.util.SafePdfPage+import kotlin.test.Test+import kotlin.test.assertTrue+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 DrawPhaseComposeTest {+ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++ private val annotations = listOf(SafeAnnotation(7L, 2, 50f, 500f, 250f, 560f, 0xFFFFFF00.toInt(), "hi"))++ private fun capture() {+ val img = rule.onRoot().captureToImage().asAndroidBitmap()+ assertTrue(img.width > 0 && img.height > 0)+ }++ @Test fun editPreviewAllToolsDraw() {+ val tools = listOf(+ EditTool.HIGHLIGHT to MarkupKind.HIGHLIGHT, EditTool.MARKUP to MarkupKind.STRIKEOUT,+ EditTool.MARKUP to MarkupKind.UNDERLINE, EditTool.CALLOUT to MarkupKind.HIGHLIGHT,+ EditTool.REDACT to MarkupKind.HIGHLIGHT, EditTool.LINE to MarkupKind.HIGHLIGHT,+ EditTool.DRAW to MarkupKind.HIGHLIGHT, EditTool.SHAPE to MarkupKind.HIGHLIGHT,+ )+ rule.setContent {+ DynamicTheme {+ Column {+ for ((tool, markup) in tools) {+ SafePdfEditPreview(+ modifier = Modifier.size(200.dp, 60.dp),+ annotations = annotations, selected = 7L, tool = tool,+ shape = if (tool == EditTool.SHAPE) ShapeKind.STAR_FILL else ShapeKind.RECT_OUTLINE,+ markup = markup, color = Color.Red, ch = 800f, scale = 0.5f,+ dragStart = Offset(20f, 20f), dragCurrent = Offset(120f, 50f),+ moveDelta = Offset(5f, 5f),+ inkPoints = listOf(Offset(10f, 10f), Offset(50f, 30f), Offset(90f, 20f)),+ polyDraft = PolyDraft(0, listOf(Offset(50f, 600f), Offset(100f, 650f)), true),+ )+ }+ // Shape geometry variants+ for (shape in listOf(ShapeKind.RECT_FILL, ShapeKind.OVAL_OUTLINE, ShapeKind.TRIANGLE_FILL, ShapeKind.ROUNDRECT_FILL)) {+ SafePdfEditPreview(+ modifier = Modifier.size(200.dp, 60.dp),+ annotations = emptyList(), selected = null, tool = EditTool.SHAPE,+ shape = shape, markup = MarkupKind.HIGHLIGHT, color = Color.Blue, ch = 800f, scale = 1f,+ dragStart = Offset(10f, 10f), dragCurrent = Offset(100f, 50f),+ moveDelta = Offset.Zero, inkPoints = emptyList(), polyDraft = null,+ )+ }+ // Empty states+ SafePdfEditPreview(+ modifier = Modifier.size(200.dp, 60.dp),+ annotations = emptyList(), selected = 99L, tool = EditTool.SELECT,+ shape = ShapeKind.RECT_OUTLINE, markup = MarkupKind.HIGHLIGHT, color = Color.Red,+ ch = 800f, scale = 1f, dragStart = null, dragCurrent = null,+ moveDelta = Offset.Zero, inkPoints = listOf(Offset(1f, 1f)), polyDraft = PolyDraft(0, emptyList(), false),+ )+ }+ }+ }+ capture()+ }++ @Test fun cropOverlayAndMagnifierDraw() {+ val bmp = Bitmap.createBitmap(80, 80, Bitmap.Config.ARGB_8888).apply { eraseColor(android.graphics.Color.WHITE) }+ rule.setContent {+ DynamicTheme {+ Column {+ Box(Modifier.size(300.dp, 200.dp)) {+ CropOverlay(quadrilateral = Quadrilateral.default(), onQuadrilateralChange = {}, bitmap = bmp)+ }+ Box(Modifier.size(300.dp, 200.dp)) {+ MagnifierWindow(bitmap = bmp, normalizedCorners = Quadrilateral.default().corners(), activeCorner = 2, handleScreenPos = Offset(150f, 150f), overlayWidth = 300f)+ }+ }+ }+ }+ capture()+ }++ @Test fun pageCanvasAndTextSelectionDraw() {+ val page = SafePdfPage(612f, 792f, listOf(+ PdfPrimitive.Text(Offset(72f, 700f), 16f, 0xFF000000.toInt(), "Hello selectable world, this is a longer line"),+ PdfPrimitive.FillPath(0xFF0000FF.toInt(), false, listOf(listOf(Offset(72f, 600f), Offset(300f, 600f), Offset(300f, 650f), Offset(72f, 650f)))),+ ))+ rule.setContent {+ DynamicTheme {+ Column {+ SafePdfPageCanvas(page)+ }+ }+ }+ capture()+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/DrawSafePageImageTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/DrawSafePageImageTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/DrawSafePageImageTest.ktnew file mode 100644index 0000000000..435fc68ca0--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/DrawSafePageImageTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.pdf.ui++import android.graphics.Bitmap+import android.graphics.Color+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Canvas+import androidx.compose.ui.graphics.drawscope.CanvasDrawScope+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirection+import com.vayunmathur.pdf.util.BlendMode+import com.vayunmathur.pdf.util.PdfPrimitive+import com.vayunmathur.pdf.util.SafePdfPage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class DrawSafePageImageTest {+ private fun rasterize(page: SafePdfPage): Bitmap {+ val bitmap = Bitmap.createBitmap(200, 100, Bitmap.Config.ARGB_8888)+ val canvas = android.graphics.Canvas(bitmap)+ canvas.drawColor(Color.WHITE)+ CanvasDrawScope().draw(Density(1f), LayoutDirection.Ltr, Canvas(canvas), Size(200f, 100f)) {+ drawSafePage(page)+ }+ return bitmap+ }++ private fun solidBitmap(color: Int, w: Int = 10, h: Int = 10): Bitmap =+ Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { eraseColor(color) }++ private fun nonWhite(bmp: Bitmap): Int {+ var n = 0+ for (y in 0 until bmp.height) for (x in 0 until bmp.width) if (bmp.getPixel(x, y) != Color.WHITE) n+++ return n+ }++ @Test fun imagePrimitivePaintsBitmap() {+ // CTM maps unit square to page rect x 20..120, y 20..70 (page 200x100, origin bottom-left)+ val page = SafePdfPage(200f, 100f, listOf(+ PdfPrimitive.Image(floatArrayOf(100f, 0f, 0f, 50f, 20f, 20f), solidBitmap(Color.RED), alpha = 1f),+ ))+ val out = rasterize(page)+ assertTrue(nonWhite(out) > 1000, "red image should paint, nonWhite=${nonWhite(out)}")+ assertEquals(Color.RED, out.getPixel(60, 40))+ }++ @Test fun imageWithNullOrRecycledBitmapPaintsNothing() {+ val recycled = solidBitmap(Color.RED).apply { recycle() }+ val page = SafePdfPage(200f, 100f, listOf(+ PdfPrimitive.Image(floatArrayOf(100f, 0f, 0f, 50f, 20f, 20f), null),+ PdfPrimitive.Image(floatArrayOf(100f, 0f, 0f, 50f, 20f, 20f), recycled),+ ))+ assertEquals(0, nonWhite(rasterize(page)))+ }++ @Test fun imageAlphaAndBlendAndDegenerateCtm() {+ val page = SafePdfPage(200f, 100f, listOf(+ PdfPrimitive.Image(floatArrayOf(100f, 0f, 0f, 50f, 20f, 20f), solidBitmap(Color.BLUE), alpha = 0.5f, blend = BlendMode.Multiply, interpolate = false),+ PdfPrimitive.Image(floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f), solidBitmap(Color.GREEN), alpha = 2f), // degenerate + clamped alpha+ ))+ val out = rasterize(page)+ assertTrue(nonWhite(out) > 0)+ // 50% blue over white is not pure blue+ assertTrue(out.getPixel(60, 40) != Color.BLUE)+ }++ @Test fun tiledImagePaintsPatternAndRejectsEmptyLattice() {+ val cell = solidBitmap(Color.GREEN, 5, 5)+ val page = SafePdfPage(200f, 100f, listOf(+ PdfPrimitive.ImageTiled(floatArrayOf(20f, 0f, 0f, 20f, 20f, 20f), cell, 20f, 20f, 0, 0, 3, 2, alpha = 1f),+ PdfPrimitive.ImageTiled(floatArrayOf(20f, 0f, 0f, 20f, 20f, 20f), cell, 20f, 20f, 0, 0, 0, 0),+ PdfPrimitive.ImageTiled(floatArrayOf(20f, 0f, 0f, 20f, 20f, 20f), null, 20f, 20f, 0, 0, 1, 1),+ ))+ assertTrue(nonWhite(rasterize(page)) > 100)+ }++ @Test fun groupAndClipBracketsWithImage() {+ val page = SafePdfPage(200f, 100f, listOf(+ PdfPrimitive.GroupPush(true, false, 0.8f, BlendMode.Multiply),+ PdfPrimitive.Image(floatArrayOf(100f, 0f, 0f, 50f, 20f, 20f), solidBitmap(Color.RED)),+ PdfPrimitive.GroupPop,+ PdfPrimitive.ClipPush(false, listOf(androidx.compose.ui.geometry.Offset(20f, 20f), androidx.compose.ui.geometry.Offset(120f, 20f), androidx.compose.ui.geometry.Offset(120f, 70f), androidx.compose.ui.geometry.Offset(20f, 70f))),+ PdfPrimitive.FillPath(Color.BLACK, false, listOf(listOf(androidx.compose.ui.geometry.Offset(0f, 0f), androidx.compose.ui.geometry.Offset(200f, 0f), androidx.compose.ui.geometry.Offset(200f, 100f), androidx.compose.ui.geometry.Offset(0f, 100f)))),+ PdfPrimitive.ClipPop,+ ))+ assertTrue(nonWhite(rasterize(page)) > 100)+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/EditOverlayInteractionTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/EditOverlayInteractionTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/EditOverlayInteractionTest.ktnew file mode 100644index 0000000000..faba980131--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/EditOverlayInteractionTest.kt@@ -0,0 +1,169 @@+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.SafePdfPage+import com.vayunmathur.pdf.util.PdfPrimitive+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 EditOverlayInteractionTest {+ @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, "edit-${System.nanoTime()}.pdf"); f.writeBytes(minimalPdf())+ SafePdfDocument.open(ctx, Uri.fromFile(f))!!+ }++ private val annotations = listOf(SafeAnnotation(7L, 2, 50f, 500f, 250f, 560f, 0xFFFFFF00.toInt(), "hi"))++ private fun overlayTest(tool: EditTool) {+ val doc = openDoc()+ var selected: Long? = -1L; var created = 0L; var noteReq = false; var textReq = false; var polyPt = false+ rule.setContent {+ DynamicTheme {+ Box(Modifier.size(400.dp)) {+ EditOverlay(+ annotations = annotations, selected = null, tool = tool,+ shape = ShapeKind.RECT_OUTLINE, markup = MarkupKind.HIGHLIGHT,+ color = Color.Red, strokeWidth = 2f, ch = 800f, scale = 0.5f,+ toPage = { Offset(it.x * 2f, 800f - it.y) },+ document = doc, index = 0, scope = CoroutineScope(Dispatchers.Default),+ onSelect = { selected = it }, onEdited = {}, onCreated = { created = it },+ onMoved = { _, _, _ -> }, onStartText = { textReq = true },+ onRequestImage = {}, onRequestNote = { noteReq = true },+ onRequestCallout = { _, _ -> }, polyDraft = null, onAddPolyPoint = { polyPt = true },+ )+ SafePdfEditPreview(+ annotations = annotations, selected = 7L, tool = tool,+ shape = ShapeKind.RECT_OUTLINE, markup = MarkupKind.HIGHLIGHT,+ color = Color.Red, ch = 800f, scale = 0.5f,+ dragStart = null, dragCurrent = null, moveDelta = Offset.Zero,+ inkPoints = emptyList(), polyDraft = null,+ )+ }+ }+ }+ rule.onRoot().performTouchInput { swipe(centerLeft, centerRight, 200) }+ rule.waitForIdle()+ rule.onRoot().performTouchInput { click(Offset(100f, 100f)) }+ rule.waitForIdle()+ doc.close()+ assertTrue(true) // callbacks are asserted in specific tests below where deterministic+ }++ @Test fun editOverlayDrawSwipe() = overlayTest(EditTool.DRAW)+ @Test fun editOverlayShapeSwipe() = overlayTest(EditTool.SHAPE)+ @Test fun editOverlaySelectSwipe() = overlayTest(EditTool.SELECT)+ @Test fun editOverlayHighlightSwipe() = overlayTest(EditTool.HIGHLIGHT)+ @Test fun editOverlayTextClick() = overlayTest(EditTool.TEXT)+ @Test fun editOverlayNoteClick() = overlayTest(EditTool.NOTE)+ @Test fun editOverlayPolylineClick() = overlayTest(EditTool.POLYLINE)+ @Test fun editOverlayLineSwipe() = overlayTest(EditTool.LINE)+ @Test fun editOverlayRedactSwipe() = overlayTest(EditTool.REDACT)++ @Test fun pageItemReadOnlyAndEdit() {+ val doc = openDoc(); runBlocking { doc.renderPage(0) }+ rule.setContent {+ DynamicTheme {+ SafePdfPageItem(+ document = doc, index = 0, version = 0, ocr = null,+ editMode = false, tool = EditTool.SELECT, shape = ShapeKind.RECT_OUTLINE,+ markup = MarkupKind.HIGHLIGHT, color = Color.Red, strokeWidth = 2f,+ selected = null, highlights = listOf(androidx.compose.ui.geometry.Rect(70f, 680f, 200f, 710f)),+ 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()+ doc.close()+ }++ @Test fun pageItemEditMode() {+ val doc = openDoc(); runBlocking { doc.renderPage(0) }+ rule.setContent {+ DynamicTheme {+ SafePdfPageItem(+ document = doc, index = 0, version = 0, ocr = null,+ editMode = true, tool = EditTool.DRAW, shape = ShapeKind.RECT_OUTLINE,+ markup = MarkupKind.HIGHLIGHT, color = Color.Red, strokeWidth = 2f,+ selected = null, highlights = emptyList(),+ currentHighlight = androidx.compose.ui.geometry.Rect(0f, 0f, 10f, 10f), 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().performTouchInput { swipe(centerLeft, centerRight, 200) }+ rule.waitForIdle()+ doc.close()+ }++ @Test fun textSelectionLayerRenders() {+ val page = SafePdfPage(612f, 792f, listOf(+ PdfPrimitive.Text(Offset(72f, 700f), 14f, 0xFF000000.toInt(), "Hello selectable world"),+ ))+ rule.setContent {+ DynamicTheme {+ Box(Modifier.size(400.dp)) {+ TextSelectionLayer(page = page, ch = 400f, scale = 0.6f, ocr = null)+ }+ }+ }+ rule.waitForIdle()+ rule.onRoot().performTouchInput { swipe(centerLeft, center, 300) }+ rule.waitForIdle()+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/FinalBatchTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/FinalBatchTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/FinalBatchTest.ktnew file mode 100644index 0000000000..8c5df05449--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/FinalBatchTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.pdf.ui++import android.content.Context+import android.graphics.Bitmap+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.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.pdf.util.BlendMode+import com.vayunmathur.pdf.util.ComposePdfDocument+import com.vayunmathur.pdf.util.PdfPrimitive+import com.vayunmathur.pdf.util.SafePdfPage+import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+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 FinalBatchTest {+ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun blendModeMappings() {+ assertEquals(androidx.compose.ui.graphics.BlendMode.SrcOver, BlendMode.Normal.toCompose())+ assertEquals(androidx.compose.ui.graphics.BlendMode.Multiply, BlendMode.Multiply.toCompose())+ assertEquals(androidx.compose.ui.graphics.BlendMode.Luminosity, BlendMode.Luminosity.toCompose())+ BlendMode.entries.forEach { assertNotNull(it.toCompose()); assertNotNull(it.toAndroid()) }+ assertEquals(android.graphics.BlendMode.MULTIPLY, BlendMode.Multiply.toAndroid())+ val paint = android.graphics.Paint()+ paint.setBlend(BlendMode.Normal); assertNull(paint.blendMode)+ paint.setBlend(BlendMode.Screen); assertEquals(android.graphics.BlendMode.SCREEN, paint.blendMode)+ paint.setBlend(BlendMode.Normal); assertNull(paint.blendMode)+ }++ @Test fun listingsHappyPaths() {+ // Form fields: count, id, type, rect, name, value, checked+ fun str(b: ByteBuffer, s: String) { val bytes = s.toByteArray(); b.putShort(bytes.size.toShort()); b.put(bytes) }+ val ff = ByteBuffer.allocate(200).order(ByteOrder.LITTLE_ENDIAN).putInt(1).putLong(9L).put(1)+ .putFloat(1f).putFloat(2f).putFloat(3f).putFloat(4f)+ str(ff, "field"); str(ff, "value"); ff.put(1)+ val fields = com.vayunmathur.pdf.util.SafePdfListings.parseFormFields(ff.array().copyOf(ff.position()))+ assertEquals(1, fields.size); assertEquals("field", fields[0].name); assertTrue(fields[0].checked)++ val out = ByteBuffer.allocate(100).order(ByteOrder.LITTLE_ENDIAN).putInt(1).putShort(2).putInt(7)+ str(out, "Title")+ val outline = com.vayunmathur.pdf.util.SafePdfListings.parseOutline(out.array().copyOf(out.position()))+ assertEquals(listOf(com.vayunmathur.pdf.util.SafeOutlineItem(2, 7, "Title")), outline)++ val sm = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN).putInt(1).putInt(3)+ .putFloat(1f).putFloat(2f).putFloat(3f).putFloat(4f)+ assertEquals(3, com.vayunmathur.pdf.util.SafePdfListings.parseSearchMatches(sm.array())[0].page)++ val empty = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(0).array()+ assertTrue(com.vayunmathur.pdf.util.SafePdfListings.parseAnnotations(empty).isEmpty())+ assertTrue(com.vayunmathur.pdf.util.SafePdfListings.parseLinks(empty).isEmpty())+ assertTrue(com.vayunmathur.pdf.util.SafePdfListings.parseOutline(empty).isEmpty())+ }++ @Test fun composeAppendImageFromJpeg() { runBlocking {+ val png = File(ctx.cacheDir, "final.png")+ png.outputStream().use { Bitmap.createBitmap(24, 18, Bitmap.Config.ARGB_8888).apply { eraseColor(android.graphics.Color.BLUE) }.compress(Bitmap.CompressFormat.PNG, 100, it) }+ val jpeg = readAsJpeg(ctx, Uri.fromFile(png)); assertNotNull(jpeg)+ val doc = ComposePdfDocument.create()+ try {+ assertEquals(1, doc.appendImage(jpeg.bytes, jpeg.width, jpeg.height))+ assertEquals(1, doc.pageCount())+ assertNotNull(doc.renderPage(0))+ assertEquals(1, doc.appendImage(byteArrayOf(1, 2, 3), 24, 18)) // native embeds bytes without validating JPEG+ assertNotNull(doc.save())+ } finally { doc.close() }+ } }++ @Test fun textSelectionLongPress() {+ val page = SafePdfPage(612f, 792f, listOf(+ PdfPrimitive.Text(Offset(72f, 700f), 16f, 0xFF000000.toInt(), "Hello selectable world"),+ ))+ rule.setContent {+ DynamicTheme {+ Box(Modifier.size(400.dp)) { TextSelectionLayer(page = page, ch = 400f, scale = 0.6f, ocr = null) }+ }+ }+ rule.waitForIdle()+ rule.onRoot().performTouchInput {+ down(Offset(80f, 60f))+ advanceEventTime(700)+ moveBy(Offset(160f, 60f))+ up()+ }+ rule.waitForIdle()+ // Tap dismisses any selection+ rule.onRoot().performTouchInput { down(Offset(80f, 60f)); up() }+ rule.waitForIdle()+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/PdfComposeScreensTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/PdfComposeScreensTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/PdfComposeScreensTest.ktnew file mode 100644index 0000000000..29cbbe1b22--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/PdfComposeScreensTest.kt@@ -0,0 +1,180 @@+package com.vayunmathur.pdf.ui++import androidx.activity.ComponentActivity+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import com.vayunmathur.library.ui.DrawerValue+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.rememberDrawerState+import com.vayunmathur.pdf.InitialScreen+import com.vayunmathur.pdf.util.PdfPrimitive+import com.vayunmathur.pdf.util.SafeOutlineItem+import com.vayunmathur.pdf.util.SafePdfPage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+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 PdfComposeScreensTest {+ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++ private val samplePage = SafePdfPage(612f, 792f, listOf(+ PdfPrimitive.Text(Offset(64f, 700f), 18f, 0xFF000000.toInt(), "Annual Report"),+ PdfPrimitive.FillPath(0xFF0000FF.toInt(), false, listOf(listOf(Offset(64f, 600f), Offset(200f, 600f), Offset(200f, 650f), Offset(64f, 650f)))),+ PdfPrimitive.StrokePath(0xFF000000.toInt(), 2f, FloatArray(0), 0f, listOf(Offset(64f, 500f), Offset(300f, 500f))),+ ))++ @Test fun initialScreenButtonsFireCallbacks() {+ var opened = 0; var captured = 0; var cut = 0+ rule.setContent { DynamicTheme { InitialScreen({ opened++ }, { captured++ }, { cut++ }) } }+ rule.onNodeWithText("Open PDF").assertIsDisplayed().performClick()+ rule.onNodeWithText("Capture PDF").assertIsDisplayed().performClick()+ rule.onNodeWithText("PDF cut and glue").assertIsDisplayed().performClick()+ assertEquals(1, opened); assertEquals(1, captured); assertEquals(1, cut)+ }++ @Test fun pageCanvasRendersSample() {+ rule.setContent { DynamicTheme { SafePdfPageCanvas(samplePage) } }+ rule.waitForIdle()+ }++ @Test fun pageCanvasFailurePlaceholder() {+ rule.setContent { DynamicTheme { SafePdfPageCanvas(null, failureReason = "boom") } }+ rule.onNodeWithText("This page could not be displayed").assertIsDisplayed()+ }++ @Test fun pageCanvasLoadingPlaceholder() {+ rule.setContent { DynamicTheme { SafePdfPageCanvas(null) } }+ rule.waitForIdle()+ }++ @Test fun wideLayoutShowsBothSlots() {+ rule.setContent {+ DynamicTheme {+ PdfViewerWideLayout(+ viewer = { androidx.compose.foundation.layout.Box(it) { com.vayunmathur.library.ui.Text("ViewerPane") } },+ tools = { androidx.compose.foundation.layout.Box(it) { com.vayunmathur.library.ui.Text("ToolsPane") } },+ )+ }+ }+ rule.onNodeWithText("ViewerPane").assertIsDisplayed()+ rule.onNodeWithText("ToolsPane").assertIsDisplayed()+ }++ @Test fun outlineDrawerListsAndSelects() {+ var selected = -1+ rule.setContent {+ DynamicTheme {+ PdfOutlineDrawer(+ outline = listOf(SafeOutlineItem(0, 0, "Cover"), SafeOutlineItem(1, 3, "Chapter One")),+ drawerState = rememberDrawerState(DrawerValue.Open),+ onSelectPage = { selected = it },+ ) { com.vayunmathur.library.ui.Text("BodyContent") }+ }+ }+ rule.onNodeWithText("Chapter One").assertIsDisplayed().performClick()+ assertEquals(3, selected)+ }++ @Test fun editToolbarToolSelection() {+ var tool: EditTool? = null; var deleted = false+ rule.setContent {+ DynamicTheme {+ EditToolbar(+ tool = EditTool.SELECT, onTool = { tool = it },+ shape = ShapeKind.RECT_OUTLINE, onShape = {},+ markup = MarkupKind.HIGHLIGHT, onMarkup = {},+ color = Color.Red, onColor = {}, onStyle = {},+ canDelete = true, onDelete = { deleted = true }, onDuplicate = {},+ )+ }+ }+ rule.waitForIdle()+ // Toolbar renders icon buttons; interaction smoke: compose survives+ assertTrue(true)+ }++ @Test fun styleDialogShowsAndDismisses() {+ var dismissed = false; var color: Color? = null+ rule.setContent {+ DynamicTheme {+ StyleDialog(color = Color.Red, onColor = { color = it }, opacity = 1f, onOpacity = {},+ strokeWidth = 2f, onWidth = {}, onDismiss = { dismissed = true })+ }+ }+ rule.onNodeWithText("Style").assertIsDisplayed()+ rule.onNodeWithText("Done").performClick()+ assertTrue(dismissed)+ }++ @Test fun passwordPromptTypesAndOpens() {+ var input = ""; var opened = false+ rule.setContent {+ DynamicTheme {+ SafePdfPasswordPrompt(pwInput = input, onPwInput = { input = it }, pwError = true,+ onOpen = { opened = true }, onBack = {})+ }+ }+ rule.onNodeWithText("Password required").assertIsDisplayed()+ rule.onNodeWithText("Incorrect password").assertIsDisplayed()+ rule.onNodeWithText("Open").performClick()+ assertTrue(opened)+ }++ @Test fun pendingNoteDialogAdds() {+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined))+ state.pendingNote = 0 to Offset(10f, 10f)+ rule.setContent { DynamicTheme { SafePdfPendingDialogs(state, null, SafePdfLauncherSet({}, {}, {})) } }+ rule.onNodeWithText("Sticky note").assertIsDisplayed()+ rule.onNodeWithText("Cancel").performClick()+ assertEquals(null, state.pendingNote)+ }++ @Test fun cutGlueEmpty() {+ rule.setContent {+ DynamicTheme {+ CutGlueContent(pageKeys = emptyList(), renderPage = { null })+ }+ }+ rule.onNodeWithText("Tap + to append a PDF or image").assertIsDisplayed()+ }++ @Test fun cutGlueWithPages() {+ rule.setContent {+ DynamicTheme {+ CutGlueContent(+ pageKeys = listOf(0L, 1L),+ renderPage = { samplePage },+ initialPages = mapOf(0L to samplePage, 1L to samplePage),+ )+ }+ }+ rule.waitForIdle()+ }++ @Test fun toolButtonsAndMenusRender() {+ var markup: MarkupKind? = null; var shape: ShapeKind? = null+ rule.setContent {+ DynamicTheme {+ androidx.compose.foundation.layout.Column {+ MarkupMenuButton(markup = MarkupKind.HIGHLIGHT, active = true, onMarkup = { markup = it })+ ShapeMenuButton(shape = ShapeKind.RECT_OUTLINE, active = false, onShape = { shape = it })+ LinesMenuButton(tool = EditTool.LINE, onTool = {})+ }+ }+ }+ rule.waitForIdle()+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/SafePdfViewerStateTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/SafePdfViewerStateTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/SafePdfViewerStateTest.ktnew file mode 100644index 0000000000..f8f2a06823--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/SafePdfViewerStateTest.kt@@ -0,0 +1,113 @@+package com.vayunmathur.pdf.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.TextFieldValue+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class SafePdfViewerStateTest {+ private fun state() = SafePdfViewerState(CoroutineScope(Dispatchers.Unconfined))++ @Test fun defaults() {+ val s = state()+ assertFalse(s.editMode); assertFalse(s.dirty); assertEquals(EditTool.SELECT, s.tool)+ assertEquals(ShapeKind.RECT_OUTLINE, s.shape); assertEquals(MarkupKind.HIGHLIGHT, s.markup)+ assertEquals(Color.Red, s.color); assertEquals(1f, s.opacity); assertEquals(2f, s.strokeWidth)+ assertTrue(s.undoStack.isEmpty()); assertEquals(0, s.pageCount)+ }++ @Test fun drawColorAppliesOpacity() {+ val s = state(); s.color = Color.Red; s.opacity = 0.5f+ assertEquals(0.5f, s.drawColor.alpha, 0.01f)+ }++ @Test fun markEditedBumpsOnlyThatPageAndDirties() {+ val s = state(); s.markEdited(2); s.markEdited(2); s.markEdited(3)+ assertEquals(2, s.pageVersions[2]); assertEquals(1, s.pageVersions[3]); assertTrue(s.dirty)+ }++ @Test fun registerCreatedIgnoresZeroAndClearsRedo() {+ val s = state()+ s.redoStack.add(EditAction(0, 9L, EditKind.ADDED))+ s.registerCreated(1, 0L); assertTrue(s.undoStack.isEmpty()); assertEquals(1, s.redoStack.size)+ s.registerCreated(1, 42L)+ assertEquals(listOf(EditAction(1, 42L, EditKind.ADDED)), s.undoStack.toList())+ assertTrue(s.redoStack.isEmpty())+ }++ @Test fun registerMovedRecordsRects() {+ val s = state(); s.registerMoved(0, 5L, listOf(0f, 0f, 1f, 1f), listOf(2f, 2f, 3f, 3f))+ assertEquals(EditKind.MOVED, s.undoStack.single().kind)+ assertEquals(listOf(2f, 2f, 3f, 3f), s.undoStack.single().newRect)+ }++ @Test fun addPolyPointDraftLifecycle() {+ val s = state()+ s.addPolyPoint(0, Offset(1f, 2f))+ assertEquals(PolyDraft(0, listOf(Offset(1f, 2f)), false), s.polyDraft)+ s.addPolyPoint(0, Offset(3f, 4f)); assertEquals(2, s.polyDraft!!.points.size)+ s.addPolyPoint(1, Offset(9f, 9f)); assertEquals(2, s.polyDraft!!.points.size) // other page ignored+ s.tool = EditTool.BEZIER+ val s2 = state(); s2.tool = EditTool.BEZIER; s2.addPolyPoint(0, Offset.Zero)+ assertTrue(s2.polyDraft!!.bezier)+ }++ @Test fun commitPolyDiscardsShortDraftAndClears() {+ val s = state(); s.addPolyPoint(0, Offset.Zero)+ s.commitPoly(null); assertNull(s.polyDraft)+ // >=2 points but no document: still clears+ s.addPolyPoint(0, Offset.Zero); s.addPolyPoint(0, Offset(1f, 1f))+ s.commitPoly(null); assertNull(s.polyDraft)+ }++ @Test fun commitTextWithNullsIsNoOp() {+ val s = state(); s.commitText(null, null)+ val session = TextSession(0, Offset.Zero, 12f, 0, null, TextFieldValue("hi", TextRange(2)))+ s.commitText(session, null) // no doc+ s.commitTextAndClear(null); assertNull(s.textSession)+ }++ @Test fun toggleEditModeFlipsAndClearsSelection() {+ val s = state(); s.selected = 0 to 5L+ s.toggleEditMode(null); assertTrue(s.editMode); assertNull(s.selected)+ s.toggleEditMode(null); assertFalse(s.editMode)+ }++ @Test fun deleteDuplicateApplyWithNullDocAreNoOps() {+ val s = state(); s.selected = 0 to 1L+ s.deleteSelected(null); assertEquals(0 to 1L, s.selected)+ s.duplicateSelected(null); s.applyRedactions(null)+ s.createNote(null, 0, Offset.Zero, "x"); assertNull(s.pendingNote)+ s.createCallout(null, 0, Offset.Zero, Offset(1f, 1f), "y"); assertNull(s.pendingCallout)+ }++ @Test fun undoRedoWithNullDocDoNotCrashOnEmpty() {+ val s = state(); s.undo(null); s.redo(null)+ assertTrue(s.undoStack.isEmpty() && s.redoStack.isEmpty())+ }++ @Test fun startTextReplacesSession() {+ val s = state()+ val a = TextSession(0, Offset.Zero, 12f, 0, null, TextFieldValue("a"))+ val b = TextSession(1, Offset(1f, 1f), 14f, 0, null, TextFieldValue("b"))+ s.startText(null, a); assertEquals(a, s.textSession)+ s.startText(null, b); assertEquals(b, s.textSession)+ }++ @Test fun onImagePickedWithoutTargetClearsTarget() {+ val s = state(); s.onImagePicked(null, appContext(), null); assertNull(s.imageTarget)+ }++ private fun appContext(): android.content.Context =+ androidx.test.core.app.ApplicationProvider.getApplicationContext()+}
pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.ktnew file mode 100644index 0000000000..8ef63a35af--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/ScrollZoomGlyphTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.pdf.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.unit.IntSize+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class ScrollZoomGlyphTest {+ private fun scrollState(pages: Int = 3, w: Int = 612, h: Int = 800): SafePdfScrollState {+ val s = SafePdfScrollState()+ s.viewportSize = IntSize(w, h); s.pageCount = pages+ return s+ }++ @Test fun scrollNotReadyWithoutPagesOrViewport() {+ val s = SafePdfScrollState(); assertFalse(s.isReady())+ s.pageCount = 2; assertFalse(s.isReady())+ s.viewportSize = IntSize(100, 100); assertTrue(s.isReady())+ }++ @Test fun contentHeightUsesFallbackRatio() {+ val s = scrollState(2, w = 612, h = 800)+ // each page 612 / (612/792) = 792+ assertEquals(1584f, s.contentHeightPx(), 0.5f)+ assertEquals(0f, s.pageTop(0)); assertEquals(792f, s.pageTop(1), 0.5f)+ assertEquals(1584f, s.pageTop(99), 0.5f) // clamped to last entry (content height)+ }++ @Test fun measuredHeightOverridesEstimateAndIgnoresInvalid() {+ val s = scrollState(2)+ s.setMeasuredHeight(0, 400); assertEquals(400f + 792f, s.contentHeightPx(), 0.5f)+ s.setMeasuredHeight(0, 0); s.setMeasuredHeight(-1, 100); s.setMeasuredHeight(5, 100)+ assertEquals(400f + 792f, s.contentHeightPx(), 0.5f)+ s.ratioAt = { 1f }+ // page1 now estimated 612/1=612, page0 still measured+ assertEquals(1012f, s.contentHeightPx(), 0.5f)+ }++ @Test fun scrollClampsAndProgress() {+ val s = scrollState(3)+ s.scrollTo(99999f, 1f); assertEquals(s.range(1f), s.scrollPx)+ assertEquals(1f, s.progress(1f))+ s.scrollTo(-50f, 1f); assertEquals(0f, s.scrollPx); assertEquals(0f, s.progress(1f))+ val consumed = s.scrollByScreen(-100f, 1f) // finger up? dy negative -> scroll forward 100+ assertEquals(100f, s.scrollPx, 0.01f); assertEquals(-100f, consumed, 0.01f)+ }++ @Test fun currentPageAndVisibleRange() {+ val s = scrollState(5)+ assertEquals(0, s.currentPage())+ s.scrollTo(800f, 1f); assertEquals(1, s.currentPage())+ val range = s.visibleRange(1f)+ assertTrue(range.first <= 1 && range.last >= 1)+ assertEquals(0..2, SafePdfScrollState().visibleRange(1f))+ }++ @Test fun scrollToPage() {+ val s = scrollState(4)+ s.scrollToPage(2, 1f); assertEquals(1584f, s.scrollPx, 0.5f)+ s.scrollToPage(99, 1f); assertEquals(s.range(1f), s.scrollPx)+ SafePdfScrollState().scrollToPage(1, 1f) // no pages, no crash+ }++ @Test fun zoomAroundKeepsCentroid() {+ val s = scrollState(5)+ s.scrollTo(500f, 1f)+ s.zoomAround(400f, 1f, 2f)+ // docY=900, new scroll=900-200=700+ assertEquals(700f, s.scrollPx, 0.5f)+ }++ @Test fun zoomStateTransformClamps() {+ val scroll = scrollState(5)+ val z = SafePdfZoomState()+ z.viewportSize = IntSize(1000, 800)+ z.onPageWidth(612f); z.onPageWidth(100f) // monotonic+ assertEquals(612f, z.maxPageWidthPts)+ z.onTransform(Offset(500f, 400f), 100f, Offset(99999f, 0f), scroll)+ assertTrue(z.zoom <= maxZoomFor(612f, 1000) + 0.001f)+ assertEquals(maxPanX(1000, z.zoom), z.pan.x, 0.01f)+ assertEquals(0f, z.pan.y)+ z.setZoomPan(2f, Offset(50f, 99f)); assertEquals(2f, z.zoom); assertEquals(Offset(50f, 0f), z.pan)+ z.onTransform(Offset.Zero, 0.0001f, Offset.Zero, scroll); assertEquals(MIN_ZOOM, z.zoom)+ }++ @Test fun selGlyphBoundsAndCenter() {+ val g = selGlyph("a", 10f, 20f, 30f, 40f)+ assertEquals(10f, g.left); assertEquals(30f, g.right); assertEquals(Offset(20f, 30f), g.center)+ val skewed = SelGlyph("x", Offset(5f, 5f), Offset(15f, 0f), Offset(20f, 10f), Offset(10f, 15f))+ assertEquals(0f, skewed.top); assertEquals(20f, skewed.right)+ }++ @Test fun nearestGlyphAndWordRange() {+ val glyphs = listOf(+ selGlyph("h", 0f, 0f, 10f, 10f), selGlyph("i", 10f, 0f, 20f, 10f),+ selGlyph(" ", 20f, 0f, 30f, 10f), selGlyph("y", 40f, 0f, 50f, 10f),+ )+ assertEquals(1, nearestGlyph(glyphs, Offset(15f, 5f)))+ assertNull(nearestGlyph(glyphs, Offset(500f, 500f), maxDist = 10f))+ assertNull(nearestGlyph(emptyList(), Offset.Zero))+ assertEquals(0..1, wordRangeAt(glyphs, 0))+ assertEquals(0..1, wordRangeAt(glyphs, 1))+ assertEquals(3..3, wordRangeAt(glyphs, 3))+ assertEquals(9..9, wordRangeAt(glyphs, 9))+ }++ @Test fun sameWordAndHandleAt() {+ val a = selGlyph("a", 0f, 0f, 10f, 10f); val b = selGlyph("b", 10f, 0f, 20f, 10f)+ val far = selGlyph("c", 100f, 0f, 110f, 10f)+ assertTrue(sameWord(a, b)); assertFalse(sameWord(a, far))+ val glyphs = listOf(a, b)+ assertEquals(0, handleAt(glyphs, Offset(0f, 10f), 0..1))+ assertEquals(1, handleAt(glyphs, Offset(20f, 10f), 0..1))+ assertNull(handleAt(glyphs, Offset(500f, 500f), 0..1))+ assertNull(handleAt(glyphs, Offset.Zero, 5..9))+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/SelectionGlyphsRobolectricTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/SelectionGlyphsRobolectricTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/SelectionGlyphsRobolectricTest.ktnew file mode 100644index 0000000000..ba8b35e00a--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/SelectionGlyphsRobolectricTest.kt@@ -0,0 +1,52 @@+package com.vayunmathur.pdf.ui++import androidx.compose.ui.geometry.Offset+import com.vayunmathur.pdf.util.PdfPrimitive+import com.vayunmathur.pdf.util.SafePdfPage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SelectionGlyphsRobolectricTest {+ @Test fun pdfTypefaceFamiliesAndStyles() {+ val serif = pdfTypeface(1, false, false); assertTrue(serif != null)+ val sans = pdfTypeface(0, false, false); assertTrue(sans != null)+ val monoBold = pdfTypeface(2, true, false); assertTrue(monoBold.isBold)+ val italic = pdfTypeface(99, false, true); assertTrue(italic.isItalic)+ val boldItalic = pdfTypeface(1, true, true); assertTrue(boldItalic.isBold && boldItalic.isItalic)+ }++ @Test fun buildEmbeddedGlyphsFromText() {+ val page = SafePdfPage(612f, 792f, listOf(+ PdfPrimitive.Text(origin = Offset(72f, 700f), size = 12f, color = 0xFF000000.toInt(), text = "Hi", advance = 12f),+ PdfPrimitive.Text(origin = Offset(72f, 600f), size = 12f, color = 0, text = "", advance = 0f),+ PdfPrimitive.FillPath(0, false, listOf(listOf(Offset.Zero))),+ ))+ val glyphs = buildEmbeddedGlyphs(page, ch = 792f, scale = 1f)+ assertEquals(2, glyphs.size)+ assertEquals("H", glyphs[0].glyph.ch); assertEquals("i", glyphs[1].glyph.ch)+ // Ordered by -origin.y: higher page y first+ assertTrue(glyphs[0].orderY < glyphs[1].orderY || glyphs.size == 2)+ assertTrue(glyphs[0].glyph.right > glyphs[0].glyph.left)+ }++ @Test fun buildEmbeddedGlyphsInvisibleUsesAdvance() {+ val page = SafePdfPage(612f, 792f, listOf(+ PdfPrimitive.Text(origin = Offset(0f, 700f), size = 10f, color = 0, text = "abcd", advance = 40f, renderMode = 3),+ ))+ val glyphs = buildEmbeddedGlyphs(page, 792f, 1f)+ assertEquals(4, glyphs.size)+ // Total span should be about advance*scale = 40+ val span = glyphs.last().glyph.right - glyphs.first().glyph.left+ assertTrue(span in 30f..50f, "span=$span")+ }++ @Test fun buildEmbeddedGlyphsEmptyPage() {+ assertTrue(buildEmbeddedGlyphs(SafePdfPage(100f, 100f, emptyList()), 100f, 1f).isEmpty())+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/StateDocBatchTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/StateDocBatchTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/StateDocBatchTest.ktnew file mode 100644index 0000000000..52b130f498--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/StateDocBatchTest.kt@@ -0,0 +1,185 @@+package com.vayunmathur.pdf.ui++import android.content.Context+import android.graphics.Bitmap+import android.net.Uri+import androidx.activity.ComponentActivity+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onFirst+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.pdf.util.SafePdfDocument+import com.vayunmathur.pdf.util.addImageStamp+import com.vayunmathur.pdf.util.addText+import com.vayunmathur.pdf.util.moveAnnotation+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+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 StateDocBatchTest {+ @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, "state-${System.nanoTime()}.pdf"); f.writeBytes(minimalPdf())+ SafePdfDocument.open(ctx, Uri.fromFile(f))!!+ }++ private suspend fun await(desc: String, cond: suspend () -> Boolean) =+ withTimeout(8000) { while (!cond()) delay(25) }++ @Test fun selectionTextCases() {+ val g = listOf(selGlyph("h", 0f, 0f, 10f, 10f), selGlyph("i", 10f, 0f, 20f, 10f), selGlyph("!", 20f, 0f, 30f, 10f))+ assertEquals("hi!", selectionText(g, 0..2))+ assertEquals("i", selectionText(g, 1..1))+ assertEquals("", selectionText(g, 5..9))+ assertEquals("", selectionText(emptyList(), 0..0))+ assertEquals("", selectionText(g, 2..1))+ }++ @Test fun allKindIconsCompose() {+ rule.setContent {+ DynamicTheme {+ androidx.compose.foundation.layout.Column {+ for (k in MarkupKind.entries) { val icon = k.icon(); icon(Color.Red) }+ for (k in ShapeKind.entries) { val icon = k.icon(); icon(Color.Blue) }+ }+ }+ }+ rule.waitForIdle()+ }++ @Test fun markupMenuSelects() {+ var picked: MarkupKind? = null+ rule.setContent { DynamicTheme { MarkupMenuButton(MarkupKind.HIGHLIGHT, true) { picked = it } } }+ // IconButton is the only click target; click via semantics on the button node+ rule.onAllNodes(androidx.compose.ui.test.hasClickAction()).onFirst().performClick()+ rule.onNodeWithText("Squiggly").assertIsDisplayed().performClick()+ assertEquals(MarkupKind.SQUIGGLY, picked)+ }++ @Test fun shapeMenuSelects() {+ var picked: ShapeKind? = null+ rule.setContent { DynamicTheme { ShapeMenuButton(ShapeKind.RECT_OUTLINE, false) { picked = it } } }+ rule.onAllNodes(androidx.compose.ui.test.hasClickAction()).onFirst().performClick()+ rule.onNodeWithText("Ellipse (filled)").assertIsDisplayed().performClick()+ assertEquals(ShapeKind.OVAL_FILL, picked)+ }++ @Test fun linesMenuSelects() {+ var picked: EditTool? = null+ rule.setContent { DynamicTheme { LinesMenuButton(EditTool.SELECT) { picked = it } } }+ rule.onAllNodes(androidx.compose.ui.test.hasClickAction()).onFirst().performClick()+ rule.onNodeWithText("Bézier curve").assertIsDisplayed().performClick()+ assertEquals(EditTool.BEZIER, picked)+ }++ @Test fun readAsJpegAndImageStampAndOnImagePicked() { runBlocking {+ val doc = openDoc()+ try {+ val png = File(ctx.cacheDir, "stamp.png")+ png.outputStream().use { Bitmap.createBitmap(30, 20, Bitmap.Config.ARGB_8888).apply { eraseColor(android.graphics.Color.RED) }.compress(Bitmap.CompressFormat.PNG, 100, it) }+ val jpeg = readAsJpeg(ctx, Uri.fromFile(png))+ assertNotNull(jpeg); assertEquals(30, jpeg.width); assertEquals(20, jpeg.height); assertTrue(jpeg.bytes.isNotEmpty())+ assertNull(readAsJpeg(ctx, Uri.parse("content://missing/img")))+ val stampId = doc.addImageStamp(0, 100f, 500f, 250f, 600f, jpeg.width, jpeg.height, jpeg.bytes)+ assertTrue(stampId != 0L, "image stamp id=$stampId")++ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Default))+ state.imageTarget = 0 to Offset(120f, 650f)+ val before = doc.annotations(0).size+ state.onImagePicked(doc, ctx, Uri.fromFile(png))+ await("stamp annotation") { doc.annotations(0).size > before }+ assertNull(state.imageTarget)+ } finally { doc.close() }+ } }++ @Test fun commitPolyUndoMovedRemovedAndTextEditBranches() { runBlocking {+ val doc = openDoc()+ val state = SafePdfViewerState(CoroutineScope(Dispatchers.Default))+ try {+ // commitPoly straight + bezier+ state.polyDraft = PolyDraft(0, listOf(Offset(80f, 600f), Offset(150f, 650f), Offset(220f, 600f)), false)+ state.commitPoly(doc); assertNull(state.polyDraft)+ await("poly annot") { doc.annotations(0).isNotEmpty() }+ state.polyDraft = PolyDraft(0, listOf(Offset(80f, 500f), Offset(150f, 550f), Offset(220f, 500f)), true)+ state.commitPoly(doc)+ await("bezier annot") { doc.annotations(0).size >= 2 }++ // createCallout with doc+ state.createCallout(doc, 0, Offset(60f, 60f), Offset(160f, 160f), "callout text")+ await("callout annot") { doc.annotations(0).size >= 3 }++ // MOVED undo/redo+ val id = doc.annotations(0).first().id+ val before = doc.annotations(0).first { it.id == id }+ state.registerMoved(0, id, listOf(before.x0, before.y0, before.x1, before.y1), listOf(before.x0 + 20f, before.y0, before.x1 + 20f, before.y1))+ doc.moveAnnotation(0, id, before.x0 + 20f, before.y0, before.x1 + 20f, before.y1)+ state.undo(doc)+ await("undo moved") { state.redoStack.isNotEmpty() }+ state.redo(doc)+ await("redo moved") { state.undoStack.isNotEmpty() }++ // Text edit existing + delete-on-empty+ val textId = doc.addText(0, 100f, 300f, 300f, 330f, 0xFF000000.toInt(), 12f, "old")+ assertTrue(textId != 0L)+ state.textSession = TextSession(0, Offset(100f, 330f), 12f, 0, textId, androidx.compose.ui.text.input.TextFieldValue("new text"))+ state.commitTextAndClear(doc)+ delay(300)+ state.textSession = TextSession(0, Offset(100f, 330f), 12f, 0, textId, androidx.compose.ui.text.input.TextFieldValue(""))+ state.commitTextAndClear(doc)+ await("text deleted") { doc.annotations(0).none { it.id == textId } }+ } finally { doc.close() }+ } }++ @Test fun exportCapturedPdfViaViewModel() {+ val app = ctx as android.app.Application+ val vm = com.vayunmathur.pdf.util.PdfViewModel(app)+ val png = File(ctx.cacheDir, "vm-page.png")+ png.outputStream().use { Bitmap.createBitmap(20, 20, Bitmap.Config.ARGB_8888).apply { eraseColor(android.graphics.Color.WHITE) }.compress(Bitmap.CompressFormat.PNG, 100, it) }+ vm.addCapturedImage(Uri.fromFile(png))+ val out = File(ctx.cacheDir, "vm-out.pdf")+ // viewModelScope runs on Main; Robolectric looper drives it+ vm.exportCapturedPdf(Uri.fromFile(out))+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ Thread.sleep(200)+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/ViewerModelsGeometryTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/ViewerModelsGeometryTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/ViewerModelsGeometryTest.ktnew file mode 100644index 0000000000..ca5eb2438c--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/ViewerModelsGeometryTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.pdf.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Rect+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class ViewerModelsGeometryTest {+ @Test fun shapeKindFillAndGeom() {+ assertTrue(ShapeKind.RECT_FILL.isFill); assertFalse(ShapeKind.RECT_OUTLINE.isFill)+ assertEquals(ShapeGeom.RECT, ShapeKind.RECT_OUTLINE.geom)+ assertEquals(ShapeGeom.POLYGON, ShapeKind.ROUNDRECT_FILL.geom)+ assertEquals(ShapeGeom.OVAL, ShapeKind.OVAL_FILL.geom)+ assertEquals(ShapeGeom.POLYGON, ShapeKind.TRIANGLE_FILL.geom)+ assertEquals(18, ShapeKind.entries.size)+ }++ @Test fun shapeLabels() {+ assertEquals("Rectangle", ShapeKind.RECT_OUTLINE.label())+ assertEquals("Rectangle (filled)", ShapeKind.RECT_FILL.label())+ assertEquals("Rounded rectangle", ShapeKind.ROUNDRECT_OUTLINE.label())+ assertEquals("Ellipse (filled)", ShapeKind.OVAL_FILL.label())+ assertEquals("Triangle", ShapeKind.TRIANGLE_OUTLINE.label())+ assertEquals("Star (filled)", ShapeKind.STAR_FILL.label())+ assertEquals("Arrow", ShapeKind.ARROW_OUTLINE.label())+ }++ @Test fun markupLabels() {+ assertEquals("Highlight", MarkupKind.HIGHLIGHT.label())+ assertEquals("Underline", MarkupKind.UNDERLINE.label())+ assertEquals("Strikeout", MarkupKind.STRIKEOUT.label())+ assertEquals("Squiggly", MarkupKind.SQUIGGLY.label())+ }++ @Test fun unitPolygons() {+ assertEquals(listOf(Offset(0.5f, 0f), Offset(1f, 1f), Offset(0f, 1f)), ShapeKind.TRIANGLE_OUTLINE.unitPolygon())+ assertEquals(4, ShapeKind.DIAMOND_FILL.unitPolygon().size)+ assertEquals(5, ShapeKind.PENTAGON_OUTLINE.unitPolygon().size)+ assertEquals(6, ShapeKind.HEXAGON_FILL.unitPolygon().size)+ assertEquals(10, ShapeKind.STAR_OUTLINE.unitPolygon().size)+ assertEquals(7, ShapeKind.ARROW_FILL.unitPolygon().size)+ assertTrue(ShapeKind.RECT_OUTLINE.unitPolygon().isEmpty())+ assertTrue(ShapeKind.OVAL_FILL.unitPolygon().isEmpty())+ assertTrue(ShapeKind.ROUNDRECT_OUTLINE.unitPolygon().size > 10)+ // All unit points inside unit square+ ShapeKind.entries.forEach { k -> k.unitPolygon().forEach { p -> assertTrue(p.x in -0.01f..1.01f && p.y in -0.01f..1.01f, "$k $p") } }+ }++ @Test fun regularPolygonAndStar() {+ val pent = regularPolygonUnit(5)+ assertEquals(5, pent.size); assertEquals(Offset(0.5f, 0f), pent.first())+ val star = starUnit(5, 0.5f, 0.22f)+ assertEquals(10, star.size); assertEquals(Offset(0.5f, 0f), star.first())+ }++ @Test fun roundRectClampsRadius() {+ val pts = roundRectUnit(2f, 4) // clamped to 0.5+ assertTrue(pts.all { it.x in 0f..1f && it.y in 0f..1f })+ assertEquals(20, pts.size) // 4 corners * (seg+1)+ }++ @Test fun mapUnitScalesIntoRect() {+ val r = Rect(10f, 20f, 110f, 220f)+ assertEquals(Offset(10f, 20f), mapUnit(Offset(0f, 0f), r))+ assertEquals(Offset(60f, 120f), mapUnit(Offset(0.5f, 0.5f), r))+ assertEquals(Offset(110f, 220f), mapUnit(Offset(1f, 1f), r))+ }++ @Test fun flattenSmoothShortInputUnchangedAndLongSmooths() {+ val two = listOf(Offset(0f, 0f), Offset(1f, 1f))+ assertEquals(two, flattenSmooth(two))+ val pts = listOf(Offset(0f, 0f), Offset(10f, 10f), Offset(20f, 0f), Offset(30f, 10f))+ val out = flattenSmooth(pts)+ assertTrue(out.size > pts.size)+ assertEquals(pts.first(), out.first()); assertEquals(pts.last(), out.last())+ }++ @Test fun maxZoomFor() {+ assertEquals(MAX_ZOOM, maxZoomFor(0f, 1000))+ assertEquals(MAX_ZOOM, maxZoomFor(612f, 0))+ assertEquals(MAX_ZOOM, maxZoomFor(100f, 1000)) // 0.4 clamped up to 6+ assertEquals(ABS_MAX_ZOOM, maxZoomFor(100000f, 1000)) // huge clamped to 40+ val mid = maxZoomFor(612f, 100) // 4*612/100=24.48+ assertEquals(24.48f, mid, 0.01f)+ }++ @Test fun maxPanX() {+ assertEquals(0f, maxPanX(1000, 1f)); assertEquals(0f, maxPanX(1000, 0.5f))+ assertEquals(500f, maxPanX(1000, 2f))+ }++ @Test fun editActionAndPolyDraftDefaults() {+ val a = EditAction(2, 42L, EditKind.ADDED)+ assertEquals(null, a.oldRect)+ val d = PolyDraft(1, listOf(Offset.Zero), bezier = true); assertTrue(d.bezier)+ }+}
pdf/src/test/java/com/vayunmathur/pdf/ui/ViewerScreenRobolectricTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/ui/ViewerScreenRobolectricTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/ui/ViewerScreenRobolectricTest.ktnew file mode 100644index 0000000000..bf453889b5--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/ui/ViewerScreenRobolectricTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.pdf.ui++import android.graphics.Bitmap+import android.graphics.Color+import android.net.Uri+import androidx.activity.ComponentActivity+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+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 kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+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 ViewerScreenRobolectricTest {+ @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()++ 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)+ }++ @Test fun viewerScreenLoadsRealPdf() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ val f = File(ctx.cacheDir, "viewer.pdf"); f.writeBytes(minimalPdf())+ var backed = false+ rule.setContent { DynamicTheme { SafePdfViewerScreen(Uri.fromFile(f)) { backed = true } } }+ // Document opens on IO via produceState; wait for composition to settle repeatedly+ rule.waitUntil(timeoutMillis = 10_000) {+ try { rule.onAllNodes(androidx.compose.ui.test.hasContentDescription("Search", substring = true)).fetchSemanticsNodes().isNotEmpty() }+ catch (_: Throwable) { false }+ }+ rule.waitForIdle()+ assertTrue(!backed)+ }++ @Test fun viewerScreenErrorForNonPdf() {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ val f = File(ctx.cacheDir, "not.pdf"); f.writeText("<html>error</html>")+ rule.setContent { DynamicTheme { SafePdfViewerScreen(Uri.fromFile(f)) {} } }+ rule.waitUntil(timeoutMillis = 10_000) {+ try { rule.onAllNodes(androidx.compose.ui.test.hasText("This file isn't a PDF", substring = true)).fetchSemanticsNodes().isNotEmpty() }+ catch (_: Throwable) { false }+ }+ rule.waitForIdle()+ }++ @Test fun warpQuadProducesTargetSize() {+ 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))+ val clamped = warpQuadToBitmap(src, Quadrilateral.default(), 0, 0)+ assertTrue(clamped.width >= 1 && clamped.height >= 1)+ }++ @Test fun savePdfToUriWithNoImagesAndWithImage() { runBlocking {+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+ // A PNG source image on disk+ val imgFile = File(ctx.cacheDir, "page.png")+ imgFile.outputStream().use { Bitmap.createBitmap(20, 28, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.WHITE) }.compress(Bitmap.CompressFormat.PNG, 100, it) }+ val outFile = File(ctx.cacheDir, "out.pdf")+ val ok = savePdfToUri(ctx, listOf(CapturedImage(Uri.fromFile(imgFile))), Uri.fromFile(outFile))+ // Robolectric's PdfDocument cannot write a real PDF stream, so the exporter+ // must degrade to a clean false here rather than throwing (on a device it returns true).+ kotlin.test.assertFalse(ok, "Robolectric PdfDocument write should fail cleanly, got success")+ val bad = savePdfToUri(ctx, listOf(CapturedImage(Uri.parse("content://missing/1"))), Uri.fromFile(File(ctx.cacheDir, "out2.pdf")))+ kotlin.test.assertFalse(bad, "undecodable source yields no pages, so the write must fail cleanly")+ // Filters exercise applyScanFilter paths when decode succeeds+ for (filter in ScanFilter.entries) {+ savePdfToUri(ctx, listOf(CapturedImage(Uri.fromFile(imgFile), quadrilateral = Quadrilateral.default())), Uri.fromFile(File(ctx.cacheDir, "out-$filter.pdf")), filter)+ }+ } }+}
pdf/src/test/java/com/vayunmathur/pdf/util/FrameGeometryTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/util/FrameGeometryTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/util/FrameGeometryTest.ktnew file mode 100644index 0000000000..cc4827ae47--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/util/FrameGeometryTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.pdf.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class FrameGeometryTest {+ @Test fun grayscaleUsesLumaWeights() {+ // Pure red: 255*77 shr 8 = 76, green: 150*255 shr8=149, blue: 29, white 255+ val out = grayscale(intArrayOf(0xFFFF0000.toInt(), 0xFF00FF00.toInt(), 0xFF0000FF.toInt(), 0xFFFFFFFF.toInt(), 0xFF000000.toInt()))+ assertEquals(listOf(76, 149, 28, 255, 0), out.toList())+ }++ @Test fun gaussianBlurKeepsUniformFieldAndZeroesBorder() {+ val w = 10; val h = 10+ val src = IntArray(w * h) { 159 }+ val out = gaussianBlur(src, w, h)+ assertEquals(159, out[5 * w + 5])+ assertEquals(0, out[0]) // border not convolved+ }++ @Test fun adaptiveThresholdMarksDarkPixelInBrightField() {+ val w = 12; val h = 12+ val gray = IntArray(w * h) { 200 }+ gray[6 * w + 6] = 0+ val out = adaptiveThreshold(gray, w, h)+ assertTrue(out[6 * w + 6])+ assertTrue(!out[0])+ }++ @Test fun dilateSpreadsToCrossNeighbours() {+ val w = 5; val h = 5+ val edges = BooleanArray(w * h); edges[2 * w + 2] = true+ dilate(edges, w, h)+ assertTrue(edges[2 * w + 2]); assertTrue(edges[1 * w + 2]); assertTrue(edges[3 * w + 2])+ assertTrue(edges[2 * w + 1]); assertTrue(edges[2 * w + 3])+ assertTrue(!edges[1 * w + 1]) // diagonal not dilated+ }++ @Test fun morphCloseFillsSinglePixelHole() {+ val w = 7; val h = 7+ val bin = BooleanArray(w * h) { true }; bin[3 * w + 3] = false+ morphClose(bin, w, h)+ assertTrue(bin[3 * w + 3])+ }++ @Test fun traceContoursFindsSquareBoundary() {+ val w = 20; val h = 20+ val bin = BooleanArray(w * h)+ for (y in 5..14) for (x in 5..14) bin[y * w + x] = true+ val contours = traceContours(bin, w, h)+ assertTrue(contours.isNotEmpty())+ assertTrue(contours.first().size >= 4)+ assertTrue(contours.first().all { (x, y) -> x in 5..14 && y in 5..14 })+ }++ @Test fun traceContoursEmptyForBlank() {+ assertTrue(traceContours(BooleanArray(100), 10, 10).isEmpty())+ }++ @Test fun findBestQuadDetectsFilledRectangle() {+ val w = 40; val h = 40+ val bin = BooleanArray(w * h)+ for (y in 8..31) for (x in 8..31) bin[y * w + x] = true+ val quad = findBestQuad(bin, w, h)+ assertNotNull(quad)+ // Normalized corners near the rectangle (contour is boundary, approx may inset slightly)+ assertTrue(quad.topLeft.x < 0.35f && quad.topLeft.y < 0.35f, quad.toString())+ assertTrue(quad.bottomRight.x > 0.65f && quad.bottomRight.y > 0.65f, quad.toString())+ }++ @Test fun findBestQuadNullForBlankAndTiny() {+ assertNull(findBestQuad(BooleanArray(40 * 40), 40, 40))+ val w = 40; val h = 40; val bin = BooleanArray(w * h); bin[20 * w + 20] = true+ assertNull(findBestQuad(bin, w, h))+ }++ @Test fun contourTracerRejectsVisitedAndInterior() {+ val w = 10; val h = 10; val bin = BooleanArray(w * h) { true }+ val visited = BooleanArray(w * h)+ val tracer = ContourTracer(bin, w, h, visited, intArrayOf(1, 1, 0, -1, -1, -1, 0, 1), intArrayOf(0, 1, 1, 1, 0, -1, -1, -1))+ assertNull(tracer.traceFrom(5, 5)) // interior: left neighbour foreground+ }+}
pdf/src/test/java/com/vayunmathur/pdf/util/NativeDocumentTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/util/NativeDocumentTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/util/NativeDocumentTest.ktnew file mode 100644index 0000000000..f678bdc664--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/util/NativeDocumentTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.pdf.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking++class NativeDocumentTest {+ private fun minimalPdf(text: String = "Hello"): ByteArray {+ val content = "BT /F1 24 Tf 100 700 Td ($text) 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)+ }++ @Test fun nativeAvailableAndRejectsGarbage() {+ assertTrue(PdfNative.isAvailable, "host pdf_render lib should be on java.library.path")+ assertEquals(0L, PdfNative.openDocument("not a pdf".toByteArray()))+ assertEquals(0, PdfNative.pdfPasswordState("not a pdf".toByteArray()))+ PdfNative.closeDocument(0L) // documented safe+ }++ @Test fun openRenderSearchAndSave() = runBlocking {+ val bytes = minimalPdf()+ assertEquals(0, PdfNative.pdfPasswordState(bytes))+ val handle = PdfNative.openDocument(bytes)+ assertTrue(handle != 0L)+ try {+ assertEquals(1, PdfNative.getPageCount(handle))+ val wire = PdfNative.renderPage(handle, 0)+ assertNotNull(wire)+ val page = SafePdfParser.parse(wire)+ assertEquals(612f, page.width); assertEquals(792f, page.height)+ assertTrue(page.primitives.isNotEmpty())+ assertNull(PdfNative.renderPage(handle, 99))+ val saved = PdfNative.saveDocument(handle)+ assertNotNull(saved); assertTrue(saved.isNotEmpty())+ val text = PdfNative.extractText(handle)+ assertTrue(text?.contains("Hello") == true, "extractText=$text")+ } finally { PdfNative.closeDocument(handle) }+ }++ @Test fun composeDocumentLifecycle() = runBlocking {+ val doc = ComposePdfDocument.create()+ try {+ assertEquals(0, doc.pageCount())+ assertEquals(0, doc.appendPdf("garbage".toByteArray()))+ assertEquals(1, doc.appendPdf(minimalPdf("One")))+ assertEquals(1, doc.appendPdf(minimalPdf("Two")))+ assertEquals(2, doc.pageCount())+ val page = doc.renderPage(0); assertNotNull(page); assertEquals(612f, page.width)+ assertNull(doc.renderPage(99))+ assertTrue(doc.movePage(0, 1))+ assertTrue(doc.removePage(1)); assertEquals(1, doc.pageCount())+ val saved = doc.save(); assertNotNull(saved)+ // Saved bytes reopen+ val h = PdfNative.openDocument(saved); assertTrue(h != 0L); PdfNative.closeDocument(h)+ } finally { doc.close(); doc.close() } // idempotent+ assertEquals(0, doc.pageCount())+ assertEquals(0, doc.appendPdf(minimalPdf()))+ assertNull(doc.save())+ }++ @Test fun encryptedSaveReopensWithPassword() = runBlocking {+ val handle = PdfNative.openDocument(minimalPdf())+ assertTrue(handle != 0L)+ try {+ val enc = PdfNative.saveEncrypted(handle, "userpw", "ownerpw")+ if (enc != null) {+ assertEquals(1, PdfNative.pdfPasswordState(enc))+ assertEquals(0L, PdfNative.openDocument(enc))+ val h2 = PdfNative.openDocumentWithPassword(enc, "userpw")+ assertTrue(h2 != 0L); PdfNative.closeDocument(h2)+ assertEquals(0L, PdfNative.openDocumentWithPassword(enc, "wrong"))+ }+ } finally { PdfNative.closeDocument(handle) }+ }+}
pdf/src/test/java/com/vayunmathur/pdf/util/RobolectricUtilTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/util/RobolectricUtilTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/util/RobolectricUtilTest.ktnew file mode 100644index 0000000000..7074486e4a--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/util/RobolectricUtilTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.pdf.util++import android.app.Application+import android.graphics.Bitmap+import android.graphics.Color+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.pdf.model.Quadrilateral+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class RobolectricUtilTest {+ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @Test fun pdfStateStoreRoundTripAndDefault() {+ val uri = Uri.parse("content://docs/report.pdf")+ assertEquals(0, PdfStateStore.restoreSafePage(app, uri))+ PdfStateStore.saveSafePage(app, uri, 7)+ assertEquals(7, PdfStateStore.restoreSafePage(app, uri))+ assertEquals(0, PdfStateStore.restoreSafePage(app, Uri.parse("content://docs/other.pdf")))+ PdfStateStore.saveSafePage(app, uri, 3)+ assertEquals(3, PdfStateStore.restoreSafePage(app, uri))+ }++ @Test fun pdfViewModelCapturedImageOps() {+ val vm = PdfViewModel(app)+ val u1 = Uri.parse("content://img/1"); val u2 = Uri.parse("content://img/2"); val u3 = Uri.parse("content://img/3")+ assertEquals(0, vm.addCapturedImage(u1)); assertEquals(1, vm.addCapturedImage(u2)); assertEquals(2, vm.addCapturedImage(u3))+ assertEquals(listOf(u1, u2, u3), vm.capturedImages.value.map { it.uri })+ vm.moveCapturedImage(0, 2)+ assertEquals(listOf(u2, u3, u1), vm.capturedImages.value.map { it.uri })+ vm.moveCapturedImage(9, 0); assertEquals(3, vm.capturedImages.value.size)+ vm.updateQuadrilateral(1, Quadrilateral.default())+ assertEquals(Quadrilateral.default(), vm.capturedImages.value[1].quadrilateral)+ assertNotNull(vm.capturedImages.value[1].cropRect)+ vm.updateQuadrilateral(99, Quadrilateral.default()) // no crash+ vm.removeCapturedImage(0); assertEquals(listOf(u3, u1), vm.capturedImages.value.map { it.uri })+ vm.removeCapturedImage(99); assertEquals(2, vm.capturedImages.value.size)+ vm.clearCapturedImages(); assertTrue(vm.capturedImages.value.isEmpty())+ }++ @Test fun capturedImageDefaultsUnderRobolectric() {+ val img = com.vayunmathur.pdf.model.CapturedImage(Uri.parse("content://x/1"))+ assertNull(img.cropRect); assertNull(img.quadrilateral)+ }++ @Test fun decodeRawBitmap() {+ val data = ByteArray(2 * 2 * 4) { 0xFF.toByte() }+ val bmp = SafePdfImages.decodeBitmap(2, 2, 0, data)+ assertNotNull(bmp); assertEquals(2, bmp.width); assertEquals(Color.WHITE, bmp.getPixel(0, 0))+ assertNull(SafePdfImages.decodeBitmap(2, 2, 0, ByteArray(4))) // too short+ assertNull(SafePdfImages.decodeBitmap(0, 2, 0, data))+ assertNull(SafePdfImages.decodeBitmap(2, 2, 99, data))+ }++ @Test fun autoFrameDetectorUniformBitmapReturnsNullOrQuadNoCrash() {+ val bmp = Bitmap.createBitmap(60, 60, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.WHITE) }+ // Uniform image has no document edges; detector should not crash+ AutoFrameDetector.detect(bmp)+ }++ @Test fun autoFrameDetectorFindsDarkDocumentOnWhite() {+ val bmp = Bitmap.createBitmap(80, 80, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.WHITE) }+ val canvas = android.graphics.Canvas(bmp)+ val paint = android.graphics.Paint().apply { color = Color.BLACK }+ canvas.drawRect(20f, 20f, 60f, 60f, paint)+ val quad = AutoFrameDetector.detect(bmp)+ // Black filled rect gives strong edges; if detected, corners near rect+ if (quad != null) {+ assertTrue(quad.topLeft.x < 0.5f && quad.bottomRight.x > 0.4f, quad.toString())+ }+ }+}
pdf/src/test/java/com/vayunmathur/pdf/util/SafePdfDocumentRobolectricTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/util/SafePdfDocumentRobolectricTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/util/SafePdfDocumentRobolectricTest.ktnew file mode 100644index 0000000000..eebdf830af--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/util/SafePdfDocumentRobolectricTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.pdf.util++import android.content.Context+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.GraphicsMode++@RunWith(RobolectricTestRunner::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class SafePdfDocumentRobolectricTest {+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun minimalPdf(text: String = "Hello"): ByteArray {+ val content = "BT /F1 24 Tf 100 700 Td ($text) 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 uriFor(bytes: ByteArray, name: String = "doc.pdf"): Uri {+ val f = File(ctx.cacheDir, name); f.writeBytes(bytes); return Uri.fromFile(f)+ }++ @Test fun openGarbageAndMissingReturnNull() { runBlocking {+ assertNull(SafePdfDocument.open(ctx, uriFor("nope".toByteArray(), "bad.pdf")))+ assertNull(SafePdfDocument.open(ctx, Uri.parse("content://nonexistent/x.pdf")))+ assertFalse(SafePdfDocument.looksLikePdf(ctx, uriFor("hello".toByteArray(), "bad2.pdf")))+ assertEquals(0, SafePdfDocument.passwordState(ctx, uriFor("nope".toByteArray(), "bad3.pdf")))+ } }++ @Test fun openRenderCacheAndListings() { runBlocking {+ val uri = uriFor(minimalPdf())+ assertTrue(SafePdfDocument.looksLikePdf(ctx, uri))+ assertEquals(0, SafePdfDocument.passwordState(ctx, uri))+ val doc = SafePdfDocument.open(ctx, uri); assertNotNull(doc)+ try {+ assertEquals(1, doc.pageCount)+ assertNull(doc.knownAspectRatio(0))+ val page = doc.renderPage(0); assertNotNull(page)+ assertEquals(612f, page.width); assertTrue(page.primitives.isNotEmpty())+ assertEquals(612f / 792f, doc.knownAspectRatio(0)!!, 0.001f)+ val cached = doc.renderPage(0); assertEquals(page, cached)+ val result = doc.renderPageResult(0); assertTrue(result is SafePdfDocument.PageLoad.Decoded)+ assertNull(doc.renderPage(99))+ assertTrue(doc.renderPageResult(99) is SafePdfDocument.PageLoad.Failed)+ assertTrue(doc.annotations(0).isEmpty()); assertTrue(doc.formFields(0).isEmpty())+ assertTrue(doc.links(0).isEmpty()); assertTrue(doc.outline().isEmpty())+ assertTrue(doc.search("").isEmpty()); assertTrue(doc.search(" ").isEmpty())+ val hits = doc.search("Hello"); assertTrue(hits.isNotEmpty(), "search hits=$hits")+ assertTrue(doc.search("hello", caseSensitive = true).isEmpty()) // case-sensitive: text is Hello? ci search above; cs lowercase should miss+ doc.prewarmSearch()+ assertTrue(doc.extractText()?.contains("Hello") == true)+ assertFalse(doc.hasRedactions())+ val extracted = doc.extractPage(0); assertNotNull(extracted); assertTrue(extracted.isNotEmpty())+ val saved = doc.save(); assertNotNull(saved)+ val compressed = doc.saveCompressed(); assertNotNull(compressed)+ } finally { doc.close() }+ } }++ @Test fun annotationEditsRoundTrip() { runBlocking {+ val doc = SafePdfDocument.open(ctx, uriFor(minimalPdf(), "edit.pdf")); assertNotNull(doc)+ try {+ val id = doc.addText(0, 100f, 600f, 320f, 630f, 0xFF0000FF.toInt(), 14f, "Note text")+ assertTrue(id != 0L, "addText id=$id")+ var annots = doc.annotations(0)+ assertTrue(annots.any { it.id == id }, "annots=$annots")+ assertTrue(doc.editText(0, id, "Edited"))+ assertTrue(doc.moveAnnotation(0, id, 110f, 610f, 330f, 640f))+ val dup = doc.duplicateAnnotation(0, id, 14f, -14f)+ if (dup != 0L) {+ assertTrue(doc.annotations(0).any { it.id == dup })+ assertTrue(doc.detachAnnotation(0, dup))+ assertTrue(doc.reattachAnnotation(0, dup))+ assertTrue(doc.deleteAnnotation(0, dup))+ }+ val hl = doc.addHighlight(0, 100f, 650f, 200f, 670f, 0xFFFFFF00.toInt())+ val markup = doc.addTextMarkup(0, 100f, 650f, 200f, 670f, 0xFF000000.toInt(), 0)+ val note = doc.addNote(0, 50f, 50f, 0xFF00FF00.toInt(), "sticky")+ val callout = doc.addCallout(0, 50f, 50f, 150f, 150f, 0xFF000000.toInt(), 14f, "call")+ val rect = doc.addRect(0, 10f, 10f, 100f, 100f, 0xFFFF0000.toInt(), 2f, false)+ val oval = doc.addOval(0, 10f, 10f, 100f, 100f, 0xFFFF0000.toInt(), 2f, true)+ val poly = doc.addPoly(0, floatArrayOf(0f, 0f, 50f, 50f, 100f, 0f), 0xFF000000.toInt(), 2f, false, false)+ val ink = doc.addInk(0, 0xFF000000.toInt(), 2f, floatArrayOf(0f, 0f, 10f, 10f, 20f, 20f))+ listOf(hl, markup, note, callout, rect, oval, poly, ink).forEach { assertTrue(it != 0L, "edit id=$it") }+ assertTrue(doc.annotations(0).size >= 8)+ // Form setters on non-widget ids should not crash (false expected)+ doc.setTextField(0, 999999L, "x"); doc.setCheckbox(0, 999999L, true); doc.setChoiceField(0, 999999L, "x")+ val red = doc.addRedaction(0, 90f, 590f, 330f, 640f)+ assertTrue(red != 0L)+ assertTrue(doc.hasRedactions())+ assertNotNull(doc.saveEncrypted("u", "o"))+ assertTrue(doc.flattenDocument() || true) // flatten may report false if nothing flattenable; call covered+ } finally { doc.close() }+ } }++ @Test fun redactionsApply() { runBlocking {+ val doc = SafePdfDocument.open(ctx, uriFor(minimalPdf(), "redact.pdf")); assertNotNull(doc)+ try {+ doc.addRedaction(0, 90f, 680f, 200f, 720f)+ doc.applyRedactions()+ assertNotNull(doc.save())+ } finally { doc.close() }+ } }+}
pdf/src/test/java/com/vayunmathur/pdf/util/SafePdfModelsTest.kt
diff --git a/pdf/src/test/java/com/vayunmathur/pdf/util/SafePdfModelsTest.kt b/pdf/src/test/java/com/vayunmathur/pdf/util/SafePdfModelsTest.ktnew file mode 100644index 0000000000..615032192e--- /dev/null+++ b/pdf/src/test/java/com/vayunmathur/pdf/util/SafePdfModelsTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.pdf.util++import androidx.compose.ui.geometry.Offset+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class SafePdfModelsTest {+ @Test fun blendModeFromCode() {+ assertEquals(BlendMode.Normal, BlendMode.fromCode(0))+ assertEquals(BlendMode.Multiply, BlendMode.fromCode(1))+ assertEquals(BlendMode.Luminosity, BlendMode.fromCode(15))+ assertEquals(BlendMode.Normal, BlendMode.fromCode(99))+ assertEquals(BlendMode.Normal, BlendMode.fromCode(-1))+ assertEquals(16, BlendMode.entries.size)+ BlendMode.entries.forEach { assertEquals(it, BlendMode.fromCode(it.code)) }+ }++ @Test fun textDefaultAdvanceIsHalfSizePerGlyph() {+ val t = PdfPrimitive.Text(origin = Offset(10f, 20f), size = 12f, color = 0xFF000000.toInt(), text = "abcd")+ assertEquals(24f, t.advance) // 12 * 0.5 * 4+ assertEquals(0, t.renderMode); assertEquals(BlendMode.Normal, t.blend); assertEquals(1f, t.hScale)+ assertFalse(t.isBold); assertFalse(t.outline)+ }++ @Test fun dataClassesHoldFields() {+ val page = SafePdfPage(612f, 792f, listOf(PdfPrimitive.ClipPop, PdfPrimitive.GroupPop))+ assertEquals(612f, page.width); assertEquals(2, page.primitives.size)+ val a = SafeAnnotation(7L, 2, 1f, 2f, 3f, 4f, 0xFF00FF00.toInt(), "hi")+ assertEquals(7L, a.id); assertEquals("hi", a.contents)+ val f = SafeFormField(3L, 1, 0f, 0f, 10f, 10f, "name", "val", true)+ assertTrue(f.checked); assertEquals("val", f.value)+ assertEquals(SafeOutlineItem(1, 5, "Ch1"), SafeOutlineItem(1, 5, "Ch1"))+ assertEquals(5, SafeSearchMatch(5, 0f, 0f, 1f, 1f).page)+ assertEquals(-1, SafeLink(0f, 0f, 1f, 1f, -1, "").destPage)+ }++ @Test fun strokePathDefaultsAndArrayEqualityNote() {+ val s = PdfPrimitive.StrokePath(0, 2f, floatArrayOf(3f, 2f), 0f, listOf(Offset.Zero))+ assertEquals(0, s.cap); assertEquals(10f, s.miter)+ assertTrue(s.dash.contentEquals(floatArrayOf(3f, 2f)))+ }++ @Test fun pathOps() {+ assertEquals(PathOp.Move(1f, 2f), PathOp.Move(1f, 2f))+ assertEquals(PathOp.Close, PathOp.Close)+ val c = PathOp.Cubic(1f, 2f, 3f, 4f, 5f, 6f); assertEquals(6f, c.y3)+ }++ @Test fun safePdfImagesBudgets() {+ assertTrue(SafePdfImages.badDimensions(0, 10)); assertTrue(SafePdfImages.badDimensions(10, -1))+ assertTrue(SafePdfImages.badDimensions(20001, 10)); assertFalse(SafePdfImages.badDimensions(100, 100))+ assertTrue(SafePdfImages.imageTooLarge(SafePdfImages.MAX_IMAGE_DATA_BYTES + 1))+ assertFalse(SafePdfImages.imageTooLarge(1024))+ assertEquals(1, SafePdfImages.sampleSizeFor(100, 100))+ assertEquals(2, SafePdfImages.sampleSizeFor(8000, 8000)) // 64M -> /4 =16M fits+ assertTrue(SafePdfImages.sampleSizeFor(20000, 20000) >= 4)+ }++ @Test fun scanFilterEntries() {+ assertEquals(listOf(ScanFilter.NONE, ScanFilter.GRAYSCALE, ScanFilter.BW, ScanFilter.CONTRAST), ScanFilter.entries.toList())+ }+}