fix(planning): harden receipt camera capture and image decoding

This commit is contained in:
bleack committed 2026-11-28 13:02:20 +01:00
1 parent 8260dba5a5
commit e534cfa7b0
5 files changed
+355 -32

No files matched your search

+6
View File
@@ -12,6 +12,12 @@
<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
<application <application
android:allowBackup="true" android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"
@@ -46,6 +46,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
@@ -187,7 +188,7 @@ fun AppRoot(
} }
} }
var currentTab by remember { mutableStateOf(MainTab.JOURNAL) } var currentTab by rememberSaveable { mutableStateOf(MainTab.JOURNAL) }
// Meal entry sheet state (supports editing existing meal OR pre-filling a new meal from a recipe or plan) // Meal entry sheet state (supports editing existing meal OR pre-filling a new meal from a recipe or plan)
var showMealEntrySheet by remember { mutableStateOf(false) } var showMealEntrySheet by remember { mutableStateOf(false) }
@@ -1,8 +1,10 @@
package com.example.ui.planning package com.example.ui.planning
import android.Manifest import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.net.Uri import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
@@ -43,6 +45,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@@ -66,6 +69,7 @@ import com.example.data.model.ShoppingListItem
import com.example.data.model.StorageLocation import com.example.data.model.StorageLocation
import com.example.data.model.WeekPredictionUiState import com.example.data.model.WeekPredictionUiState
import com.example.util.ImageUtils import com.example.util.ImageUtils
import kotlinx.coroutines.launch
import java.time.LocalDate import java.time.LocalDate
enum class PlanningSubTab(val label: String) { enum class PlanningSubTab(val label: String) {
@@ -126,7 +130,8 @@ fun PlanningScreen(
var editingInventoryItem by remember { mutableStateOf<InventoryItem?>(null) } var editingInventoryItem by remember { mutableStateOf<InventoryItem?>(null) }
var showReceiptSourceDialog by remember { mutableStateOf(false) } var showReceiptSourceDialog by remember { mutableStateOf(false) }
var pendingCaptureUri by remember { mutableStateOf<Uri?>(null) } var pendingCaptureUriString by rememberSaveable { mutableStateOf<String?>(null) }
val coroutineScope = rememberCoroutineScope()
var shoppingItemForStockPrompt by remember { mutableStateOf<ShoppingListItem?>(null) } var shoppingItemForStockPrompt by remember { mutableStateOf<ShoppingListItem?>(null) }
var showPredictWeekSheet by rememberSaveable { mutableStateOf(false) } 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( val takeReceiptPhotoLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicture() contract = ActivityResultContracts.StartActivityForResult()
) { success -> ) { result ->
val captured = pendingCaptureUri val expectedUri = pendingCaptureUriString?.let(Uri::parse)
pendingCaptureUri = null pendingCaptureUriString = null
if (success && captured != null) { if (result.resultCode == Activity.RESULT_OK) {
onScanReceiptUri(captured) 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 = { val launchCameraCapture = {
try { try {
val uri = ImageUtils.createReceiptCaptureUri(context) val uri = ImageUtils.createReceiptCaptureUri(context)
pendingCaptureUri = uri pendingCaptureUriString = uri.toString()
takeReceiptPhotoLauncher.launch(uri) val captureIntent = ImageUtils.buildCameraCaptureIntent(context, uri)
} catch (_: Exception) { takeReceiptPhotoLauncher.launch(captureIntent)
} catch (e: Exception) {
pendingCaptureUriString = null
Log.e("PlanningScreen", "Failed to launch camera capture", e)
onShowMessage("Impossible d'ouvrir l'appareil photo") onShowMessage("Impossible d'ouvrir l'appareil photo")
} }
} }
+229 -20
View File
@@ -1,12 +1,20 @@
package com.example.util package com.example.util
import android.content.ClipData
import android.content.Context import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap import android.graphics.Bitmap
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Base64 import android.util.Base64
import android.util.Log import android.util.Log
import androidx.core.content.FileProvider
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.io.File import java.io.File
import java.io.FileOutputStream import java.io.FileOutputStream
@@ -152,36 +160,199 @@ object ImageUtils {
/** /**
* Creates a temporary FileProvider URI inside cacheDir/receipt_scans/ for capturing a * Creates a temporary FileProvider URI inside cacheDir/receipt_scans/ for capturing a
* receipt photo with the device camera without needing external storage permissions. * 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 { 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() if (!exists()) mkdirs()
} }
val file = File(dir, "receipt_${System.currentTimeMillis()}.jpg") // Clean up stale cached receipt captures (> 24h)
return androidx.core.content.FileProvider.getUriForFile( val cutoff = System.currentTimeMillis() - 24L * 60L * 60L * 1000L
context.applicationContext, dir.listFiles()?.forEach { existing ->
"${context.applicationContext.packageName}.fileprovider", 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 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<Bitmap>("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) * 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). * 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( suspend fun loadResizedBitmapForAi(
context: Context, context: Context,
sourceUri: Uri, sourceUri: Uri,
maxDimension: Int = 1440 maxDimension: Int = 1440
): Bitmap? = withContext(Dispatchers.IO) { ): 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 { try {
val boundsOptions = BitmapFactory.Options().apply { inJustDecodeBounds = true } val boundsOptions = BitmapFactory.Options().apply { inJustDecodeBounds = true }
context.contentResolver.openInputStream(sourceUri)?.use { stream -> context.contentResolver.openInputStream(sourceUri)?.use { stream ->
BitmapFactory.decodeStream(stream, null, boundsOptions) BitmapFactory.decodeStream(stream, null, boundsOptions)
} ?: return@withContext null } ?: return null
if (boundsOptions.outWidth <= 0 || boundsOptions.outHeight <= 0) { if (boundsOptions.outWidth <= 0 || boundsOptions.outHeight <= 0) {
return@withContext null return decodeFromFileDescriptor(context, sourceUri, maxDimension)
} }
var inSampleSize = 1 var inSampleSize = 1
@@ -198,24 +369,62 @@ object ImageUtils {
} }
val decoded = context.contentResolver.openInputStream(sourceUri)?.use { stream -> val decoded = context.contentResolver.openInputStream(sourceUri)?.use { stream ->
BitmapFactory.decodeStream(stream, null, decodeOptions) BitmapFactory.decodeStream(stream, null, decodeOptions)
} ?: return@withContext null } ?: return decodeFromFileDescriptor(context, sourceUri, maxDimension)
if (decoded.width > maxDimension || decoded.height > maxDimension) { return scaleBitmapIfNeeded(decoded, maxDimension)
val ratio = minOf( } catch (e: Exception) {
maxDimension.toFloat() / decoded.width, Log.e(TAG, "Error loading bitmap for AI vision via stream: ${e.message}", e)
maxDimension.toFloat() / decoded.height return decodeFromFileDescriptor(context, sourceUri, maxDimension)
) }
val targetW = (decoded.width * ratio).toInt().coerceAtLeast(1) }
val targetH = (decoded.height * ratio).toInt().coerceAtLeast(1)
Bitmap.createScaledBitmap(decoded, targetW, targetH, true).also { private fun decodeFromFileDescriptor(
if (it != decoded) decoded.recycle() 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 { var inSampleSize = 1
decoded 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) { } 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 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
}
}
} }
@@ -1,9 +1,17 @@
package com.example package com.example
import android.content.Context 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 androidx.test.core.app.ApplicationProvider
import com.example.util.ImageUtils import com.example.util.ImageUtils
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue import org.junit.Assert.assertTrue
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
@@ -11,6 +19,7 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config import org.robolectric.annotation.Config
import java.io.File import java.io.File
import java.io.FileOutputStream
@RunWith(RobolectricTestRunner::class) @RunWith(RobolectricTestRunner::class)
@Config(sdk = [36]) @Config(sdk = [36])
@@ -21,6 +30,12 @@ class ImageUtilsTest {
@Before @Before
fun setUp() { fun setUp() {
context = ApplicationProvider.getApplicationContext() 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 @Test
@@ -68,4 +83,76 @@ class ImageUtilsTest {
assertFalse(ImageUtils.deletePhotoFile("/data/data/com.example/databases/secret.db")) assertFalse(ImageUtils.deletePhotoFile("/data/data/com.example/databases/secret.db"))
assertFalse(ImageUtils.deletePhotoFile("../meal_photos/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()
}
} }