248 lines · 10.5 KB · KotlinRaw
package com.cottondb.android.ui.mediaimport android.graphics.ImageDecoderimport android.graphics.Bitmapimport androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableLongStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.ImageBitmapimport androidx.compose.ui.graphics.asImageBitmapimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.unit.Dpimport androidx.compose.ui.unit.dpimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.media.LocalMediaimport com.cottondb.android.media.LocalMediaSourceimport java.text.BreakIteratorimport java.util.Localeimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport kotlin.math.ceilimport kotlin.math.maximport 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. */@Composablefun 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<Pair<String?, MediaImageCrop?>?>(null) } var state by remember(source) { mutableStateOf<MediaImageState>(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. */@Composablefun 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", ) }}@Composableprivate 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.") } }