From e534cfa7b0122f45295f4c07bdb6d917bc5c7847 Mon Sep 17 00:00:00 2001 From: bleack Date: Sat, 28 Nov 2026 13:02:20 +0100 Subject: [PATCH] fix(planning): harden receipt camera capture and image decoding --- app/src/main/AndroidManifest.xml | 6 + app/src/main/java/com/example/MainActivity.kt | 3 +- .../com/example/ui/planning/PlanningScreen.kt | 42 ++- .../main/java/com/example/util/ImageUtils.kt | 249 ++++++++++++++++-- .../test/java/com/example/ImageUtilsTest.kt | 87 ++++++ 5 files changed, 355 insertions(+), 32 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c507ed0..3f0e394 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -12,6 +12,12 @@ + + + + + + (null) } var showReceiptSourceDialog by remember { mutableStateOf(false) } - var pendingCaptureUri by remember { mutableStateOf(null) } + var pendingCaptureUriString by rememberSaveable { mutableStateOf(null) } + val coroutineScope = rememberCoroutineScope() var shoppingItemForStockPrompt by remember { mutableStateOf(null) } var showPredictWeekSheet by rememberSaveable { mutableStateOf(false) } @@ -143,23 +148,38 @@ fun PlanningScreen( } } - // Camera capture via FileProvider URI + // Camera capture via FileProvider URI with explicit read/write grants + OEM fallback handling val takeReceiptPhotoLauncher = rememberLauncherForActivityResult( - contract = ActivityResultContracts.TakePicture() - ) { success -> - val captured = pendingCaptureUri - pendingCaptureUri = null - if (success && captured != null) { - onScanReceiptUri(captured) + contract = ActivityResultContracts.StartActivityForResult() + ) { result -> + val expectedUri = pendingCaptureUriString?.let(Uri::parse) + pendingCaptureUriString = null + if (result.resultCode == Activity.RESULT_OK) { + val resultData = result.data + coroutineScope.launch { + val resolvedUri = ImageUtils.resolveCapturedReceiptUri( + context = context, + expectedUri = expectedUri, + resultData = resultData + ) + if (resolvedUri != null) { + onScanReceiptUri(resolvedUri) + } else { + onShowMessage("Impossible de récupérer la photo prise. Réessayez ou choisissez depuis la galerie.") + } + } } } val launchCameraCapture = { try { val uri = ImageUtils.createReceiptCaptureUri(context) - pendingCaptureUri = uri - takeReceiptPhotoLauncher.launch(uri) - } catch (_: Exception) { + pendingCaptureUriString = uri.toString() + val captureIntent = ImageUtils.buildCameraCaptureIntent(context, uri) + takeReceiptPhotoLauncher.launch(captureIntent) + } catch (e: Exception) { + pendingCaptureUriString = null + Log.e("PlanningScreen", "Failed to launch camera capture", e) onShowMessage("Impossible d'ouvrir l'appareil photo") } } diff --git a/app/src/main/java/com/example/util/ImageUtils.kt b/app/src/main/java/com/example/util/ImageUtils.kt index cb9b6af..36a425e 100644 --- a/app/src/main/java/com/example/util/ImageUtils.kt +++ b/app/src/main/java/com/example/util/ImageUtils.kt @@ -1,12 +1,20 @@ package com.example.util +import android.content.ClipData import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.BitmapFactory +import android.graphics.ImageDecoder import android.net.Uri +import android.os.Build +import android.provider.MediaStore import android.util.Base64 import android.util.Log +import androidx.core.content.FileProvider import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import java.io.File import java.io.FileOutputStream @@ -152,36 +160,199 @@ object ImageUtils { /** * Creates a temporary FileProvider URI inside cacheDir/receipt_scans/ for capturing a * receipt photo with the device camera without needing external storage permissions. + * Pre-creates the empty file so OEM camera apps that inspect or open it with "rw" succeed. */ fun createReceiptCaptureUri(context: Context): Uri { - val dir = File(context.applicationContext.cacheDir, "receipt_scans").apply { + val appContext = context.applicationContext + val dir = File(appContext.cacheDir, "receipt_scans").apply { if (!exists()) mkdirs() } - val file = File(dir, "receipt_${System.currentTimeMillis()}.jpg") - return androidx.core.content.FileProvider.getUriForFile( - context.applicationContext, - "${context.applicationContext.packageName}.fileprovider", + // Clean up stale cached receipt captures (> 24h) + val cutoff = System.currentTimeMillis() - 24L * 60L * 60L * 1000L + dir.listFiles()?.forEach { existing -> + if (existing.isFile && existing.lastModified() < cutoff) { + existing.delete() + } + } + val file = File(dir, "receipt_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}.jpg") + if (!file.exists()) { + file.createNewFile() + } + return FileProvider.getUriForFile( + appContext, + "${appContext.packageName}.fileprovider", file ) } + /** + * Builds an ACTION_IMAGE_CAPTURE Intent with explicit ClipData and read/write URI + * permission grants for all resolved camera handlers (avoids silent 0-byte captures on OEM cameras). + */ + fun buildCameraCaptureIntent(context: Context, outputUri: Uri): Intent { + val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).apply { + putExtra(MediaStore.EXTRA_OUTPUT, outputUri) + addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION) + clipData = ClipData.newUri(context.contentResolver, "receipt_photo", outputUri) + } + val resolvedHandlers = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.queryIntentActivities( + intent, + PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY.toLong()) + ) + } else { + @Suppress("DEPRECATION") + context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) + } + resolvedHandlers.forEach { resolveInfo -> + val packageName = resolveInfo.activityInfo?.packageName ?: return@forEach + runCatching { + context.grantUriPermission( + packageName, + outputUri, + Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION + ) + } + } + return intent + } + + /** + * Resolves the usable receipt image URI after a camera capture returns RESULT_OK. + * Waits briefly for camera apps still flushing the file, and falls back to resultData.data + * or an inline thumbnail bitmap if an OEM camera ignored EXTRA_OUTPUT. + */ + suspend fun resolveCapturedReceiptUri( + context: Context, + expectedUri: Uri?, + resultData: Intent? + ): Uri? = withContext(Dispatchers.IO) { + if (expectedUri != null && waitForReadableBytes(context, expectedUri)) { + return@withContext expectedUri + } + + val dataUri = resultData?.data + if (dataUri != null && hasReadableBytes(context, dataUri)) { + Log.w(TAG, "Camera ignored EXTRA_OUTPUT; falling back to resultData.data") + return@withContext dataUri + } + + val inlineBitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + resultData?.getParcelableExtra("data", Bitmap::class.java) + } else { + @Suppress("DEPRECATION") + resultData?.getParcelableExtra("data") + } + if (inlineBitmap != null) { + Log.w(TAG, "Camera returned inline thumbnail bitmap; saving to receipt cache") + saveBitmapToReceiptCache(context, inlineBitmap)?.let { return@withContext it } + } + + expectedUri + } + + private fun saveBitmapToReceiptCache(context: Context, bitmap: Bitmap): Uri? { + return try { + val appContext = context.applicationContext + val dir = File(appContext.cacheDir, "receipt_scans").apply { + if (!exists()) mkdirs() + } + val file = File(dir, "receipt_fallback_${System.currentTimeMillis()}.jpg") + FileOutputStream(file).use { out -> + bitmap.compress(Bitmap.CompressFormat.JPEG, 92, out) + out.flush() + } + FileProvider.getUriForFile( + appContext, + "${appContext.packageName}.fileprovider", + file + ) + } catch (e: Exception) { + Log.e(TAG, "Failed to save fallback receipt bitmap: ${e.message}", e) + null + } + } + + private fun hasReadableBytes(context: Context, uri: Uri): Boolean { + return try { + context.contentResolver.openInputStream(uri)?.use { stream -> + stream.read() != -1 + } ?: false + } catch (_: Exception) { + false + } + } + + private suspend fun waitForReadableBytes( + context: Context, + uri: Uri, + maxAttempts: Int = 4, + delayMs: Long = 150L + ): Boolean { + repeat(maxAttempts) { attempt -> + if (hasReadableBytes(context, uri)) return true + if (attempt < maxAttempts - 1) delay(delayMs) + } + return false + } + /** * Decodes and scales an image URI to a crisp, memory-safe Bitmap (maxDimension px on longest edge) * suitable for multimodal Gemini Vision analysis (well under the 20MB inline payload limit). + * Uses ImageDecoder on API 28+ (supports HEIC/HEIF, Ultra HDR, and automatic EXIF rotation) + * with a resilient BitmapFactory fallback. */ suspend fun loadResizedBitmapForAi( context: Context, sourceUri: Uri, maxDimension: Int = 1440 ): Bitmap? = withContext(Dispatchers.IO) { + if (!waitForReadableBytes(context, sourceUri)) { + Log.e(TAG, "Receipt image URI has no readable bytes: $sourceUri") + return@withContext null + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + try { + val source = ImageDecoder.createSource(context.contentResolver, sourceUri) + val decoded = ImageDecoder.decodeBitmap(source) { decoder, info, _ -> + decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE + val width = info.size.width + val height = info.size.height + if (width > maxDimension || height > maxDimension) { + val ratio = minOf( + maxDimension.toFloat() / width, + maxDimension.toFloat() / height + ) + val targetW = (width * ratio).toInt().coerceAtLeast(1) + val targetH = (height * ratio).toInt().coerceAtLeast(1) + decoder.setTargetSize(targetW, targetH) + } + } + if (decoded.width > 0 && decoded.height > 0) { + return@withContext decoded + } + } catch (t: Throwable) { + Log.w(TAG, "ImageDecoder failed for $sourceUri, falling back to BitmapFactory: ${t.message}") + } + } + + decodeWithBitmapFactory(context, sourceUri, maxDimension) + } + + private fun decodeWithBitmapFactory( + context: Context, + sourceUri: Uri, + maxDimension: Int + ): Bitmap? { try { val boundsOptions = BitmapFactory.Options().apply { inJustDecodeBounds = true } context.contentResolver.openInputStream(sourceUri)?.use { stream -> BitmapFactory.decodeStream(stream, null, boundsOptions) - } ?: return@withContext null + } ?: return null if (boundsOptions.outWidth <= 0 || boundsOptions.outHeight <= 0) { - return@withContext null + return decodeFromFileDescriptor(context, sourceUri, maxDimension) } var inSampleSize = 1 @@ -198,24 +369,62 @@ object ImageUtils { } val decoded = context.contentResolver.openInputStream(sourceUri)?.use { stream -> BitmapFactory.decodeStream(stream, null, decodeOptions) - } ?: return@withContext null + } ?: return decodeFromFileDescriptor(context, sourceUri, maxDimension) - if (decoded.width > maxDimension || decoded.height > maxDimension) { - val ratio = minOf( - maxDimension.toFloat() / decoded.width, - maxDimension.toFloat() / decoded.height - ) - val targetW = (decoded.width * ratio).toInt().coerceAtLeast(1) - val targetH = (decoded.height * ratio).toInt().coerceAtLeast(1) - Bitmap.createScaledBitmap(decoded, targetW, targetH, true).also { - if (it != decoded) decoded.recycle() + return scaleBitmapIfNeeded(decoded, maxDimension) + } catch (e: Exception) { + Log.e(TAG, "Error loading bitmap for AI vision via stream: ${e.message}", e) + return decodeFromFileDescriptor(context, sourceUri, maxDimension) + } + } + + private fun decodeFromFileDescriptor( + context: Context, + sourceUri: Uri, + maxDimension: Int + ): Bitmap? { + return try { + context.contentResolver.openFileDescriptor(sourceUri, "r")?.use { pfd -> + val fd = pfd.fileDescriptor + val boundsOptions = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeFileDescriptor(fd, null, boundsOptions) + if (boundsOptions.outWidth <= 0 || boundsOptions.outHeight <= 0) { + return null } - } else { - decoded + var inSampleSize = 1 + if (boundsOptions.outHeight > maxDimension || boundsOptions.outWidth > maxDimension) { + val halfHeight = boundsOptions.outHeight / 2 + val halfWidth = boundsOptions.outWidth / 2 + while (halfHeight / inSampleSize >= maxDimension && halfWidth / inSampleSize >= maxDimension) { + inSampleSize *= 2 + } + } + val decodeOptions = BitmapFactory.Options().apply { + this.inSampleSize = inSampleSize + } + val decoded = BitmapFactory.decodeFileDescriptor(fd, null, decodeOptions) + ?: return null + scaleBitmapIfNeeded(decoded, maxDimension) } } catch (e: Exception) { - Log.e(TAG, "Error loading bitmap for AI vision: ${e.message}", e) + Log.e(TAG, "Error loading bitmap for AI vision via file descriptor: ${e.message}", e) null } } + + private fun scaleBitmapIfNeeded(decoded: Bitmap, maxDimension: Int): Bitmap { + return if (decoded.width > maxDimension || decoded.height > maxDimension) { + val ratio = minOf( + maxDimension.toFloat() / decoded.width, + maxDimension.toFloat() / decoded.height + ) + val targetW = (decoded.width * ratio).toInt().coerceAtLeast(1) + val targetH = (decoded.height * ratio).toInt().coerceAtLeast(1) + Bitmap.createScaledBitmap(decoded, targetW, targetH, true).also { + if (it != decoded) decoded.recycle() + } + } else { + decoded + } + } } diff --git a/app/src/test/java/com/example/ImageUtilsTest.kt b/app/src/test/java/com/example/ImageUtilsTest.kt index 4bf8592..d1c4c9f 100644 --- a/app/src/test/java/com/example/ImageUtilsTest.kt +++ b/app/src/test/java/com/example/ImageUtilsTest.kt @@ -1,9 +1,17 @@ package com.example import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import android.graphics.Color +import android.provider.MediaStore import androidx.test.core.app.ApplicationProvider import com.example.util.ImageUtils +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -11,6 +19,7 @@ import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.io.File +import java.io.FileOutputStream @RunWith(RobolectricTestRunner::class) @Config(sdk = [36]) @@ -21,6 +30,12 @@ class ImageUtilsTest { @Before fun setUp() { context = ApplicationProvider.getApplicationContext() + // Robolectric creates a fresh cacheDir per test, while FileProvider caches PathStrategy statically. + runCatching { + val cacheField = androidx.core.content.FileProvider::class.java.getDeclaredField("sCache") + cacheField.isAccessible = true + (cacheField.get(null) as? MutableMap<*, *>)?.clear() + } } @Test @@ -68,4 +83,76 @@ class ImageUtilsTest { assertFalse(ImageUtils.deletePhotoFile("/data/data/com.example/databases/secret.db")) assertFalse(ImageUtils.deletePhotoFile("../meal_photos/secret.db")) } + + @Test + fun createReceiptCaptureUri_preCreatesFileAndReturnsFileProviderUri() { + val uri = ImageUtils.createReceiptCaptureUri(context) + assertEquals("content", uri.scheme) + assertTrue(uri.authority.orEmpty().endsWith(".fileprovider")) + assertTrue(uri.toString().contains("receipt_scans")) + + val scanDir = File(context.cacheDir, "receipt_scans") + assertTrue(scanDir.exists()) + assertTrue(scanDir.listFiles()?.isNotEmpty() == true) + } + + @Test + fun buildCameraCaptureIntent_setsExtraOutputClipDataAndUriGrantFlags() { + val uri = ImageUtils.createReceiptCaptureUri(context) + val intent = ImageUtils.buildCameraCaptureIntent(context, uri) + + assertEquals(MediaStore.ACTION_IMAGE_CAPTURE, intent.action) + @Suppress("DEPRECATION") + assertEquals(uri, intent.getParcelableExtra(MediaStore.EXTRA_OUTPUT)) + assertNotNull(intent.clipData) + assertEquals(uri, intent.clipData?.getItemAt(0)?.uri) + assertTrue((intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) + assertTrue((intent.flags and Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) + } + + @Test + fun loadResizedBitmapForAi_decodesValidFileProviderJpeg() = runTest { + val uri = ImageUtils.createReceiptCaptureUri(context) + val bmp = Bitmap.createBitmap(400, 300, Bitmap.Config.ARGB_8888).apply { + eraseColor(Color.WHITE) + } + context.contentResolver.openOutputStream(uri)?.use { out -> + bmp.compress(Bitmap.CompressFormat.JPEG, 90, out) + } + bmp.recycle() + + val loaded = ImageUtils.loadResizedBitmapForAi(context, uri, maxDimension = 200) + assertNotNull(loaded) + assertTrue(loaded!!.width <= 200 && loaded.height <= 200) + loaded.recycle() + } + + @Test + fun loadResizedBitmapForAi_emptyFileReturnsNull() = runTest { + val uri = ImageUtils.createReceiptCaptureUri(context) + val loaded = ImageUtils.loadResizedBitmapForAi(context, uri, maxDimension = 200) + assertNull(loaded) + } + + @Test + fun resolveCapturedReceiptUri_fallsBackToInlineBitmapWhenExpectedFileIsEmpty() = runTest { + val emptyExpectedUri = ImageUtils.createReceiptCaptureUri(context) + val inlineBmp = Bitmap.createBitmap(120, 160, Bitmap.Config.ARGB_8888).apply { + eraseColor(Color.LTGRAY) + } + val resultIntent = Intent().putExtra("data", inlineBmp) + + val resolved = ImageUtils.resolveCapturedReceiptUri( + context = context, + expectedUri = emptyExpectedUri, + resultData = resultIntent + ) + inlineBmp.recycle() + + assertNotNull(resolved) + assertFalse("Should fall back away from empty expected URI", resolved == emptyExpectedUri) + val loaded = ImageUtils.loadResizedBitmapForAi(context, resolved!!, maxDimension = 200) + assertNotNull(loaded) + loaded!!.recycle() + } }