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

@@ -46,6 +46,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
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)
var showMealEntrySheet by remember { mutableStateOf(false) }
@@ -1,8 +1,10 @@
package com.example.ui.planning
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
@@ -43,6 +45,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
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.WeekPredictionUiState
import com.example.util.ImageUtils
import kotlinx.coroutines.launch
import java.time.LocalDate
enum class PlanningSubTab(val label: String) {
@@ -126,7 +130,8 @@ fun PlanningScreen(
var editingInventoryItem by remember { mutableStateOf<InventoryItem?>(null) }
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 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")
}
}
+229 -20
View File
@@ -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<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)
* 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
}
}
}