package com.cottondb.android.ui.locations import android.content.ComponentCallbacks2 import android.content.Context import android.content.res.Configuration import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState 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.geometry.Offset import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asComposePath import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import com.cottondb.android.BuildConfig import com.cottondb.android.day.locations.LocationMapFrame import com.cottondb.android.day.locations.LocationPin import com.cottondb.android.day.locations.LocationPoint import com.cottondb.android.day.locations.LocationPresentationFacts import com.cottondb.android.day.locations.LocationSnapshotRequest import com.cottondb.android.day.locations.PinnedLocation import com.cottondb.android.design.CottonFonts import com.cottondb.android.design.CottonTextStyles import com.cottondb.android.generated.CottonPalette import java.util.LinkedHashMap import kotlin.math.abs import org.maplibre.android.MapLibre import org.maplibre.android.RenderingEngine import org.maplibre.android.WellKnownTileServer import org.maplibre.android.camera.CameraUpdateFactory import org.maplibre.android.geometry.LatLng import org.maplibre.android.geometry.LatLngBounds import org.maplibre.android.maps.MapLibreMap import org.maplibre.android.maps.MapView import org.maplibre.android.maps.Style import org.maplibre.android.snapshotter.MapSnapshotter import org.maplibre.android.style.layers.Property import org.maplibre.android.style.layers.PropertyFactory.iconAllowOverlap import org.maplibre.android.style.layers.PropertyFactory.iconAnchor import org.maplibre.android.style.layers.PropertyFactory.iconIgnorePlacement import org.maplibre.android.style.layers.PropertyFactory.iconImage import org.maplibre.android.style.layers.SymbolLayer import org.maplibre.android.style.sources.GeoJsonSource import org.maplibre.geojson.Feature import org.maplibre.geojson.FeatureCollection import org.maplibre.geojson.Point private const val OPEN_FREE_MAP_LIBERTY = "https://tiles.openfreemap.org/styles/liberty" private const val PAPER_LONG_PRESS_MILLIS = 400L private const val MAX_SNAPSHOT_PHYSICAL_SIDE = 1_024 private const val SNAPSHOT_CACHE_ENTRIES = 8 private const val PIN_IMAGE_ID = "cotton-location-pin" private const val PIN_SOURCE_ID = "cotton-location-pin-source" private const val PIN_LAYER_ID = "cotton-location-pin-layer" private fun initializeMapLibre(context: Context) { // minSdk 28 cannot promise Vulkan. The OpenGL-only artifact and this explicit // engine select the one renderer Cotton supports across its advertised ABIs. MapLibre.getInstance(context, "", WellKnownTileServer.MapLibre, RenderingEngine.Type.OPENGL) } /** * Detail's editable map. `LocationPin` is the existing core write DTO; a map * gesture can pass it directly to `LocationDetailModel.setPin`. */ @Composable fun LocationMiniMap( pin: PinnedLocation?, enabled: Boolean, onPin: (LocationPin) -> Unit, modifier: Modifier = Modifier, ) { Column(modifier = modifier) { if (BuildConfig.DEBUG) { PaperLocationMap(pin, enabled, onPin, Modifier.fillMaxWidth().height(220.dp)) } else { TiledLocationMiniMap(pin, enabled, onPin, Modifier.fillMaxWidth().height(220.dp)) } Text( text = if (pin == null) "no pin yet — long-press the map to drop one" else "long-press the map to move the pin", modifier = Modifier.padding(top = 8.dp), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkSecondary, ) } } /** A release postcard is a bounded, cancellable snapshot, never a list MapView. */ @Composable fun LocationPostcardMap(pin: PinnedLocation, modifier: Modifier = Modifier) { if (BuildConfig.DEBUG) PaperLocationMap(pin, false, {}, modifier) else TiledLocationPostcard(pin, modifier) } @Composable private fun PaperLocationMap( pin: PinnedLocation?, enabled: Boolean, onPin: (LocationPin) -> Unit, modifier: Modifier, ) { val frame = remember(pin) { LocationPresentationFacts.frame(pin?.let(::listOf).orEmpty()) } val currentOnPin by rememberUpdatedState(onPin) androidx.compose.foundation.Canvas( modifier = modifier .clip(RoundedCornerShape(3.dp)) .then( if (enabled) Modifier.pointerInput(frame, currentOnPin) { val maximumDistance = 10.dp.toPx() awaitEachGesture { val down = awaitFirstDown() down.consume() // Compose's ordinary tap detector permits in-bounds movement; // Swift's LongPressGesture cancels after 10 points in any direction. val canceled = withTimeoutOrNull(PAPER_LONG_PRESS_MILLIS) { var ended = false while (!ended) { val event = awaitPointerEvent(PointerEventPass.Main) val change = event.changes.singleOrNull { it.id == down.id } ended = event.changes.size != 1 || change == null || !change.pressed || change.isConsumed || (change.position - down.position).getDistance() > maximumDistance || change.position.x !in 0f..size.width.toFloat() || change.position.y !in 0f..size.height.toFloat() if (!ended) ended = awaitPointerEvent(PointerEventPass.Final).changes.any { it.isConsumed } } true } if (canceled == null) { currentEvent.changes.forEach { it.consume() } LocationPresentationFacts.unproject( LocationPoint(down.position.x.toDouble(), down.position.y.toDouble()), size.width.toDouble(), size.height.toDouble(), frame, )?.let { currentOnPin(LocationPin(it.latitude, it.longitude)) } do { val event = awaitPointerEvent(PointerEventPass.Main) event.changes.forEach { it.consume() } } while (event.changes.any { it.pressed }) } } } else Modifier, ) .semantics { contentDescription = if (enabled) { "Paper location map. Hold for 400 milliseconds to choose a location." } else "Paper location map" }, ) { drawPaperPlan(frame) pin?.let { value -> LocationPresentationFacts.project(value.latitude, value.longitude, size.width.toDouble(), size.height.toDouble(), frame) ?.let { point -> drawMapPin(point.x.toFloat(), point.y.toFloat(), (size.height * .14f).coerceIn(16.dp.toPx(), 30.dp.toPx())) } } } } @Composable private fun TiledLocationMiniMap( pin: PinnedLocation?, enabled: Boolean, onPin: (LocationPin) -> Unit, modifier: Modifier, ) { val context = LocalContext.current val lifecycle = LocalLifecycleOwner.current.lifecycle val currentPin by rememberUpdatedState(pin) val currentEnabled by rememberUpdatedState(enabled) val currentOnPin by rememberUpdatedState(onPin) val mapView = remember(context.applicationContext) { initializeMapLibre(context.applicationContext) ManagedLocationMapView(context) { latitude, longitude -> if (currentEnabled) currentOnPin(LocationPin(latitude, longitude)) } } DisposableEffect(mapView, lifecycle, context.applicationContext) { val observer = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_START -> mapView.start() Lifecycle.Event.ON_RESUME -> mapView.resume() Lifecycle.Event.ON_PAUSE -> mapView.pause() Lifecycle.Event.ON_STOP -> mapView.stop() Lifecycle.Event.ON_DESTROY -> mapView.destroy() else -> Unit } } val memory = object : ComponentCallbacks2 { override fun onConfigurationChanged(newConfig: Configuration) = Unit override fun onLowMemory() = mapView.lowMemory() override fun onTrimMemory(level: Int) { if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW) mapView.lowMemory() } } lifecycle.addObserver(observer) context.applicationContext.registerComponentCallbacks(memory) if (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) mapView.start() if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) mapView.resume() onDispose { context.applicationContext.unregisterComponentCallbacks(memory) lifecycle.removeObserver(observer) mapView.destroy() } } AndroidView( factory = { mapView }, update = { it.show(currentPin) }, modifier = modifier .clip(RoundedCornerShape(3.dp)) .semantics { contentDescription = "Location map" }, ) } @Composable private fun TiledLocationPostcard(pin: PinnedLocation, modifier: Modifier) { val context = LocalContext.current val density = LocalDensity.current BoxWithConstraints( modifier = modifier .clip(RoundedCornerShape(3.dp)) .background(CottonPalette.groundElevated) .semantics { contentDescription = "Location map preview" }, ) { val requested = remember(pin, maxWidth, maxHeight, density.density) { LocationPresentationFacts.snapshotRequest(pin, maxWidth.value.toDouble(), maxHeight.value.toDouble(), density.density.toDouble())?.bounded() } var bitmap by remember(requested) { mutableStateOf(null) } DisposableEffect(requested, context.applicationContext) { bitmap = null val request = requested if (request == null) return@DisposableEffect onDispose {} LocationSnapshotCache.get(request)?.let { cached -> bitmap = cached return@DisposableEffect onDispose {} } initializeMapLibre(context.applicationContext) var disposed = false val snapshotter = MapSnapshotter( context.applicationContext, MapSnapshotter.Options(request.width, request.height) .withStyleBuilder(Style.Builder().fromUri(OPEN_FREE_MAP_LIBERTY)) .withRegion(boundsFor(request.latitude, request.longitude, request.span)) .withAttribution(true) .withLogo(true) .withPixelRatio(request.scale.toFloat()), ) snapshotter.start( MapSnapshotter.SnapshotReadyCallback { snapshot -> if (!disposed) { val printed = snapshot.bitmap.copy(Bitmap.Config.ARGB_8888, true) val point = snapshot.pixelForLatLng(LatLng(request.latitude, request.longitude)) val pinImage = canonicalPinBitmap(context.applicationContext, 20f) Canvas(printed).drawBitmap(pinImage, point.x - pinImage.width / 2f, point.y - pinImage.height, null) pinImage.recycle() LocationSnapshotCache.put(request, printed) bitmap = printed } }, MapSnapshotter.ErrorHandler { if (!disposed) bitmap = null }, ) onDispose { disposed = true snapshotter.cancel() } } // Swift keeps the pin when tiles are unavailable: its coordinates remain a fact. // A successful image already carries its pin at the SDK-projected coordinate. bitmap?.let { image -> Image(image.asImageBitmap(), null, Modifier.fillMaxSize(), contentScale = ContentScale.Fit) } if (bitmap == null && requested != null) androidx.compose.foundation.Canvas(Modifier.fillMaxSize()) { drawMapPin(center.x, center.y, 20.dp.toPx()) } } } private class ManagedLocationMapView( context: Context, private val onLongPress: (Double, Double) -> Unit, ) : MapView(context) { private var map: MapLibreMap? = null private var wantedPin: PinnedLocation? = null private var shownPin: PinnedLocation? = null private var hasShown = false private var styleLoaded = false private var started = false private var resumed = false private var destroyed = false private val pinBitmap = canonicalPinBitmap(context) private val listener = MapLibreMap.OnMapLongClickListener { coordinate -> if (!destroyed) onLongPress(coordinate.latitude, coordinate.longitude) true } init { onCreate(null) getMapAsync { loaded -> if (destroyed) return@getMapAsync map = loaded loaded.addOnMapLongClickListener(listener) // Keep MapLibre's attribution and logo enabled. loaded.setStyle(Style.Builder().fromUri(OPEN_FREE_MAP_LIBERTY)) { style -> if (!destroyed) { installPinLayer(style) styleLoaded = true renderWantedPin() } } } } fun show(pin: PinnedLocation?) { if (hasShown && wantedPin == pin) return wantedPin = pin renderWantedPin() } fun start() { if (!destroyed && !started) { onStart(); started = true } } fun resume() { start(); if (!destroyed && !resumed) { onResume(); resumed = true } } fun pause() { if (!destroyed && resumed) { onPause(); resumed = false } } fun stop() { pause(); if (!destroyed && started) { onStop(); started = false } } fun lowMemory() { if (!destroyed) onLowMemory() } fun destroy() { if (destroyed) return stop() destroyed = true map?.removeOnMapLongClickListener(listener) map = null onDestroy() } private fun renderWantedPin() { val map = map ?: return if (destroyed || !styleLoaded) return if (hasShown && shownPin == wantedPin) return val style = map.style ?: return val source = style.getSource(PIN_SOURCE_ID) as? GeoJsonSource ?: return val pin = wantedPin if (pin == null) source.setGeoJson(FeatureCollection.fromFeatures(emptyList())) else source.setGeoJson(pinFeature(pin)) map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundsFor(pin), 0)) shownPin = wantedPin hasShown = true } private fun installPinLayer(style: Style) { style.addImage(PIN_IMAGE_ID, pinBitmap, false) style.addSource(GeoJsonSource(PIN_SOURCE_ID, FeatureCollection.fromFeatures(emptyList()))) style.addLayer( SymbolLayer(PIN_LAYER_ID, PIN_SOURCE_ID).withProperties( iconImage(PIN_IMAGE_ID), iconAnchor(Property.ICON_ANCHOR_BOTTOM), iconAllowOverlap(true), iconIgnorePlacement(true), ), ) } } private fun pinFeature(pin: PinnedLocation): Feature = Feature.fromGeometry( Point.fromLngLat(pin.longitude, pin.latitude), ) private object LocationSnapshotCache { private val images = object : LinkedHashMap(SNAPSHOT_CACHE_ENTRIES, .75f, true) { override fun removeEldestEntry(eldest: MutableMap.MutableEntry?): Boolean = size > SNAPSHOT_CACHE_ENTRIES } @Synchronized fun get(request: LocationSnapshotRequest): Bitmap? = images[request] @Synchronized fun put(request: LocationSnapshotRequest, bitmap: Bitmap) { images[request] = bitmap } } private fun LocationSnapshotRequest.bounded(): LocationSnapshotRequest { val maxLogical = (MAX_SNAPSHOT_PHYSICAL_SIDE / scale.coerceAtLeast(1)).coerceAtLeast(1) return copy(width = width.coerceIn(1, maxLogical), height = height.coerceIn(1, maxLogical)) } private fun boundsFor(pin: PinnedLocation?): LatLngBounds { val frame = LocationPresentationFacts.frame(pin?.let(::listOf).orEmpty()) return boundsFor(frame.latitude, frame.longitude, maxOf(frame.latitudeDelta, frame.longitudeDelta)) } private fun boundsFor(latitude: Double, longitude: Double, span: Double): LatLngBounds { val half = span / 2 return LatLngBounds.from( (latitude + half).coerceAtMost(90.0), (longitude + half).coerceAtMost(180.0), (latitude - half).coerceAtLeast(-90.0), (longitude - half).coerceAtLeast(-180.0), ) } private fun DrawScope.drawPaperPlan(frame: LocationMapFrame) { val ruling = 26.dp.toPx() fun anchor(degrees: Double) = ((abs(degrees) * 1_000.0 % 26.0) * density).toFloat() fun lines(vertical: Boolean, origin: Float) { var coordinate = origin % ruling var index = 0 while (coordinate < if (vertical) size.width else size.height) { val main = index % 4 == 0 val paint = CottonPalette.inkSecondary.copy(alpha = if (main) .85f else .45f) val width = if (main) 1.1.dp.toPx() else .6.dp.toPx() if (vertical) drawLine(paint, Offset(coordinate, 0f), Offset(coordinate, size.height), width) else drawLine(paint, Offset(0f, coordinate), Offset(size.width, coordinate), width) coordinate += ruling index += 1 } } lines(true, anchor(frame.longitude)) lines(false, anchor(frame.latitude)) } /** Swift PinMark: tangent flanks, a round head, and a transparent even-odd hole. */ private fun pinPath(width: Float, height: Float): android.graphics.Path { val radius = width / 2f return android.graphics.Path().apply { fillType = android.graphics.Path.FillType.EVEN_ODD moveTo(width / 2f, height) arcTo(android.graphics.RectF(0f, 0f, width, width), 150f, 240f, false) close() addCircle(radius, radius, radius * .38f, android.graphics.Path.Direction.CW) } } /** The tip, rather than the icon centre, is the exact persisted coordinate. */ private fun DrawScope.drawMapPin(x: Float, y: Float, height: Float) { val width = height * .7f translate(x - width / 2f, y - height) { drawPath(pinPath(width, height).asComposePath(), CottonPalette.accent) } } private fun canonicalPinBitmap(context: Context, heightDp: Float = 30f): Bitmap { val height = (heightDp * context.resources.displayMetrics.density).toInt().coerceAtLeast(1) val width = (height * .7f).toInt().coerceAtLeast(1) return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).also { bitmap -> Canvas(bitmap).drawPath(pinPath(width.toFloat(), height.toFloat()), Paint(Paint.ANTI_ALIAS_FLAG).apply { color = CottonPalette.accent.toArgb() }) } }