package com.cottondb.android.ui.photos import android.graphics.ImageDecoder import androidx.activity.compose.BackHandler import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf 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.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.unit.IntSize import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.semantics.Role 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 com.cottondb.android.design.CottonMetrics import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette import com.cottondb.android.media.LocalMediaFile import kotlin.math.max import kotlin.math.min import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /** * A full-size view of an already-local media file. The caller owns local lookup, * byte retrieval, absence text, and retries over the network; this composable * never has a media source and cannot start a download. */ @Composable fun LocalPhotoViewer(file: LocalMediaFile, caption: String?, onClose: () -> Unit) { var attempt by remember(file) { mutableIntStateOf(0) } var state by remember(file) { mutableStateOf(LocalPhotoViewerState.Loading) } var transform by remember(file) { mutableStateOf(PhotoViewerTransform()) } var viewport by remember { mutableStateOf(IntSize.Zero) } LaunchedEffect(file, attempt) { state = LocalPhotoViewerState.Loading state = try { LocalPhotoViewerState.Ready(decodeLocalPhoto(file, MAX_DECODE_EDGE)) } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { LocalPhotoViewerState.Error("This photo could not be opened.") } } BackHandler(onBack = onClose) Box(Modifier.fillMaxSize().background(CottonPalette.ground).safeDrawingPadding()) { when (val shown = state) { LocalPhotoViewerState.Loading -> ViewerText("Opening photo…") is LocalPhotoViewerState.Error -> Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally) { ViewerText(shown.message) ViewerButton("Try again", { attempt += 1 }) } is LocalPhotoViewerState.Ready -> Image( shown.bitmap, contentDescription = "Photo", contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize() .onSizeChanged { viewport = it } .pointerInput(file) { detectTransformGestures { _, pan, zoom, _ -> val next = transform.next(zoom, pan.x, pan.y) transform = next.copy( x = next.x.coerceIn(-viewport.width * (next.scale - 1) / 2, viewport.width * (next.scale - 1) / 2), y = next.y.coerceIn(-viewport.height * (next.scale - 1) / 2, viewport.height * (next.scale - 1) / 2), ) } } .graphicsLayer(scaleX = transform.scale, scaleY = transform.scale, translationX = transform.x, translationY = transform.y), ) } Column(Modifier.fillMaxSize().padding(horizontal = CottonMetrics.contentMargin, vertical = 12.dp)) { ViewerButton("Close", onClose, Modifier.align(Alignment.End)) androidx.compose.foundation.layout.Spacer(Modifier.weight(1f)) caption?.takeIf(String::isNotBlank)?.let { ViewerText(it, Modifier.align(Alignment.CenterHorizontally).background(CottonPalette.ground, RoundedCornerShape(8.dp)).padding(8.dp), TextAlign.Center) } } } } sealed interface LocalPhotoViewerState { data object Loading : LocalPhotoViewerState data class Ready(val bitmap: ImageBitmap) : LocalPhotoViewerState data class Error(val message: String) : LocalPhotoViewerState } /** Shared state math is pure so a gesture reset is guaranteed by `remember(file)`. */ data class PhotoViewerTransform(val scale: Float = 1f, val x: Float = 0f, val y: Float = 0f) { fun next(zoom: Float, panX: Float, panY: Float): PhotoViewerTransform { if (!zoom.isFinite() || !panX.isFinite() || !panY.isFinite()) return this val nextScale = (scale * zoom).coerceIn(1f, 6f) return if (nextScale <= 1.05f) PhotoViewerTransform() else PhotoViewerTransform(nextScale, x + panX, y + panY) } } private const val MAX_DECODE_EDGE = 4096 private suspend fun decodeLocalPhoto(file: LocalMediaFile, maxEdge: Int): ImageBitmap = withContext(Dispatchers.IO) { val bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(file.file)) { decoder, info, _ -> val sourceEdge = max(info.size.width, info.size.height).coerceAtLeast(1) val scale = min(1f, maxEdge.toFloat() / sourceEdge) decoder.setTargetSize(max(1, (info.size.width * scale).toInt()), max(1, (info.size.height * scale).toInt())) decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE } bitmap.asImageBitmap() } @Composable private fun ViewerText(value: String, modifier: Modifier = Modifier, align: TextAlign = TextAlign.Center) = androidx.compose.material3.Text(value, modifier.semantics { contentDescription = value }, style = CottonTextStyles.preview, color = CottonPalette.ink, textAlign = align) @Composable private fun ViewerButton(label: String, action: () -> Unit, modifier: Modifier = Modifier) = androidx.compose.material3.Text(label, modifier.heightIn(min = 44.dp).background(CottonPalette.ground, RoundedCornerShape(24.dp)).clickable(role = Role.Button, onClick = action).semantics { contentDescription = label }.padding(8.dp), style = CottonTextStyles.preview, color = CottonPalette.accent)