Cotton code
471 lines · 20.7 KB · KotlinRaw
package com.cottondb.android.ui.locationsimport android.content.ComponentCallbacks2import android.content.Contextimport android.content.res.Configurationimport android.graphics.Bitmapimport android.graphics.Canvasimport android.graphics.Paintimport androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.gestures.awaitEachGestureimport androidx.compose.foundation.gestures.awaitFirstDownimport androidx.compose.ui.input.pointer.PointerEventPassimport androidx.compose.foundation.layout.BoxWithConstraintsimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberUpdatedStateimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.graphics.asImageBitmapimport androidx.compose.ui.graphics.asComposePathimport androidx.compose.ui.graphics.drawscope.translateimport androidx.compose.ui.graphics.drawscope.DrawScopeimport androidx.compose.ui.graphics.toArgbimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport androidx.compose.ui.viewinterop.AndroidViewimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.LifecycleEventObserverimport androidx.lifecycle.compose.LocalLifecycleOwnerimport com.cottondb.android.BuildConfigimport com.cottondb.android.day.locations.LocationMapFrameimport com.cottondb.android.day.locations.LocationPinimport com.cottondb.android.day.locations.LocationPointimport com.cottondb.android.day.locations.LocationPresentationFactsimport com.cottondb.android.day.locations.LocationSnapshotRequestimport com.cottondb.android.day.locations.PinnedLocationimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport java.util.LinkedHashMapimport kotlin.math.absimport org.maplibre.android.MapLibreimport org.maplibre.android.RenderingEngineimport org.maplibre.android.WellKnownTileServerimport org.maplibre.android.camera.CameraUpdateFactoryimport org.maplibre.android.geometry.LatLngimport org.maplibre.android.geometry.LatLngBoundsimport org.maplibre.android.maps.MapLibreMapimport org.maplibre.android.maps.MapViewimport org.maplibre.android.maps.Styleimport org.maplibre.android.snapshotter.MapSnapshotterimport org.maplibre.android.style.layers.Propertyimport org.maplibre.android.style.layers.PropertyFactory.iconAllowOverlapimport org.maplibre.android.style.layers.PropertyFactory.iconAnchorimport org.maplibre.android.style.layers.PropertyFactory.iconIgnorePlacementimport org.maplibre.android.style.layers.PropertyFactory.iconImageimport org.maplibre.android.style.layers.SymbolLayerimport org.maplibre.android.style.sources.GeoJsonSourceimport org.maplibre.geojson.Featureimport org.maplibre.geojson.FeatureCollectionimport org.maplibre.geojson.Pointprivate const val OPEN_FREE_MAP_LIBERTY = "https://tiles.openfreemap.org/styles/liberty"private const val PAPER_LONG_PRESS_MILLIS = 400Lprivate const val MAX_SNAPSHOT_PHYSICAL_SIDE = 1_024private const val SNAPSHOT_CACHE_ENTRIES = 8private 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`. */@Composablefun 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. */@Composablefun LocationPostcardMap(pin: PinnedLocation, modifier: Modifier = Modifier) {    if (BuildConfig.DEBUG) PaperLocationMap(pin, false, {}, modifier)    else TiledLocationPostcard(pin, modifier)}@Composableprivate 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())) }        }    }}@Composableprivate 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" },    )}@Composableprivate 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<Bitmap?>(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<Feature>()))        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<Feature>())))        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<LocationSnapshotRequest, Bitmap>(SNAPSHOT_CACHE_ENTRIES, .75f, true) {        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<LocationSnapshotRequest, Bitmap>?): 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() })    }}