package com.cottondb.android.ui.media import android.graphics.ImageDecoder import android.graphics.Bitmap import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.cottondb.android.design.CottonFonts import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette import com.cottondb.android.media.LocalMedia import com.cottondb.android.media.LocalMediaSource import java.text.BreakIterator import java.util.Locale import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.math.ceil import kotlin.math.max import kotlin.math.min /** A normalized, top-left-origin fractional crop matching Swift face `x/y/w/h` boxes. */ data class MediaImageCrop(val x: Double, val y: Double, val width: Double, val height: Double) { internal fun pixelRect(sourceWidth: Int, sourceHeight: Int): MediaImageCropRect? { if (sourceWidth <= 0 || sourceHeight <= 0 || !x.isFinite() || !y.isFinite() || !width.isFinite() || !height.isFinite() || width <= 0.0 || height <= 0.0 || x < 0.0 || y < 0.0 || x + width > 1.0 || y + height > 1.0) return null val left = kotlin.math.floor(x * sourceWidth).toInt() val top = kotlin.math.floor(y * sourceHeight).toInt() val right = kotlin.math.ceil(x * sourceWidth + width * sourceWidth).toInt() val bottom = kotlin.math.ceil(y * sourceHeight + height * sourceHeight).toInt() if (left < 0 || top < 0 || right > sourceWidth || bottom > sourceHeight || right <= left || bottom <= top) return null return MediaImageCropRect(left, top, right - left, bottom - top) } } internal data class MediaImageCropRect(val left: Int, val top: Int, val width: Int, val height: Int) /** The visible state of one local-only `read.mediaPath` request. */ sealed interface MediaImageState { data object Resolving : MediaImageState data class Ready(val bitmap: ImageBitmap) : MediaImageState data object Absent : MediaImageState data class Unavailable(val message: String) : MediaImageState } /** * Renders an existing local media file only. It calls [LocalMediaSource.local], never * `ensure`, so mounting a list cannot start downloads. [eventRevision] belongs * to the app host; it is a chance to re-ask after a data event, not a listener. */ @Composable fun MediaImage( key: String?, source: LocalMediaSource, eventRevision: Long, edge: Dp, modifier: Modifier = Modifier, description: String = "Image", crop: MediaImageCrop? = null, ) { val density = LocalDensity.current val targetPixels = remember(edge, density.density) { max(1, ceil(edge.value * density.density).toInt()) } val asked = key?.trim()?.takeIf(String::isNotEmpty) var slotKey by remember(source) { mutableStateOf?>(null) } var state by remember(source) { mutableStateOf(MediaImageState.Absent) } var generation by remember(source) { mutableLongStateOf(0L) } val requestedSlot = asked to crop LaunchedEffect(asked, crop, eventRevision, targetPixels, source) { val request = ++generation if (requestedSlot != slotKey) { slotKey = requestedSlot state = if (asked == null) MediaImageState.Absent else MediaImageState.Resolving } if (asked == null) return@LaunchedEffect val result = try { val local = withContext(Dispatchers.IO) { source.local(asked) } when (local) { is LocalMedia.Present -> decodeMedia(local, targetPixels, crop) LocalMedia.Absent -> MediaImageState.Absent } } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { MediaImageState.Unavailable(failure.message ?: "This image could not be opened.") } // A lazy item may be reused before its old local read or decode returns. if (generation == request && slotKey == requestedSlot) state = result } // Composition can paint once before the key effect clears state; never let // a bitmap for a previous lazy-list item appear in that intervening frame. val displayedState = if (slotKey == requestedSlot) state else { if (asked == null) MediaImageState.Absent else MediaImageState.Resolving } val stateDescription = when (displayedState) { MediaImageState.Resolving -> "$description is resolving locally" is MediaImageState.Ready -> description MediaImageState.Absent -> "$description is not on this phone yet" is MediaImageState.Unavailable -> "$description is unavailable: ${displayedState.message}" } Box( modifier.clip(RoundedCornerShape(3.dp)) .background(CottonPalette.ground) .semantics { contentDescription = stateDescription }, contentAlignment = Alignment.Center, ) { when (val shown = displayedState) { is MediaImageState.Ready -> Image( bitmap = shown.bitmap, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize(), ) MediaImageState.Resolving -> Unit MediaImageState.Absent -> Unit is MediaImageState.Unavailable -> Text( "Unavailable", style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary, textAlign = TextAlign.Center, ) } } } /** * The shared conversation/caller face. A key gets an empty print window until * its bytes are local. Only a missing key becomes Swift's typed initial card. */ @Composable fun CottonAvatar( seed: String, name: String, pictureKey: String?, source: LocalMediaSource, eventRevision: Long, size: Dp, modifier: Modifier = Modifier, ) { val presentKey = pictureKey?.trim()?.takeIf(String::isNotEmpty) if (presentKey != null) { MediaImage( key = presentKey, source = source, eventRevision = eventRevision, edge = size, modifier = modifier.size(size), description = "$name picture", ) } else { TypedInitialCard( initial = typedInitial(name), seed = seed, modifier = modifier.size(size), description = "$name initials", ) } } @Composable private fun TypedInitialCard( initial: String, seed: String, modifier: Modifier, description: String, ) = Box( modifier.clip(RoundedCornerShape(3.dp)) .background(CottonPalette.groundElevated) .semantics { contentDescription = description }, contentAlignment = Alignment.Center, ) { Text( initial, style = CottonTextStyles.body.copy(fontFamily = CottonFonts.type), color = CottonPalette.ink, textAlign = TextAlign.Center, ) } /** * ChatPicture.swift uses the first trimmed Swift `Character`; BreakIterator * gives Android's nearest grapheme boundary rather than a UTF-16 code unit. */ private fun typedInitial(name: String): String { val trimmed = name.trim() if (trimmed.isEmpty()) return "–" val iterator = BreakIterator.getCharacterInstance(Locale.getDefault()) iterator.setText(trimmed) val end = iterator.next() return trimmed.substring(0, end).uppercase(Locale.getDefault()) } internal suspend fun decodeMedia(local: LocalMedia.Present, edgePixels: Int, crop: MediaImageCrop?): MediaImageState = withContext(Dispatchers.IO) { try { val bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(local.file.file)) { decoder, info, _ -> val sourceWidth = info.size.width val sourceHeight = info.size.height // Crop needs the short edge at draw resolution. A panorama may // need a larger long edge, but never more than this tile budget. val cropRect = crop?.pixelRect(sourceWidth, sourceHeight) val shortEdge = cropRect?.let { min(it.width, it.height) } ?: min(sourceWidth, sourceHeight).coerceAtLeast(1) val requestedScale = edgePixels.toFloat() / shortEdge.toFloat() val requestedWidth = max(1, (sourceWidth * requestedScale).toInt()) val requestedHeight = max(1, (sourceHeight * requestedScale).toInt()) val pixelBudget = max(256 * 256, edgePixels * edgePixels * 8) val budgetScale = min(1f, kotlin.math.sqrt(pixelBudget.toFloat() / (requestedWidth.toLong() * requestedHeight).toFloat())) decoder.setTargetSize( max(1, (requestedWidth * budgetScale).toInt()), max(1, (requestedHeight * budgetScale).toInt()), ) decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE } val rect = crop?.pixelRect(bitmap.width, bitmap.height) val shown = rect?.let { Bitmap.createBitmap(bitmap, it.left, it.top, it.width, it.height) } ?: bitmap if (shown !== bitmap) bitmap.recycle() MediaImageState.Ready(shown.asImageBitmap()) } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { MediaImageState.Unavailable(failure.message ?: "This image could not be decoded.") } }