Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

fix: a scan keeps its photo when Android closes the app behind the camera (#38)

Josh3b8300a86cc0
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt
index cc7434c..822b3d2 100644
--- a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/AppViewModel.kt
@@ -32,6 +32,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import io.github.artcraftandroid.pdfcraft.PdfcraftApplication
import io.github.artcraftandroid.pdfcraft.R
@@ -59,8 +60,14 @@ data class PasswordRequest(val uri: Uri, val file: File, val wrong: Boolean)
/** Script alerts waiting at once, at most. */
private const val MAX_SCRIPT_ALERTS = 20
-/** The app's state: the engine, the open document, Home's lists, and the messages. */
-class AppViewModel(app: Application) : AndroidViewModel(app) {
+/** The saved-state key of the scan in progress. */
+private const val SCAN_STATE = "scan"
+
+/**
+ * The app's state: the engine, the open document, Home's lists, and the messages. [saved] keeps
+ * what must outlive Android closing the app in the background (the scan in progress).
+ */
+class AppViewModel(app: Application, private val saved: SavedStateHandle) : AndroidViewModel(app) {
private val application = app as PdfcraftApplication
val files = DocumentFiles(app)
val recents = RecentFiles(File(app.filesDir, "recent.json"))
@@ -1905,6 +1912,48 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
private var shotFile: File? = null
private var retakeIndex: Int? = null
+ // A scan Android closed the app in the middle of, while the camera app was in front, carries on
+ // when the photo comes back (#38): what it needs is kept in the saved state, read when it's saved.
+ private var scanRestoring: String? = null
+ private val scanRestore: kotlinx.coroutines.Job? = saved.get<android.os.Bundle>(SCAN_STATE)?.getString(SCAN_STATE)?.let { text ->
+ ScanSession.decode(text)?.let { restoreScan(text, it) }
+ }
+
+ init {
+ saved.setSavedStateProvider(SCAN_STATE) {
+ android.os.Bundle().apply { putString(SCAN_STATE, scanRestoring ?: scanSession()?.encode()) }
+ }
+ }
+
+ /** The scan in progress (or the Add image photo being taken); null when there is none. */
+ private fun scanSession(): ScanSession? {
+ if (shotFile == null && scanPages.isEmpty()) return null
+ return ScanSession(shotFile?.path, retakeIndex, imageShot, scanName, scanPages.map { ScanSession.Page(it.file.path, it.corners, it.found) })
+ }
+
+ private fun restoreScan(text: String, session: ScanSession): kotlinx.coroutines.Job {
+ scanRestoring = text
+ shotFile = session.shot?.let(::File)
+ retakeIndex = session.retake
+ imageShot = session.forImage
+ scanName = session.name
+ return viewModelScope.launch {
+ val pages = withContext(Dispatchers.IO) {
+ session.pages.mapNotNull { p -> File(p.path).let { f -> scanThumb(f)?.let { ScanPage(f, it, p.corners, p.found) } } }
+ }
+ scanPages.addAll(pages)
+ scanRestoring = null
+ // back on the Scan screen with its pages (with none, it would open the camera itself)
+ if (pages.isNotEmpty() && toolScreen == null) toolScreen = ToolScreen.Scan
+ }
+ }
+
+ /** A scanned photo, small and upright, for the Scan screen; null when it can't be read. */
+ private fun scanThumb(f: File): androidx.compose.ui.graphics.ImageBitmap? {
+ val opts = android.graphics.BitmapFactory.Options().apply { inSampleSize = 4 }
+ return android.graphics.BitmapFactory.decodeFile(f.absolutePath, opts)?.let { rotateForExif(f, it) }?.asImageBitmap()
+ }
+
/** Scan's pages go into this document at this (1-based) position instead of a new PDF. */
var insertScanAt: Pair<OpenDocument, Int>? = null
private var insertFileAt: Pair<OpenDocument, Int>? = null
@@ -2157,7 +2206,9 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
shotFile = null
if (imageShot) {
imageShot = false
- if (!ok || !f.isFile || f.length() == 0L) {
+ // after Android closed the app, the document the picture was for isn't open any more
+ if (!ok || !f.isFile || f.length() == 0L || imageFor == null) {
+ f.delete()
imageFor = null
imageAt = null
return
@@ -2177,14 +2228,16 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
return
}
if (!ok || !f.isFile || f.length() == 0L) {
- if (scanPages.isEmpty()) toolScreen = null
+ viewModelScope.launch {
+ scanRestore?.join()
+ if (scanPages.isEmpty()) toolScreen = null
+ }
return
}
viewModelScope.launch {
- val thumb = withContext(Dispatchers.IO) {
- val opts = android.graphics.BitmapFactory.Options().apply { inSampleSize = 4 }
- android.graphics.BitmapFactory.decodeFile(f.absolutePath, opts)?.let { rotateForExif(f, it) }?.asImageBitmap()
- } ?: return@launch
+ // the pages taken before Android closed the app come first
+ scanRestore?.join()
+ val thumb = withContext(Dispatchers.IO) { scanThumb(f) } ?: return@launch
val page = ScanPage(f, thumb)
val r = retakeIndex
retakeIndex = null
@@ -2193,7 +2246,8 @@ class AppViewModel(app: Application) : AndroidViewModel(app) {
if (toolScreen != ToolScreen.Scan) toolScreen = ToolScreen.Scan
// the document's edges in the photo, shown on the page and moved in Crop; the whole
// photo is kept when none are found
- val found = engine?.let { eng -> runCatching { eng.tool("photo_find_document", mapOf("path" to f.absolutePath)) }.getOrNull() }
+ // (the engine may still be starting when the app was closed and opened again)
+ val found = (engine ?: application.engine.await().getOrNull())?.let { eng -> runCatching { eng.tool("photo_find_document", mapOf("path" to f.absolutePath)) }.getOrNull() }
?.takeIf { it.optBoolean("found") }?.optJSONArray("corners")?.takeIf { it.length() == 8 }
?.let { a -> FloatArray(8) { a.optDouble(it).toFloat() } }
val at = scanPages.indexOfFirst { it.file == f }
diff --git a/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ScanSession.kt b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ScanSession.kt
new file mode 100644
index 0000000..cefb6ee
--- /dev/null
+++ b/apps/pdfcraft-android/android/app/src/main/java/io/github/artcraftandroid/pdfcraft/ui/ScanSession.kt
@@ -0,0 +1,67 @@
+package io.github.artcraftandroid.pdfcraft.ui
+
+/**
+ * A scan in progress as text, kept in the activity's saved state: Android often closes the app
+ * while the camera app is in front, and the photo it brings back belongs to this (#38).
+ *
+ * [shot] is the file the camera is writing, [retake] the page it replaces, [forImage] when the
+ * photo is for Add image rather than the scan.
+ */
+data class ScanSession(
+ val shot: String?,
+ val retake: Int?,
+ val forImage: Boolean,
+ val name: String,
+ val pages: List<Page>,
+) {
+ class Page(val path: String, val corners: FloatArray, val found: FloatArray?)
+
+ fun encode(): String = buildString {
+ append(HEADER).append('\n')
+ append("shot\t").append(shot.orEmpty()).append('\n')
+ append("retake\t").append(retake?.toString().orEmpty()).append('\n')
+ append("image\t").append(if (forImage) "1" else "0").append('\n')
+ append("name\t").append(name.replace('\n', ' ').replace('\t', ' ')).append('\n')
+ for (p in pages) {
+ append("page\t").append(p.path).append('\t').append(p.corners.joinToString(","))
+ append('\t').append(p.found?.joinToString(",").orEmpty()).append('\n')
+ }
+ }
+
+ companion object {
+ private const val HEADER = "pdfcraft-scan 1"
+
+ /** The session in [text]; null when there is none or it isn't one. A malformed page is left out. */
+ fun decode(text: String?): ScanSession? {
+ val lines = text?.lines() ?: return null
+ if (lines.firstOrNull() != HEADER) return null
+ var shot: String? = null
+ var retake: Int? = null
+ var forImage = false
+ var name = ""
+ val pages = mutableListOf<Page>()
+ for (line in lines.drop(1)) {
+ val parts = line.split('\t')
+ val value = parts.getOrNull(1).orEmpty()
+ when (parts.first()) {
+ "shot" -> shot = value.ifEmpty { null }
+ "retake" -> retake = value.toIntOrNull()
+ "image" -> forImage = value == "1"
+ "name" -> name = value
+ "page" -> {
+ val corners = corners(parts.getOrNull(2)) ?: continue
+ if (value.isNotEmpty()) pages += Page(value, corners, corners(parts.getOrNull(3)))
+ }
+ }
+ }
+ return ScanSession(shot, retake, forImage, name, pages)
+ }
+
+ // eight shares of the photo (x1, y1 … x4, y4), or null
+ private fun corners(text: String?): FloatArray? {
+ val values = text?.split(',')?.map { it.toFloatOrNull() ?: return null } ?: return null
+ if (values.size != 8 || values.any { !it.isFinite() }) return null
+ return values.toFloatArray()
+ }
+ }
+}
diff --git a/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ScanSessionTest.kt b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ScanSessionTest.kt
new file mode 100644
index 0000000..7c1f5d7
--- /dev/null
+++ b/apps/pdfcraft-android/android/app/src/test/java/io/github/artcraftandroid/pdfcraft/ui/ScanSessionTest.kt
@@ -0,0 +1,55 @@
+package io.github.artcraftandroid.pdfcraft.ui
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ScanSessionTest {
+ private val crop = floatArrayOf(0.1f, 0.1f, 0.9f, 0.12f, 0.88f, 0.95f, 0.08f, 0.9f)
+
+ @Test
+ fun aScanComesBackAsItWas() {
+ val s = ScanSession(
+ shot = "/cache/camera/scan-3.jpg", retake = 1, forImage = false, name = "Scan 2026-10-29",
+ pages = listOf(ScanSession.Page("/cache/camera/scan-1.jpg", crop, crop), ScanSession.Page("/cache/camera/scan-2.jpg", ScanPage.WHOLE, null)),
+ )
+ val back = ScanSession.decode(s.encode())!!
+ assertEquals("/cache/camera/scan-3.jpg", back.shot)
+ assertEquals(1, back.retake)
+ assertEquals(false, back.forImage)
+ assertEquals("Scan 2026-10-29", back.name)
+ assertEquals(listOf("/cache/camera/scan-1.jpg", "/cache/camera/scan-2.jpg"), back.pages.map { it.path })
+ assertArrayEquals(crop, back.pages[0].corners, 0f)
+ assertArrayEquals(crop, back.pages[0].found, 0f)
+ assertArrayEquals(ScanPage.WHOLE, back.pages[1].corners, 0f)
+ assertNull(back.pages[1].found)
+ }
+
+ @Test
+ fun aPhotoForAddImageWithNoPagesComesBack() {
+ val back = ScanSession.decode(ScanSession("/cache/camera/image-1.jpg", null, true, "", emptyList()).encode())!!
+ assertEquals("/cache/camera/image-1.jpg", back.shot)
+ assertNull(back.retake)
+ assertTrue(back.forImage)
+ assertTrue(back.pages.isEmpty())
+ }
+
+ @Test
+ fun aNameCannotBreakTheLines() {
+ val back = ScanSession.decode(ScanSession(null, null, false, "two\nlines\tand a tab", emptyList()).encode())!!
+ assertEquals("two lines and a tab", back.name)
+ assertNull(back.shot)
+ }
+
+ @Test
+ fun anythingElseIsNoScanAndABadPageIsLeftOut() {
+ assertNull(ScanSession.decode(null))
+ assertNull(ScanSession.decode(""))
+ assertNull(ScanSession.decode("something else\nshot\t/x.jpg"))
+ val back = ScanSession.decode("pdfcraft-scan 1\npage\t/a.jpg\t1,2,3\t\npage\t/b.jpg\t0,0,1,0,1,1,0,1\tNaN,0,1,0,1,1,0,1\npage\t\t0,0,1,0,1,1,0,1\t")!!
+ assertEquals(listOf("/b.jpg"), back.pages.map { it.path })
+ assertNull(back.pages[0].found)
+ }
+}