Modern Apps git

← Modern-Apps.git

translate: open shared or opened images in image translate (#846)

Commit
a4165a35d8614edf1106a4de5c89669758369d9a
Author
Vayun Mathur <[email protected]>
When
2026-11-12 17:32 UTC (23 days ago)
Parents
ba5ad5a
Request: #846 asks to OCR-translate an existing image, both by picking
it in the app and by sharing it / opening it with Translate from a
gallery or file manager.

Current state: the in-app picker already exists (ui/ImagePicker.kt,
EXIF-aware decode in ImageTranslateScreen, shipped 2026-10-23). But the
manifest only declared MAIN and PROCESS_TEXT, and MainActivity only
read PROCESS_TEXT text, so Translate never appeared in the Share sheet
or in "Open with" for images.

Changes:
- Manifest: ACTION_SEND and ACTION_VIEW intent filters for image/*.
  No new permissions; the sender's uri grant is all that is needed.
- platform/SharedImageIntent: takes EXTRA_STREAM for SEND and the data
  uri for VIEW. Only content:// uris are accepted (a file:// uri from
  another app is unreadable without storage access or points back into
  our own private files), a declared non-image MIME type is refused,
  and an intent re-delivered by a launch from Recents is ignored (its
  one-shot grant is gone and it was already handled).
- data/SharedImageCache: the shared uri's read grant is temporary,
  while the image route keeps its uri in navigation state and decodes
  it again whenever the screen is rebuilt. So the bytes are copied on
  arrival into cacheDir/shared_images and the screen is given the
  copy's file uri. The copy is capped at 32 MB, must sniff as JPEG,
  PNG, GIF, WebP, BMP or HEIF/AVIF (magic bytes, so a lying MIME type
  cannot get a non-image through), is written to a .part file and
  renamed only when complete, and every store prunes copies older than
  a day and keeps at most the newest five (never the one just written;
  stale .part leftovers are removed).
- TranslateViewModel.openSharedImage copies on Dispatchers.IO and
  publishes a SharedImageArrival (Ready with the file uri, or Rejected
  with the reason). Provider exceptions of any kind, including a
  revoked grant, read as "unreadable". Holding the arrival in the
  ViewModel lets it wait behind the model-download gate and survive an
  activity recreation.
- MainActivity handles the launch intent once per ViewModel (so a
  recreated activity does not open the image twice) and every
  onNewIntent. Navigation runs inside the same
  InitialModelDownloadChecker gate as the picker, so a share before the
  NLLB model is downloaded opens the image once it is installed.
- Navigation (via the new ui/SharedImageEffect): a ready image resets
  the stack to Text -> Image, the same shape the picker leaves, so Back
  lands on the text page. A rejected one stays put and shows "Couldn't
  read that image" or the new "That image is too large to translate"
  through AppMessages. The effect lives in its own file so
  Navigation.kt keeps only the nav graph (PackageStructure) and stays
  under detekt's LongMethod limit.

User-visible effect: Translate shows up in the Share sheet and the
"Open with" chooser for images. Choosing it opens the image translate
screen with OCR plates over the image; a non-image or an oversized
file gets a snackbar instead. The image keeps working after the sender
app is closed.

Verification: new unit tests SharedImageIntentTest (SEND/VIEW parsing,
missing payload, other actions, non-image types, non-content schemes,
Recents relaunch; ViewModel copy/reject/unreadable; MainActivity with
a SEND launch and a VIEW onNewIntent, each checked through the
activity's ViewModel) and SharedImageCacheTest (format sniffing,
byte-exact copy, short reads, size bound, failing stream, name
collisions, newest-N and max-age pruning, .part cleanup), plus two
Navigation tests in DbBackedPagesTest. Container build of
:translate: compileDevKotlin, lint and detekt pass with no findings
in touched files; testDevUnitTest runs 119 tests and all new ones
pass. DbBackedPagesTest "text page reuse loads the record pair" is a
pre-existing flake (fails intermittently on unmodified main too).
No preview or screenshot changes.

Diff

translate/src/main/AndroidManifest.xml
diff --git a/translate/src/main/AndroidManifest.xml b/translate/src/main/AndroidManifest.xmlindex 927d08aa51..1fc1a10df9 100644--- a/translate/src/main/AndroidManifest.xml+++ b/translate/src/main/AndroidManifest.xml@@ -43,6 +43,17 @@                 <category android:name="android.intent.category.DEFAULT" />                 <data android:mimeType="text/plain" />             </intent-filter>+            <!-- Share an image / open an image with Translate: OCR-translate it (#846). -->+            <intent-filter>+                <action android:name="android.intent.action.SEND" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="image/*" />+            </intent-filter>+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="image/*" />+            </intent-filter>         </activity>     </application> 
translate/src/main/java/com/vayunmathur/translate/MainActivity.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/MainActivity.kt b/translate/src/main/java/com/vayunmathur/translate/MainActivity.ktindex adb1d6dc45..1d475ecefc 100644--- a/translate/src/main/java/com/vayunmathur/translate/MainActivity.kt+++ b/translate/src/main/java/com/vayunmathur/translate/MainActivity.kt@@ -3,6 +3,8 @@ package com.vayunmathur.translate import android.content.Intent import androidx.activity.viewModels import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue import com.vayunmathur.library.downloadservice.InitialModelDownloadChecker import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle@@ -10,6 +12,7 @@ import com.vayunmathur.library.ui.MaActivity import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.translate.platform.MadladModel import com.vayunmathur.translate.platform.NllbModel+import com.vayunmathur.translate.platform.SharedImageIntent import com.vayunmathur.translate.platform.TranslateViewModel  class MainActivity : MaActivity() {@@ -19,19 +22,44 @@ class MainActivity : MaActivity() {     override fun onCreateBeforeContent() {         NetworkClient.init(this, TrustBundle.FIRST_PARTY)         initialText = processTextFromIntent(intent)+        // A recreated activity gets the same launch intent and the same ViewModel;+        // the image it carried was already opened the first time round.+        if (!viewModel.launchIntentHandled) {+            viewModel.launchIntentHandled = true+            handleImageIntent(intent)+        }+    }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        setIntent(intent)+        handleImageIntent(intent)     }      @Composable     override fun Content() {         val ds = DataStoreUtils.getInstance(this)+        val sharedImage by viewModel.sharedImage.collectAsState()         // NLLB only: MADLAD's files are skipped so the app does not download ~1 GB         // it cannot yet use (Q2_K decode is too slow on-device — see the bring-up         // notes). Re-add `+ MadladModel.FILES` when the engine selector lands.+        // A shared image waits in the ViewModel behind this same gate, exactly like+        // the in-app picker, which is only reachable once the model is installed.         InitialModelDownloadChecker(ds, NllbModel.FILES) {-            Navigation(viewModel, initialText)+            Navigation(+                viewModel = viewModel,+                initialText = initialText,+                sharedImage = sharedImage,+                onSharedImageConsumed = viewModel::consumeSharedImage,+            )         }     } +    /** Share (SEND) / Open with (VIEW) an image: copy it in and open image translate (#846). */+    private fun handleImageIntent(intent: Intent?) {+        SharedImageIntent.imageUri(intent)?.let(viewModel::openSharedImage)+    }+     private fun processTextFromIntent(intent: Intent?): String {         if (intent?.action != Intent.ACTION_PROCESS_TEXT) return ""         return intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString().orEmpty()
translate/src/main/java/com/vayunmathur/translate/Navigation.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/Navigation.kt b/translate/src/main/java/com/vayunmathur/translate/Navigation.ktindex e28f00ee74..9b8fd28a6d 100644--- a/translate/src/main/java/com/vayunmathur/translate/Navigation.kt+++ b/translate/src/main/java/com/vayunmathur/translate/Navigation.kt@@ -10,15 +10,27 @@ import com.vayunmathur.library.util.FullscreenPage import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.translate.data.TranslationRecord+import com.vayunmathur.translate.platform.SharedImageArrival import com.vayunmathur.translate.platform.TranslateViewModel import com.vayunmathur.translate.ui.CameraTranslateScreen import com.vayunmathur.translate.ui.HistoryPage import com.vayunmathur.translate.ui.ImageTranslatePage import com.vayunmathur.translate.ui.LanguagePickerPage+import com.vayunmathur.translate.ui.SharedImageEffect import com.vayunmathur.translate.ui.TextTranslatePage +/**+ * [sharedImage] is an image handed over by Share / Open with (#846); once acted on,+ * [onSharedImageConsumed] clears it. A ready image replaces the stack with+ * Text → Image, the same shape the in-app picker leaves, so Back lands on Text.+ */ @Composable-fun Navigation(viewModel: TranslateViewModel, initialText: String) {+fun Navigation(+    viewModel: TranslateViewModel,+    initialText: String,+    sharedImage: SharedImageArrival? = null,+    onSharedImageConsumed: () -> Unit = {},+) {     val backStack = rememberNavBackStack<Route>(Route.Text)     // A history row tapped for reuse: consumed once by the text page, which loads     // the record's source text and language pair, then the stack pops back to Text.@@ -76,4 +88,7 @@ fun Navigation(viewModel: TranslateViewModel, initialText: String) {             )         }     }+    // After MainNavigation so its message drain is already collecting when a+    // rejection is posted on the first frame.+    SharedImageEffect(sharedImage, backStack, onSharedImageConsumed) }
translate/src/main/java/com/vayunmathur/translate/data/SharedImageCache.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/data/SharedImageCache.kt b/translate/src/main/java/com/vayunmathur/translate/data/SharedImageCache.ktnew file mode 100644index 0000000000..2f37cdfb5e--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/data/SharedImageCache.kt@@ -0,0 +1,190 @@+package com.vayunmathur.translate.data++import com.vayunmathur.library.log.Log+import java.io.File+import java.io.IOException+import java.io.InputStream+import java.io.OutputStream++/**+ * App-private copies of images other apps hand us through Share / Open with (#846).+ *+ * The sender's read grant on a shared content uri is temporary, but the image+ * route keeps its uri in navigation state and decodes it again whenever the screen+ * is rebuilt. So the bytes are copied here on arrival and the screen is given the+ * copy's file uri, which stays readable for as long as the file exists.+ *+ * Copies are bounded ([maxBytes]), must sniff as an image format the platform+ * decoder understands, and are pruned on every store: anything older than+ * [maxAgeMs] goes, and only the newest [maxFiles] survive. The copy just written is+ * never pruned by its own store.+ */+class SharedImageCache(+    private val dir: File,+    private val maxBytes: Long = MAX_BYTES,+    private val maxFiles: Int = MAX_FILES,+    private val maxAgeMs: Long = MAX_AGE_MS,+    private val clock: () -> Long = System::currentTimeMillis,+) {++    /** Outcome of [store]. */+    sealed interface Result {+        /** The image now lives at [file]. */+        data class Cached(val file: File) : Result++        /** The content does not start like any supported image format. */+        data object NotAnImage : Result++        /** The content is larger than the cache accepts. */+        data object TooLarge : Result++        /** The content could not be read or the copy could not be written. */+        data object Unreadable : Result+    }++    /**+     * Copies [input] into the cache. Does not close [input]. Blocking: call off the+     * main thread.+     */+    fun store(input: InputStream): Result = synchronized(LOCK) {+        try {+            storeLocked(input)+        } catch (e: IOException) {+            Log.status(TAG, "shared image copy failed", e)+            Result.Unreadable+        }+    }++    private fun storeLocked(input: InputStream): Result {+        val header = ByteArray(HEADER_BYTES)+        val headerLen = readFully(input, header)+        val extension = sniffImageExtension(header, headerLen) ?: return Result.NotAnImage+        if (!dir.isDirectory && !dir.mkdirs()) return Result.Unreadable++        val now = clock()+        var target = File(dir, "$PREFIX$now.$extension")+        var suffix = 1+        while (target.exists()) {+            target = File(dir, "$PREFIX$now-$suffix.$extension")+            suffix+++        }+        val part = File(dir, target.name + PART_SUFFIX)+        val written = try {+            part.outputStream().use { out ->+                out.write(header, 0, headerLen)+                copyBounded(input, out, headerLen.toLong())+            }+        } catch (e: IOException) {+            part.delete()+            throw e+        }+        if (written > maxBytes) {+            part.delete()+            return Result.TooLarge+        }+        if (!part.renameTo(target)) {+            part.delete()+            return Result.Unreadable+        }+        target.setLastModified(now)+        cleanUpLocked(keep = target)+        return Result.Cached(target)+    }++    /**+     * Copies until EOF or until one byte past [maxBytes] has been seen, whichever is+     * first, and returns the total count including [already] header bytes.+     */+    private fun copyBounded(input: InputStream, out: OutputStream, already: Long): Long {+        var total = already+        val buffer = ByteArray(COPY_BUFFER)+        while (total <= maxBytes) {+            val n = input.read(buffer)+            if (n < 0) break+            out.write(buffer, 0, n)+            total += n+        }+        return total+    }++    /** Prunes stale copies (see the class doc). [keep] is never deleted. */+    fun cleanUp(keep: File? = null) = synchronized(LOCK) { cleanUpLocked(keep) }++    private fun cleanUpLocked(keep: File?) {+        val now = clock()+        val files = dir.listFiles()?.filter { it.isFile } ?: return+        // A leftover .part is a copy that died mid-write; nothing points at it.+        files.filter { it.name.endsWith(PART_SUFFIX) }.forEach { it.delete() }+        val copies = files+            .filter { it.name.startsWith(PREFIX) && !it.name.endsWith(PART_SUFFIX) }+            .sortedByDescending { it.lastModified() }+        copies.forEachIndexed { index, file ->+            if (file == keep) return@forEachIndexed+            val tooOld = now - file.lastModified() > maxAgeMs+            if (tooOld || index >= maxFiles) file.delete()+        }+    }++    /** Limits, naming and the format sniffer shared by every cache instance. */+    companion object {+        /** Subdirectory of the app cache dir holding the copies. */+        const val DIR_NAME = "shared_images"++        /** Largest image accepted (bytes). Big enough for any phone camera JPEG/HEIF. */+        const val MAX_BYTES: Long = 32L * 1024 * 1024++        /** Copies kept at most: enough for a few shares in a row plus back navigation. */+        const val MAX_FILES = 5++        /** Copies older than a day are dropped regardless of count. */+        const val MAX_AGE_MS: Long = 24L * 60 * 60 * 1000++        private const val TAG = "SharedImageCache"+        private const val PREFIX = "shared-"+        private const val PART_SUFFIX = ".part"+        private const val HEADER_BYTES = 16+        private const val COPY_BUFFER = 64 * 1024+        private val LOCK = Any()++        /** The cache under [cacheDir] (normally `Context.cacheDir`). */+        fun inCacheDir(cacheDir: File): SharedImageCache = SharedImageCache(File(cacheDir, DIR_NAME))++        /**+         * File extension for the image format [header] starts with, or null when it+         * is not one the platform decoder reads (JPEG, PNG, GIF, WebP, BMP, HEIF/AVIF).+         */+        @Suppress("MagicNumber", "CyclomaticComplexMethod", "ReturnCount")+        fun sniffImageExtension(header: ByteArray, length: Int = header.size): String? {+            fun at(i: Int) = if (i < length) header[i].toInt() and 0xFF else -1+            fun ascii(offset: Int, text: String) =+                text.indices.all { at(offset + it) == text[it].code }++            if (at(0) == 0xFF && at(1) == 0xD8 && at(2) == 0xFF) return "jpg"+            if (at(0) == 0x89 && ascii(1, "PNG\r\n")) return "png"+            if (ascii(0, "GIF87a") || ascii(0, "GIF89a")) return "gif"+            if (ascii(0, "RIFF") && ascii(8, "WEBP")) return "webp"+            if (ascii(0, "BM") && length >= 6) return "bmp"+            if (ascii(4, "ftyp")) {+                val brand = (8 until 12).map { at(it) }+                if (brand.any { it < 0 }) return null+                val text = String(CharArray(4) { brand[it].toChar() })+                return when (text) {+                    "heic", "heix", "hevc", "heim", "heis", "mif1", "msf1" -> "heic"+                    "avif", "avis" -> "avif"+                    else -> null+                }+            }+            return null+        }++        private fun readFully(input: InputStream, into: ByteArray): Int {+            var len = 0+            while (len < into.size) {+                val n = input.read(into, len, into.size - len)+                if (n < 0) break+                len += n+            }+            return len+        }+    }+}
translate/src/main/java/com/vayunmathur/translate/platform/SharedImageIntent.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/SharedImageIntent.kt b/translate/src/main/java/com/vayunmathur/translate/platform/SharedImageIntent.ktnew file mode 100644index 0000000000..8c5599514a--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/platform/SharedImageIntent.kt@@ -0,0 +1,37 @@+package com.vayunmathur.translate.platform++import android.content.ContentResolver+import android.content.Intent+import android.net.Uri+import androidx.core.content.IntentCompat++/**+ * Pulls the image out of a Share (ACTION_SEND) or Open with (ACTION_VIEW) intent+ * aimed at the translator (#846).+ *+ * Only `content://` uris are taken: those carry the sender's read grant, while a+ * `file://` uri from another app would either be unreadable without storage+ * permission or point back into this app's own private files. A declared MIME type,+ * when present, must be an image type; the cache sniffs the bytes as well, so a lying+ * type still cannot get a non-image through.+ *+ * An intent re-delivered by a launch from Recents is ignored: its one-shot grant is+ * long gone and the image was already handled when it first arrived.+ */+object SharedImageIntent {++    /** The image uri carried by [intent], or null when it carries none we accept. */+    fun imageUri(intent: Intent?): Uri? {+        if (intent == null) return null+        if (intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0) return null+        val uri = when (intent.action) {+            Intent.ACTION_SEND -> IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java)+            Intent.ACTION_VIEW -> intent.data+            else -> null+        } ?: return null+        if (uri.scheme != ContentResolver.SCHEME_CONTENT) return null+        val type = intent.type+        if (type != null && !type.startsWith("image/")) return null+        return uri+    }+}
translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.ktindex dd76ebbcc8..ecdd895c50 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/TranslateViewModel.kt@@ -1,5 +1,6 @@ package com.vayunmathur.translate.platform +import com.vayunmathur.translate.data.SharedImageCache import com.vayunmathur.translate.data.TranslateRepository import com.vayunmathur.translate.data.TranslateSettings import com.vayunmathur.translate.data.TranslationRecord@@ -7,15 +8,29 @@ import com.vayunmathur.translate.domain.Languages import com.vayunmathur.translate.domain.TranslationEngine  import android.app.Application+import android.net.Uri import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.log.Log import com.vayunmathur.library.ocr.OcrEngine+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/** An image handed over by Share / Open with, waiting for the navigation to open it. */+sealed interface SharedImageArrival {+    /** Copied into the app cache; [imageUri] is the copy's file uri. */+    data class Ready(val imageUri: String) : SharedImageArrival++    /** Not opened; [reason] says why, for the message shown instead. */+    data class Rejected(val reason: SharedImageCache.Result) : SharedImageArrival+}  /**  * Holds the shared engines (translation, OCR, TTS) and the persisted language@@ -60,6 +75,22 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) {         viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList(),     ) +    /**+     * The latest shared/opened image, held until [consumeSharedImage]. It lives here,+     * not in the activity, so it waits out the model-download gate and survives the+     * activity being recreated before the navigation has opened it.+     */+    private val _sharedImage = MutableStateFlow<SharedImageArrival?>(null)+    val sharedImage: StateFlow<SharedImageArrival?> = _sharedImage.asStateFlow()++    /**+     * Set once the activity has looked at its launch intent, so a recreated activity+     * (same intent, same ViewModel) does not open the image a second time.+     */+    var launchIntentHandled: Boolean = false++    private val sharedImageCache = SharedImageCache.inCacheDir(app.cacheDir)+     init {         viewModelScope.launch {             _sourceLang.value = settings.source()@@ -141,9 +172,47 @@ class TranslateViewModel(app: Application) : AndroidViewModel(app) {      fun stopSpeaking() = tts.stop() +    /**+     * Copies the image at [uri] (a sender's content uri, readable only for now) into+     * the app cache, then publishes it through [sharedImage]. See [SharedImageCache]+     * for why the copy is needed.+     */+    @Suppress("TooGenericExceptionCaught")+    fun openSharedImage(uri: Uri) {+        val resolver = getApplication<Application>().contentResolver+        viewModelScope.launch {+            val result = withContext(Dispatchers.IO) {+                try {+                    resolver.openInputStream(uri)?.use { sharedImageCache.store(it) }+                        ?: SharedImageCache.Result.Unreadable+                } catch (e: CancellationException) {+                    throw e+                } catch (e: Exception) {+                    // Another app's provider is on the other end: besides IOException+                    // and SecurityException (no or expired grant) it can throw any+                    // RuntimeException, all of which mean "couldn't read that image".+                    Log.status(TAG, "shared image unreadable", e)+                    SharedImageCache.Result.Unreadable+                }+            }+            _sharedImage.value = when (result) {+                is SharedImageCache.Result.Cached ->+                    SharedImageArrival.Ready(Uri.fromFile(result.file).toString())+                else -> SharedImageArrival.Rejected(result)+            }+        }+    }++    /** The navigation has acted on [sharedImage]; clear it so it is not acted on again. */+    fun consumeSharedImage() {+        _sharedImage.value = null+    }+     override fun onCleared() {         ocr.close()         (translator as? NllbTranslator)?.close()         tts.shutdown()     } }++private const val TAG = "TranslateViewModel"
translate/src/main/java/com/vayunmathur/translate/ui/SharedImageEffect.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/SharedImageEffect.kt b/translate/src/main/java/com/vayunmathur/translate/ui/SharedImageEffect.ktnew file mode 100644index 0000000000..f5e23df0f0--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/ui/SharedImageEffect.kt@@ -0,0 +1,34 @@+package com.vayunmathur.translate.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.translate.R+import com.vayunmathur.translate.Route+import com.vayunmathur.translate.data.SharedImageCache+import com.vayunmathur.translate.platform.SharedImageArrival++/**+ * Acts once on a shared/opened image: a ready one replaces the stack with+ * Text → Image, a rejected one posts why through [AppMessages].+ */+@Composable+internal fun SharedImageEffect(+    sharedImage: SharedImageArrival?,+    backStack: NavBackStack<Route>,+    onConsumed: () -> Unit,+) {+    val tooLarge = stringResource(R.string.shared_image_too_large)+    val unreadable = stringResource(R.string.could_not_read_image)+    LaunchedEffect(sharedImage) {+        when (val arrival = sharedImage ?: return@LaunchedEffect) {+            is SharedImageArrival.Ready -> backStack.reset(Route.Text, Route.Image(arrival.imageUri))+            is SharedImageArrival.Rejected -> AppMessages.show(+                if (arrival.reason == SharedImageCache.Result.TooLarge) tooLarge else unreadable,+            )+        }+        onConsumed()+    }+}
translate/src/main/res/values/strings.xml
diff --git a/translate/src/main/res/values/strings.xml b/translate/src/main/res/values/strings.xmlindex c6ee46a9c4..aa6024c220 100644--- a/translate/src/main/res/values/strings.xml+++ b/translate/src/main/res/values/strings.xml@@ -38,6 +38,8 @@     <string name="could_not_read_image">Couldn’t read that image</string>     <!-- Image translate: retry action after a failed image load. -->     <string name="pick_another_image">Pick another image</string>+    <!-- Image translate: an image shared to / opened with the app exceeds the size limit. -->+    <string name="shared_image_too_large">That image is too large to translate</string>     <!-- Placeholder in the translation output card before any input is typed. -->     <string name="translation_placeholder">Translation will appear here</string>     <!-- Mic status under the source field while audio is being captured. -->
translate/src/test/java/com/vayunmathur/translate/data/SharedImageCacheTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/data/SharedImageCacheTest.kt b/translate/src/test/java/com/vayunmathur/translate/data/SharedImageCacheTest.ktnew file mode 100644index 0000000000..2b4c70fa3f--- /dev/null+++ b/translate/src/test/java/com/vayunmathur/translate/data/SharedImageCacheTest.kt@@ -0,0 +1,188 @@+package com.vayunmathur.translate.data++import org.junit.Rule+import org.junit.rules.TemporaryFolder+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayInputStream+import java.io.File+import java.io.IOException+import java.io.InputStream+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Copy, bound, sniff and prune rules of the Share / Open with image cache (#846). */+@RunWith(RobolectricTestRunner::class)+class SharedImageCacheTest {++    @get:Rule+    val tmp = TemporaryFolder()++    private var now = 1_000_000_000_000L++    private fun cache(+        dir: File = File(tmp.root, SharedImageCache.DIR_NAME),+        maxBytes: Long = SharedImageCache.MAX_BYTES,+    ) = SharedImageCache(dir = dir, maxBytes = maxBytes, clock = { now })++    private val png = byteArrayOf(0x89.toByte(), 'P'.b, 'N'.b, 'G'.b, '\r'.b, '\n'.b, 0x1A, '\n'.b) ++        ByteArray(200) { it.toByte() }+    private val jpeg = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte(), 0xE0.toByte()) + ByteArray(64)++    // --- sniffing ---------------------------------------------------------------------++    @Test+    fun `sniffs supported image formats`() {+        assertEquals("png", SharedImageCache.sniffImageExtension(png))+        assertEquals("jpg", SharedImageCache.sniffImageExtension(jpeg))+        assertEquals("gif", SharedImageCache.sniffImageExtension("GIF89a......".toByteArray()))+        assertEquals("webp", SharedImageCache.sniffImageExtension("RIFF\u0000\u0000\u0000\u0000WEBPVP8 ".toByteArray()))+        assertEquals("heic", SharedImageCache.sniffImageExtension(ftyp("heic")))+        assertEquals("heic", SharedImageCache.sniffImageExtension(ftyp("mif1")))+        assertEquals("avif", SharedImageCache.sniffImageExtension(ftyp("avif")))+        assertEquals("bmp", SharedImageCache.sniffImageExtension("BM\u0000\u0000\u0000\u0000".toByteArray()))+    }++    @Test+    fun `rejects non images and truncated headers`() {+        assertNull(SharedImageCache.sniffImageExtension("%PDF-1.7\n".toByteArray()))+        assertNull(SharedImageCache.sniffImageExtension("hello world, plain text".toByteArray()))+        assertNull(SharedImageCache.sniffImageExtension(ftyp("isom"))) // MP4 video+        assertNull(SharedImageCache.sniffImageExtension(ByteArray(0)))+        // Header shorter than the signature: the length bound wins over the array size.+        assertNull(SharedImageCache.sniffImageExtension(jpeg, length = 2))+    }++    // --- store ------------------------------------------------------------------------++    @Test+    fun `stores an image byte for byte with its sniffed extension`() {+        val result = cache().store(ByteArrayInputStream(png))+        val cached = assertIs<SharedImageCache.Result.Cached>(result)+        assertTrue(cached.file.name.endsWith(".png"))+        assertEquals(SharedImageCache.DIR_NAME, cached.file.parentFile?.name)+        assertContentEquals(png, cached.file.readBytes())+    }++    @Test+    fun `stores an image delivered in short reads`() {+        val result = cache().store(TrickleStream(jpeg))+        val cached = assertIs<SharedImageCache.Result.Cached>(result)+        assertContentEquals(jpeg, cached.file.readBytes())+    }++    @Test+    fun `rejects a non image without writing anything`() {+        val dir = File(tmp.root, "nonimage")+        val result = cache(dir).store(ByteArrayInputStream("not an image at all".toByteArray()))+        assertEquals(SharedImageCache.Result.NotAnImage, result)+        assertFalse(dir.exists() && dir.list().orEmpty().isNotEmpty())+    }++    @Test+    fun `rejects an image over the size bound and leaves no partial file`() {+        val dir = File(tmp.root, "big")+        val big = png + ByteArray(1_000)+        assertEquals(SharedImageCache.Result.TooLarge, cache(dir, maxBytes = 500).store(ByteArrayInputStream(big)))+        assertTrue(dir.list().orEmpty().isEmpty())+        // Exactly at the bound is still accepted.+        val exact = png + ByteArray(500 - png.size)+        assertIs<SharedImageCache.Result.Cached>(cache(dir, maxBytes = 500).store(ByteArrayInputStream(exact)))+    }++    @Test+    fun `a failing stream is unreadable and leaves no partial file`() {+        val dir = File(tmp.root, "failing")+        val failing = object : InputStream() {+            private var served = 0+            override fun read(): Int {+                if (served >= png.size) throw IOException("grant revoked")+                return png[served++].toInt() and 0xFF+            }+        }+        assertEquals(SharedImageCache.Result.Unreadable, cache(dir).store(failing))+        assertTrue(dir.list().orEmpty().isEmpty())+    }++    @Test+    fun `two stores in the same millisecond get distinct files`() {+        val a = assertIs<SharedImageCache.Result.Cached>(cache().store(ByteArrayInputStream(png))).file+        val b = assertIs<SharedImageCache.Result.Cached>(cache().store(ByteArrayInputStream(jpeg))).file+        assertTrue(a != b)+        assertTrue(a.exists() && b.exists())+    }++    // --- cleanup ----------------------------------------------------------------------++    @Test+    fun `keeps only the newest copies`() {+        val c = cache()+        val files = (0 until SharedImageCache.MAX_FILES + 3).map {+            now += 1_000+            assertIs<SharedImageCache.Result.Cached>(c.store(ByteArrayInputStream(png))).file+        }+        val survivors = files.filter { it.exists() }+        assertEquals(files.takeLast(SharedImageCache.MAX_FILES), survivors)+    }++    @Test+    fun `drops copies older than a day but never the one just stored`() {+        val c = cache()+        val old = assertIs<SharedImageCache.Result.Cached>(c.store(ByteArrayInputStream(png))).file+        now += SharedImageCache.MAX_AGE_MS + 1+        val fresh = assertIs<SharedImageCache.Result.Cached>(c.store(ByteArrayInputStream(jpeg))).file+        assertFalse(old.exists())+        assertTrue(fresh.exists())+        // A copy named as keep survives cleanup even once stale; without it, it goes.+        now += SharedImageCache.MAX_AGE_MS * 2+        c.cleanUp(keep = fresh)+        assertTrue(fresh.exists())+        c.cleanUp()+        assertFalse(fresh.exists())+    }++    @Test+    fun `cleanup removes leftover partial copies and ignores foreign files`() {+        val dir = File(tmp.root, SharedImageCache.DIR_NAME).apply { mkdirs() }+        val part = File(dir, "shared-1.png.part").apply { writeBytes(png) }+        val foreign = File(dir, "notes.txt").apply { writeText("keep me") }+        cache(dir).cleanUp()+        assertFalse(part.exists())+        assertTrue(foreign.exists())+    }++    @Test+    fun `cleanup on a missing directory is a no-op`() {+        cache(File(tmp.root, "absent")).cleanUp()+    }++    @Test+    fun `inCacheDir nests under the given cache dir`() {+        val result = SharedImageCache.inCacheDir(tmp.root).store(ByteArrayInputStream(png))+        val cached = assertIs<SharedImageCache.Result.Cached>(result)+        assertEquals(File(tmp.root, SharedImageCache.DIR_NAME), cached.file.parentFile)+    }++    private fun ftyp(brand: String): ByteArray =+        byteArrayOf(0, 0, 0, 0x18) + "ftyp$brand".toByteArray() + ByteArray(8)++    private val Char.b: Byte get() = code.toByte()++    /** Serves at most three bytes per read, like a slow provider pipe. */+    private class TrickleStream(private val bytes: ByteArray) : InputStream() {+        private var pos = 0+        override fun read(): Int = if (pos < bytes.size) bytes[pos++].toInt() and 0xFF else -1+        override fun read(b: ByteArray, off: Int, len: Int): Int {+            if (pos >= bytes.size) return -1+            val n = minOf(len, 3, bytes.size - pos)+            System.arraycopy(bytes, pos, b, off, n)+            pos += n+            return n+        }+    }+}
translate/src/test/java/com/vayunmathur/translate/platform/SharedImageIntentTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/platform/SharedImageIntentTest.kt b/translate/src/test/java/com/vayunmathur/translate/platform/SharedImageIntentTest.ktnew file mode 100644index 0000000000..1b9bdbc167--- /dev/null+++ b/translate/src/test/java/com/vayunmathur/translate/platform/SharedImageIntentTest.kt@@ -0,0 +1,190 @@+package com.vayunmathur.translate.platform++import android.app.Application+import android.content.Context+import android.content.Intent+import android.net.Uri+import android.os.Looper+import androidx.lifecycle.ViewModelProvider+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.translate.MainActivity+import com.vayunmathur.translate.data.SharedImageCache+import org.junit.BeforeClass+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import java.io.ByteArrayInputStream+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Share / Open with intents reaching the image translate screen (#846). */+@RunWith(RobolectricTestRunner::class)+class SharedImageIntentTest {++    companion object {+        @BeforeClass+        @JvmStatic+        fun installFakeKeyStore() {+            if (java.security.Security.getProvider("AndroidKeyStore") !is FakeAndroidKeyStoreProvider) {+                runCatching { java.security.Security.removeProvider("AndroidKeyStore") }+                java.security.Security.insertProviderAt(FakeAndroidKeyStoreProvider(), 1)+            }+        }++        private val PNG = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A) + ByteArray(100)+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val image = Uri.parse("content://com.example.gallery/media/42")++    private fun send(uri: Uri?, type: String? = "image/jpeg") = Intent(Intent.ACTION_SEND).apply {+        if (uri != null) putExtra(Intent.EXTRA_STREAM, uri)+        this.type = type+    }++    private fun view(uri: Uri?, type: String? = "image/png") = Intent(Intent.ACTION_VIEW).apply {+        if (uri != null) setDataAndType(uri, type) else this.type = type+    }++    // --- parsing ----------------------------------------------------------------------++    @Test+    fun `send takes the stream extra`() {+        assertEquals(image, SharedImageIntent.imageUri(send(image)))+        assertEquals(image, SharedImageIntent.imageUri(send(image, type = "image/*")))+        assertEquals(image, SharedImageIntent.imageUri(send(image, type = null)))+    }++    @Test+    fun `view takes the data uri`() {+        assertEquals(image, SharedImageIntent.imageUri(view(image)))+        assertEquals(image, SharedImageIntent.imageUri(view(image, type = null)))+    }++    @Test+    fun `send without a stream or view without data carries nothing`() {+        assertNull(SharedImageIntent.imageUri(send(null)))+        assertNull(SharedImageIntent.imageUri(view(null)))+        // The data uri of a SEND is not its payload.+        assertNull(SharedImageIntent.imageUri(Intent(Intent.ACTION_SEND, image)))+    }++    @Test+    fun `other actions and a null intent carry nothing`() {+        assertNull(SharedImageIntent.imageUri(null))+        assertNull(SharedImageIntent.imageUri(Intent(Intent.ACTION_MAIN)))+        assertNull(+            SharedImageIntent.imageUri(+                Intent(Intent.ACTION_PROCESS_TEXT).putExtra(Intent.EXTRA_STREAM, image),+            ),+        )+        assertNull(SharedImageIntent.imageUri(Intent(Intent.ACTION_EDIT, image)))+    }++    @Test+    fun `non image types are rejected`() {+        assertNull(SharedImageIntent.imageUri(send(image, type = "text/plain")))+        assertNull(SharedImageIntent.imageUri(view(image, type = "application/pdf")))+        assertNull(SharedImageIntent.imageUri(send(image, type = "video/mp4")))+    }++    @Test+    fun `only content uris are accepted`() {+        val file = Uri.fromFile(File("/data/data/com.vayunmathur.translate/databases/history.db"))+        assertNull(SharedImageIntent.imageUri(send(file)))+        assertNull(SharedImageIntent.imageUri(view(file)))+        assertNull(SharedImageIntent.imageUri(view(Uri.parse("https://example.com/a.png"))))+    }++    @Test+    fun `a relaunch from recents is ignored`() {+        val intent = send(image).addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)+        assertNull(SharedImageIntent.imageUri(intent))+    }++    // --- ViewModel + activity ---------------------------------------------------------++    @Test+    fun `viewmodel copies a shared image into the cache and publishes its file uri`() {+        shadowOf(context.contentResolver).registerInputStream(image, ByteArrayInputStream(PNG))+        val vm = TranslateViewModel(ApplicationProvider.getApplicationContext<Application>())+        vm.openSharedImage(image)+        val arrival = assertIs<SharedImageArrival.Ready>(awaitArrival(vm))+        val uri = Uri.parse(arrival.imageUri)+        assertEquals("file", uri.scheme)+        val file = File(assertNotNull(uri.path))+        assertEquals(File(context.cacheDir, SharedImageCache.DIR_NAME), file.parentFile)+        assertTrue(file.readBytes().contentEquals(PNG))+        vm.consumeSharedImage()+        assertNull(vm.sharedImage.value)+    }++    @Test+    fun `viewmodel rejects shared content that is not an image`() {+        val pdf = Uri.parse("content://com.example.files/doc/7")+        shadowOf(context.contentResolver).registerInputStream(pdf, ByteArrayInputStream("%PDF-1.7".toByteArray()))+        val vm = TranslateViewModel(ApplicationProvider.getApplicationContext<Application>())+        vm.openSharedImage(pdf)+        val arrival = assertIs<SharedImageArrival.Rejected>(awaitArrival(vm))+        assertEquals(SharedImageCache.Result.NotAnImage, arrival.reason)+    }++    @Test+    fun `viewmodel reports an unreadable uri`() {+        val vm = TranslateViewModel(ApplicationProvider.getApplicationContext<Application>())+        vm.openSharedImage(Uri.parse("content://com.example.gone/never/registered"))+        val arrival = assertIs<SharedImageArrival.Rejected>(awaitArrival(vm))+        assertEquals(SharedImageCache.Result.Unreadable, arrival.reason)+    }++    @Test+    fun `main activity copies an image shared to it`() {+        val shared = Uri.parse("content://com.example.gallery/media/77")+        shadowOf(context.contentResolver).registerInputStream(shared, ByteArrayInputStream(PNG))+        val controller = Robolectric.buildActivity(MainActivity::class.java, send(shared, "image/png"))+            .create().start().resume()+        // The model is not downloaded here, so the navigation never consumes the+        // arrival: it waits in the activity's ViewModel, as it would behind the gate.+        val vm = ViewModelProvider(controller.get())[TranslateViewModel::class.java]+        assertIs<SharedImageArrival.Ready>(awaitArrival(vm))+        controller.pause().stop().destroy()+    }++    @Test+    fun `main activity handles an image delivered to a running instance`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java, Intent(Intent.ACTION_MAIN))+            .create().start().resume()+        val shared = Uri.parse("content://com.example.gallery/media/78")+        shadowOf(context.contentResolver).registerInputStream(shared, ByteArrayInputStream(PNG))+        val vm = ViewModelProvider(controller.get())[TranslateViewModel::class.java]+        assertNull(vm.sharedImage.value)+        controller.newIntent(view(shared, "image/png"))+        assertEquals(Intent.ACTION_VIEW, controller.get().intent.action)+        assertEquals(shared, SharedImageIntent.imageUri(controller.get().intent))+        val arrival = awaitArrival(vm)+        assertIs<SharedImageArrival.Ready>(arrival, "got $arrival")+        controller.pause().stop().destroy()+    }++    /** The copy runs on Dispatchers.IO and publishes on main: pump main until it lands. */+    private fun awaitArrival(vm: TranslateViewModel): SharedImageArrival? {+        awaitTrue { vm.sharedImage.value != null }+        return vm.sharedImage.value+    }++    private fun awaitTrue(condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline) {+            shadowOf(Looper.getMainLooper()).idle()+            if (condition()) return+            Thread.sleep(10)+        }+        throw AssertionError("condition not met within 10s")+    }+}
translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.kt b/translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.ktindex 78b3b262bc..521c626d61 100644--- a/translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.kt+++ b/translate/src/test/java/com/vayunmathur/translate/ui/DbBackedPagesTest.kt@@ -13,10 +13,12 @@ import androidx.compose.ui.test.performTextInput import androidx.test.core.app.ApplicationProvider import com.vayunmathur.translate.Navigation import com.vayunmathur.translate.data.PlainSqlCipherDriverShadow+import com.vayunmathur.translate.data.SharedImageCache import com.vayunmathur.translate.data.TranslateRepository import com.vayunmathur.translate.data.TranslationRecord import com.vayunmathur.translate.domain.Languages import com.vayunmathur.translate.platform.FakeAndroidKeyStoreProvider+import com.vayunmathur.translate.platform.SharedImageArrival import com.vayunmathur.translate.platform.TranslateViewModel import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking@@ -281,6 +283,44 @@ class DbBackedPagesTest {         assertEquals("en", viewModel.sourceLang.value)     } +    @Test+    fun `navigation opens a shared image on top of text`() {+        val viewModel = vm()+        idle()+        var consumed = false+        // A file uri that does not exist: the image route opens and shows its failure state.+        val missing = android.net.Uri.fromFile(java.io.File("/nonexistent/shared-1.png")).toString()+        rule.setContent {+            Navigation(+                viewModel = viewModel,+                initialText = "",+                sharedImage = SharedImageArrival.Ready(missing),+                onSharedImageConsumed = { consumed = true },+            )+        }+        rule.waitUntil(8_000) {+            rule.onAllNodesWithText("Pick another image").fetchSemanticsNodes().isNotEmpty()+        }+        assertTrue(consumed)+    }++    @Test+    fun `navigation stays on text for a rejected shared image`() {+        val viewModel = vm()+        idle()+        var consumed = false+        rule.setContent {+            Navigation(+                viewModel = viewModel,+                initialText = "",+                sharedImage = SharedImageArrival.Rejected(SharedImageCache.Result.TooLarge),+                onSharedImageConsumed = { consumed = true },+            )+        }+        rule.waitUntil(8_000) { consumed }+        rule.onNodeWithContentDescription("History").assertIsDisplayed()+    }+     @Test     fun `navigation language picker selects and returns`() {         val viewModel = vm()